commit_id,project,commit_message,type,url,git_diff a467e88ae4c1dacb022288fe6d4805a7f719cd12,hadoop,YARN-1883. TestRMAdminService fails due to- inconsistent entries in UserGroups (Mit Desai via jeagles)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1582865 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 2a850e01e22d7..48fe1e261710a 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -33,6 +33,9 @@ Release 2.5.0 - UNRELEASED YARN-1136. Replace junit.framework.Assert with org.junit.Assert (Chen He via jeagles) + YARN-1883. TestRMAdminService fails due to inconsistent entries in + UserGroups (Mit Desai via jeagles) + OPTIMIZATIONS BUG FIXES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMAdminService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMAdminService.java index ab199d1d39ebe..32e78ebf1828a 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMAdminService.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMAdminService.java @@ -90,6 +90,9 @@ public void setup() throws IOException { fs.delete(tmpDir, true); fs.mkdirs(workingPath); fs.mkdirs(tmpDir); + + // reset the groups to what it default test settings + MockUnixGroupsMapping.resetGroups(); } @After @@ -785,12 +788,7 @@ private void uploadDefaultConfiguration() throws IOException { private static class MockUnixGroupsMapping implements GroupMappingServiceProvider { - @SuppressWarnings(""serial"") - private static List group = new ArrayList() {{ - add(""test_group_A""); - add(""test_group_B""); - add(""test_group_C""); - }}; + private static List group = new ArrayList(); @Override public List getGroups(String user) throws IOException { @@ -813,6 +811,13 @@ public static void updateGroups() { group.add(""test_group_E""); group.add(""test_group_F""); } + + public static void resetGroups() { + group.clear(); + group.add(""test_group_A""); + group.add(""test_group_B""); + group.add(""test_group_C""); + } } }" cce874510408305fed6e01ab5b70ab753f9ac693,ReactiveX-RxJava,Beef up UnsubscribeTester--,p,https://github.com/ReactiveX/RxJava,"diff --git a/rxjava-core/src/main/java/rx/subjects/RepeatSubject.java b/rxjava-core/src/main/java/rx/subjects/RepeatSubject.java index 1d0eb6f145..7ab3a9e2c7 100644 --- a/rxjava-core/src/main/java/rx/subjects/RepeatSubject.java +++ b/rxjava-core/src/main/java/rx/subjects/RepeatSubject.java @@ -2,10 +2,13 @@ import org.junit.Test; import org.mockito.Mockito; +import rx.Observable; import rx.Observer; import rx.Subscription; import rx.subscriptions.Subscriptions; import rx.testing.UnsubscribeTester; +import rx.util.functions.Action1; +import rx.util.functions.Func0; import rx.util.functions.Func1; import java.util.ArrayList; @@ -266,43 +269,38 @@ private void assertObservedUntilTwo(Observer aObserver) } @Test - public void testUnsubscribeFromOnNext() { - RepeatSubject subject = RepeatSubject.create(); - - UnsubscribeTester test1 = UnsubscribeTester.createOnNext(subject); - UnsubscribeTester test2 = UnsubscribeTester.createOnNext(subject); - - subject.onNext(""one""); - - test1.assertPassed(); - test2.assertPassed(); - } - - @Test - public void testUnsubscribeFromOnCompleted() { - RepeatSubject subject = RepeatSubject.create(); - - UnsubscribeTester test1 = UnsubscribeTester.createOnCompleted(subject); - UnsubscribeTester test2 = UnsubscribeTester.createOnCompleted(subject); - - subject.onCompleted(); - - test1.assertPassed(); - test2.assertPassed(); - } - - @Test - public void testUnsubscribeFromOnError() { - RepeatSubject subject = RepeatSubject.create(); - - UnsubscribeTester test1 = UnsubscribeTester.createOnError(subject); - UnsubscribeTester test2 = UnsubscribeTester.createOnError(subject); - - subject.onError(new Exception()); - - test1.assertPassed(); - test2.assertPassed(); + public void testUnsubscribe() + { + UnsubscribeTester.test(new Func0>() + { + @Override + public RepeatSubject call() + { + return RepeatSubject.create(); + } + }, new Action1>() + { + @Override + public void call(RepeatSubject repeatSubject) + { + repeatSubject.onCompleted(); + } + }, new Action1>() + { + @Override + public void call(RepeatSubject repeatSubject) + { + repeatSubject.onError(new Exception()); + } + }, new Action1>() + { + @Override + public void call(RepeatSubject repeatSubject) + { + repeatSubject.onNext(""one""); + } + } + ); } - } } diff --git a/rxjava-core/src/main/java/rx/testing/UnsubscribeTester.java b/rxjava-core/src/main/java/rx/testing/UnsubscribeTester.java index e1988c9093..08607f2734 100644 --- a/rxjava-core/src/main/java/rx/testing/UnsubscribeTester.java +++ b/rxjava-core/src/main/java/rx/testing/UnsubscribeTester.java @@ -3,6 +3,8 @@ import rx.Observable; import rx.Observer; import rx.Subscription; +import rx.util.functions.Action1; +import rx.util.functions.Func0; import static org.junit.Assert.assertTrue; @@ -12,7 +14,44 @@ public class UnsubscribeTester public UnsubscribeTester() {} - public static UnsubscribeTester createOnNext(Observable observable) + /** + * Tests the unsubscription semantics of an observable. + * + * @param provider Function that when called provides an instance of the observable being tested + * @param generateOnCompleted Causes an observer generated by @param provider to generate an onCompleted event. Null to not test onCompleted. + * @param generateOnError Causes an observer generated by @param provider to generate an onError event. Null to not test onError. + * @param generateOnNext Causes an observer generated by @param provider to generate an onNext event. Null to not test onNext. + * @param The type of object passed by the Observable + */ + public static > void test(Func0 provider, Action1 generateOnCompleted, Action1 generateOnError, Action1 generateOnNext) + { + if (generateOnCompleted != null) { + O observable = provider.call(); + UnsubscribeTester tester1 = createOnCompleted(observable); + UnsubscribeTester tester2 = createOnCompleted(observable); + generateOnCompleted.call(observable); + tester1.assertPassed(); + tester2.assertPassed(); + } + if (generateOnError != null) { + O observable = provider.call(); + UnsubscribeTester tester1 = createOnError(observable); + UnsubscribeTester tester2 = createOnError(observable); + generateOnError.call(observable); + tester1.assertPassed(); + tester2.assertPassed(); + } + if (generateOnNext != null) { + O observable = provider.call(); + UnsubscribeTester tester1 = createOnNext(observable); + UnsubscribeTester tester2 = createOnNext(observable); + generateOnNext.call(observable); + tester1.assertPassed(); + tester2.assertPassed(); + } + } + + private static UnsubscribeTester createOnCompleted(Observable observable) { final UnsubscribeTester test = new UnsubscribeTester(); test.setSubscription(observable.subscribe(new Observer() @@ -20,6 +59,7 @@ public static UnsubscribeTester createOnNext(Observable observable) @Override public void onCompleted() { + test.doUnsubscribe(); } @Override @@ -30,13 +70,12 @@ public void onError(Exception e) @Override public void onNext(T args) { - test.doUnsubscribe(); } })); return test; } - public static UnsubscribeTester createOnCompleted(Observable observable) + private static UnsubscribeTester createOnError(Observable observable) { final UnsubscribeTester test = new UnsubscribeTester(); test.setSubscription(observable.subscribe(new Observer() @@ -44,12 +83,12 @@ public static UnsubscribeTester createOnCompleted(Observable observable) @Override public void onCompleted() { - test.doUnsubscribe(); } @Override public void onError(Exception e) { + test.doUnsubscribe(); } @Override @@ -60,7 +99,7 @@ public void onNext(T args) return test; } - public static UnsubscribeTester createOnError(Observable observable) + private static UnsubscribeTester createOnNext(Observable observable) { final UnsubscribeTester test = new UnsubscribeTester(); test.setSubscription(observable.subscribe(new Observer() @@ -73,12 +112,12 @@ public void onCompleted() @Override public void onError(Exception e) { - test.doUnsubscribe(); } @Override public void onNext(T args) { + test.doUnsubscribe(); } })); return test; @@ -96,7 +135,7 @@ private void doUnsubscribe() subscription.unsubscribe(); } - public void assertPassed() + private void assertPassed() { assertTrue(""expected notification was received"", subscription == null); }" 55149154710b8bd1825442c308fb9b4b76054a63,camel,[CAMEL-1289] HeaderFilterStrategy - move from- Component to Endpoint (for JHC component)--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@743889 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/camel,"diff --git a/components/camel-jhc/src/main/java/org/apache/camel/component/jhc/JhcComponent.java b/components/camel-jhc/src/main/java/org/apache/camel/component/jhc/JhcComponent.java index c96d3aa2e2123..20234e7ead3b4 100644 --- a/components/camel-jhc/src/main/java/org/apache/camel/component/jhc/JhcComponent.java +++ b/components/camel-jhc/src/main/java/org/apache/camel/component/jhc/JhcComponent.java @@ -20,21 +20,17 @@ import java.util.Map; import org.apache.camel.Endpoint; -import org.apache.camel.HeaderFilterStrategyAware; import org.apache.camel.impl.DefaultComponent; -import org.apache.camel.spi.HeaderFilterStrategy; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; -public class JhcComponent extends DefaultComponent implements HeaderFilterStrategyAware { +public class JhcComponent extends DefaultComponent { private HttpParams params; - private HeaderFilterStrategy headerFilterStrategy; public JhcComponent() { - setHeaderFilterStrategy(new JhcHeaderFilterStrategy()); params = new BasicHttpParams() .setIntParameter(HttpConnectionParams.SO_TIMEOUT, 5000) @@ -57,11 +53,4 @@ protected Endpoint createEndpoint(String uri, String remaining, Map parameters) return new JhcEndpoint(uri, this, new URI(uri.substring(uri.indexOf(':') + 1))); } - public HeaderFilterStrategy getHeaderFilterStrategy() { - return headerFilterStrategy; - } - - public void setHeaderFilterStrategy(HeaderFilterStrategy strategy) { - headerFilterStrategy = strategy; - } } diff --git a/components/camel-jhc/src/main/java/org/apache/camel/component/jhc/JhcEndpoint.java b/components/camel-jhc/src/main/java/org/apache/camel/component/jhc/JhcEndpoint.java index 36131122d0836..6b9677b0a470b 100644 --- a/components/camel-jhc/src/main/java/org/apache/camel/component/jhc/JhcEndpoint.java +++ b/components/camel-jhc/src/main/java/org/apache/camel/component/jhc/JhcEndpoint.java @@ -19,7 +19,6 @@ import java.net.URI; import org.apache.camel.Consumer; -import org.apache.camel.HeaderFilterStrategyAware; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.impl.DefaultEndpoint; @@ -37,6 +36,7 @@ public class JhcEndpoint extends DefaultEndpoint { private HttpParams params; private URI httpUri; + private HeaderFilterStrategy headerFilterStrategy; public JhcEndpoint(String endpointUri, JhcComponent component, URI httpUri) { super(endpointUri, component); @@ -101,11 +101,12 @@ public Consumer createConsumer(Processor processor) throws Exception { return new JhcConsumer(this, processor); } + public void setHeaderFilterStrategy(HeaderFilterStrategy headerFilterStrategy) { + this.headerFilterStrategy = headerFilterStrategy; + } + public HeaderFilterStrategy getHeaderFilterStrategy() { - if (getComponent() instanceof HeaderFilterStrategyAware) { - return ((HeaderFilterStrategyAware)getComponent()).getHeaderFilterStrategy(); - } else { - return new JhcHeaderFilterStrategy(); - } + return headerFilterStrategy; } + }" d3fde78394aa28a344bc40f7724fc794c5682898,elasticsearch,Fix test failure.--,c,https://github.com/elastic/elasticsearch,"diff --git a/src/main/java/org/elasticsearch/search/fetch/FetchSubPhase.java b/src/main/java/org/elasticsearch/search/fetch/FetchSubPhase.java index d1ac77f254060..5f683ae4a3dcc 100644 --- a/src/main/java/org/elasticsearch/search/fetch/FetchSubPhase.java +++ b/src/main/java/org/elasticsearch/search/fetch/FetchSubPhase.java @@ -71,7 +71,9 @@ public AtomicReaderContext readerContext() { public IndexSearcher searcher() { if (atomicIndexSearcher == null) { - atomicIndexSearcher = new IndexSearcher(readerContext); + // Use the reader directly otherwise the IndexSearcher assertion will trip because it expects a top level + // reader context. + atomicIndexSearcher = new IndexSearcher(readerContext.reader()); } return atomicIndexSearcher; }" ec0e8cf1fb4f2b99d8677666df38234a621158d2,camel,Fixed test--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@962779 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/camel,"diff --git a/camel-core/src/test/java/org/apache/camel/processor/ShutdownCompleteAllTasksTest.java b/camel-core/src/test/java/org/apache/camel/processor/ShutdownCompleteAllTasksTest.java index d894f019a8a0d..511a8ad2eb90c 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/ShutdownCompleteAllTasksTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/ShutdownCompleteAllTasksTest.java @@ -45,19 +45,18 @@ public void testShutdownCompleteAllTasks() throws Exception { // give it 20 seconds to shutdown context.getShutdownStrategy().setTimeout(20); - // start route which will pickup the 5 files - context.startRoute(""route1""); - MockEndpoint bar = getMockEndpoint(""mock:bar""); bar.expectedMinimumMessageCount(1); assertMockEndpointsSatisfied(); + int batch = bar.getReceivedExchanges().get(0).getProperty(Exchange.BATCH_SIZE, int.class); + // shutdown during processing context.stop(); // should route all 5 - assertEquals(""Should complete all messages"", 5, bar.getReceivedCounter()); + assertEquals(""Should complete all messages"", batch, bar.getReceivedCounter()); } @Override @@ -66,7 +65,7 @@ protected RouteBuilder createRouteBuilder() throws Exception { @Override // START SNIPPET: e1 public void configure() throws Exception { - from(url).routeId(""route1"").noAutoStartup() + from(url) // let it complete all tasks during shutdown .shutdownRunningTask(ShutdownRunningTask.CompleteAllTasks) .delay(1000).to(""seda:foo""); diff --git a/camel-core/src/test/java/org/apache/camel/processor/ShutdownCompleteCurrentTaskOnlyTest.java b/camel-core/src/test/java/org/apache/camel/processor/ShutdownCompleteCurrentTaskOnlyTest.java index a06b8ada3ec05..880d61e4efa2c 100644 --- a/camel-core/src/test/java/org/apache/camel/processor/ShutdownCompleteCurrentTaskOnlyTest.java +++ b/camel-core/src/test/java/org/apache/camel/processor/ShutdownCompleteCurrentTaskOnlyTest.java @@ -45,9 +45,6 @@ public void testShutdownCompleteCurrentTaskOnly() throws Exception { // give it 20 seconds to shutdown context.getShutdownStrategy().setTimeout(20); - // start route which will pickup the 5 files - context.startRoute(""route1""); - MockEndpoint bar = getMockEndpoint(""mock:bar""); bar.expectedMinimumMessageCount(1); @@ -65,7 +62,7 @@ protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { - from(url).routeId(""route1"").noAutoStartup() + from(url) // let it complete only current task so we shutdown faster .shutdownRunningTask(ShutdownRunningTask.CompleteCurrentTaskOnly) .delay(1000).to(""seda:foo"");" 14bc62302f5db980c5c21bcb64af047ca68241b5,restlet-framework-java, - The CLAP connector didn't set the- expiration date based on its 'timeToLive' parameter. Reported by- Peter Becker.--,c,https://github.com/restlet/restlet-framework-java,"diff --git a/modules/org.restlet.example/src/org/restlet/example/jaxrs/GuardedExample.java b/modules/org.restlet.example/src/org/restlet/example/jaxrs/GuardedExample.java index 845d842af6..5d88624c9b 100644 --- a/modules/org.restlet.example/src/org/restlet/example/jaxrs/GuardedExample.java +++ b/modules/org.restlet.example/src/org/restlet/example/jaxrs/GuardedExample.java @@ -32,14 +32,14 @@ import org.restlet.Component; import org.restlet.Server; -import org.restlet.security.ChallengeGuard; -import org.restlet.security.MemoryRealm; -import org.restlet.security.Organization; -import org.restlet.security.User; import org.restlet.data.ChallengeScheme; import org.restlet.data.Protocol; import org.restlet.ext.jaxrs.JaxRsApplication; import org.restlet.ext.jaxrs.RoleChecker; +import org.restlet.security.ChallengeGuard; +import org.restlet.security.MemoryRealm; +import org.restlet.security.Organization; +import org.restlet.security.User; /** *

@@ -61,6 +61,7 @@ * @see ExampleServer * @see ExampleApplication */ +@SuppressWarnings(""deprecation"") public class GuardedExample { /** diff --git a/modules/org.restlet/src/org/restlet/engine/local/ClapClientHelper.java b/modules/org.restlet/src/org/restlet/engine/local/ClapClientHelper.java index 0a995072d9..282106ea99 100644 --- a/modules/org.restlet/src/org/restlet/engine/local/ClapClientHelper.java +++ b/modules/org.restlet/src/org/restlet/engine/local/ClapClientHelper.java @@ -168,6 +168,16 @@ protected void handleClassLoader(Request request, Response response, output.setIdentifier(request.getResourceRef()); output.setModificationDate(modificationDate); + // Update the expiration date + long timeToLive = getTimeToLive(); + if (timeToLive == 0) { + output.setExpirationDate(new Date()); + } else if (timeToLive > 0) { + output.setExpirationDate(new Date(System + .currentTimeMillis() + + (1000L * timeToLive))); + } + // Update the metadata based on file extensions final String name = path .substring(path.lastIndexOf('/') + 1); diff --git a/modules/org.restlet/src/org/restlet/engine/local/LocalClientHelper.java b/modules/org.restlet/src/org/restlet/engine/local/LocalClientHelper.java index c91301f4de..7f5f217b66 100644 --- a/modules/org.restlet/src/org/restlet/engine/local/LocalClientHelper.java +++ b/modules/org.restlet/src/org/restlet/engine/local/LocalClientHelper.java @@ -39,7 +39,6 @@ import org.restlet.representation.Variant; import org.restlet.service.MetadataService; - /** * Connector to the local resources accessible via file system, class loaders * and similar mechanisms. Here is the list of parameters that are supported: @@ -54,7 +53,8 @@ * timeToLive * int * 600 - * Time to live for a file representation before it expires (in seconds). + * Time to live for a representation before it expires (in seconds). If you + * set the value to '0', the representation will never expire. * * * defaultLanguage" 0f30646656428e3f2eb7c3a598fdf9cb1edee919,hbase,HBASE-7579 HTableDescriptor equals method fails- if results are returned in a different order; REVERT -- OVERCOMMITTED--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1471053 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/hbase,"diff --git a/bin/hbase-daemon.sh b/bin/hbase-daemon.sh index 91a15ec87d0d..e45054b5ac72 100755 --- a/bin/hbase-daemon.sh +++ b/bin/hbase-daemon.sh @@ -36,7 +36,7 @@ usage=""Usage: hbase-daemon.sh [--config ]\ (start|stop|restart|autorestart) \ - [--formatZK] [--formatFS] "" + "" # if no args specified, show usage if [ $# -le 1 ]; then @@ -57,19 +57,6 @@ shift command=$1 shift -if [ ""$startStop"" = ""start"" ];then - for i in 1 2 - do - if [ ""$1"" = ""--formatZK"" ];then - formatzk=$1 - shift - elif [ ""$1"" = ""--formatFS"" ];then - formatfs=$1 - shift - fi - done -fi - hbase_rotate_log () { log=$1; @@ -111,10 +98,6 @@ check_before_start(){ fi } -clear_hbase_data() { - $bin/hbase-cleanup.sh $formatzk $formatfs -} - wait_until_done () { p=$1 @@ -189,7 +172,6 @@ case $startStop in (start) check_before_start - clear_hbase_data nohup $thiscmd --config ""${HBASE_CONF_DIR}"" internal_start $command $args < /dev/null > /dev/null 2>&1 & ;; diff --git a/bin/start-hbase.sh b/bin/start-hbase.sh index 672a0e89ed01..8fca03ca7769 100755 --- a/bin/start-hbase.sh +++ b/bin/start-hbase.sh @@ -24,7 +24,7 @@ # Start hadoop hbase daemons. # Run this on master node. -usage=""Usage: start-hbase.sh [autorestart] [--formatZK] [--formatFS]"" +usage=""Usage: start-hbase.sh"" bin=`dirname ""${BASH_SOURCE-$0}""` bin=`cd ""$bin"">/dev/null; pwd` @@ -37,19 +37,12 @@ if [ $errCode -ne 0 ] then exit $errCode fi -for i in 1 2 3 -do - if [ ""$1"" = ""autorestart"" ];then - commandToRun=""autorestart"" - elif [ ""$1"" = ""--formatZK"" ];then - formatzk=$1 - elif [ ""$1"" = ""--formatFS"" ];then - formatfs=$1 - fi - shift -done -if [ ""$commandToRun"" = """" ];then + +if [ ""$1"" = ""autorestart"" ] +then + commandToRun=""autorestart"" +else commandToRun=""start"" fi @@ -59,10 +52,10 @@ distMode=`$bin/hbase --config ""$HBASE_CONF_DIR"" org.apache.hadoop.hbase.util.HBa if [ ""$distMode"" == 'false' ] then - ""$bin""/hbase-daemon.sh $commandToRun master $formatzk $formatfs + ""$bin""/hbase-daemon.sh $commandToRun master else ""$bin""/hbase-daemons.sh --config ""${HBASE_CONF_DIR}"" $commandToRun zookeeper - ""$bin""/hbase-daemon.sh --config ""${HBASE_CONF_DIR}"" $commandToRun master $formatzk $formatfs + ""$bin""/hbase-daemon.sh --config ""${HBASE_CONF_DIR}"" $commandToRun master ""$bin""/hbase-daemons.sh --config ""${HBASE_CONF_DIR}"" \ --hosts ""${HBASE_REGIONSERVERS}"" $commandToRun regionserver ""$bin""/hbase-daemons.sh --config ""${HBASE_CONF_DIR}"" \ diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/HColumnDescriptor.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/HColumnDescriptor.java index 4e2c2a829429..ecb0826b5ed8 100644 --- a/hbase-client/src/main/java/org/apache/hadoop/hbase/HColumnDescriptor.java +++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/HColumnDescriptor.java @@ -1125,10 +1125,12 @@ public void write(DataOutput out) throws IOException { public int compareTo(HColumnDescriptor o) { int result = Bytes.compareTo(this.name, o.getName()); if (result == 0) { - // The maps interface should compare values, even if they're in different orders - if (!this.values.equals(o.values)) { - return 1; - } + // punt on comparison for ordering, just calculate difference + result = this.values.hashCode() - o.values.hashCode(); + if (result < 0) + result = -1; + else if (result > 0) + result = 1; } if (result == 0) { result = this.configuration.hashCode() - o.configuration.hashCode(); diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/HTableDescriptor.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/HTableDescriptor.java index b27826856f7c..8d2afcf36eff 100644 --- a/hbase-client/src/main/java/org/apache/hadoop/hbase/HTableDescriptor.java +++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/HTableDescriptor.java @@ -225,7 +225,9 @@ public class HTableDescriptor implements WritableComparable { * catalog tables, .META. and -ROOT-. */ protected HTableDescriptor(final byte [] name, HColumnDescriptor[] families) { - setName(name); + this.name = name.clone(); + this.nameAsString = Bytes.toString(this.name); + setMetaFlags(name); for(HColumnDescriptor descriptor : families) { this.families.put(descriptor.getName(), descriptor); } @@ -237,7 +239,12 @@ protected HTableDescriptor(final byte [] name, HColumnDescriptor[] families) { */ protected HTableDescriptor(final byte [] name, HColumnDescriptor[] families, Map values) { - this(name.clone(), families); + this.name = name.clone(); + this.nameAsString = Bytes.toString(this.name); + setMetaFlags(name); + for(HColumnDescriptor descriptor : families) { + this.families.put(descriptor.getName(), descriptor); + } for (Map.Entry entry: values.entrySet()) { setValue(entry.getKey(), entry.getValue()); @@ -277,7 +284,9 @@ public HTableDescriptor(final String name) { */ public HTableDescriptor(final byte [] name) { super(); - setName(name); + setMetaFlags(this.name); + this.name = this.isMetaRegion()? name: isLegalTableName(name); + this.nameAsString = Bytes.toString(this.name); } /** @@ -289,7 +298,9 @@ public HTableDescriptor(final byte [] name) { */ public HTableDescriptor(final HTableDescriptor desc) { super(); - setName(desc.name.clone()); + this.name = desc.name.clone(); + this.nameAsString = Bytes.toString(this.name); + setMetaFlags(this.name); for (HColumnDescriptor c: desc.families.values()) { this.families.put(c.getName(), new HColumnDescriptor(c)); } @@ -639,13 +650,9 @@ public String getRegionSplitPolicyClassName() { * Set the name of the table. * * @param name name of table - * @throws IllegalArgumentException if passed a table name - * that is made of other than 'word' characters, underscore or period: i.e. - * [a-zA-Z_0-9.]. - * @see HADOOP-1581 HBASE: Un-openable tablename bug */ public void setName(byte[] name) { - this.name = isMetaTable(name) ? name : isLegalTableName(name); + this.name = name; this.nameAsString = Bytes.toString(this.name); setMetaFlags(this.name); } @@ -980,34 +987,39 @@ public void write(DataOutput out) throws IOException { */ @Override public int compareTo(final HTableDescriptor other) { - // Check name matches int result = Bytes.compareTo(this.name, other.name); - if (result != 0) return result; - - // Check size matches - result = families.size() - other.families.size(); - if (result != 0) return result; - - // Compare that all column families - for (Iterator it = families.values().iterator(), - it2 = other.families.values().iterator(); it.hasNext(); ) { - result = it.next().compareTo(it2.next()); - if (result != 0) { - return result; + if (result == 0) { + result = families.size() - other.families.size(); + } + if (result == 0 && families.size() != other.families.size()) { + result = Integer.valueOf(families.size()).compareTo( + Integer.valueOf(other.families.size())); + } + if (result == 0) { + for (Iterator it = families.values().iterator(), + it2 = other.families.values().iterator(); it.hasNext(); ) { + result = it.next().compareTo(it2.next()); + if (result != 0) { + break; + } } } - - // Compare values - if (!values.equals(other.values)) { - return 1; + if (result == 0) { + // punt on comparison for ordering, just calculate difference + result = this.values.hashCode() - other.values.hashCode(); + if (result < 0) + result = -1; + else if (result > 0) + result = 1; } - - // Compare configuration - if (!configuration.equals(other.configuration)) { - return 1; + if (result == 0) { + result = this.configuration.hashCode() - other.configuration.hashCode(); + if (result < 0) + result = -1; + else if (result > 0) + result = 1; } - - return 0; + return result; } /** diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/TestHColumnDescriptor.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/TestHColumnDescriptor.java index fb4506555bbd..253460936dd2 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/TestHColumnDescriptor.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/TestHColumnDescriptor.java @@ -18,14 +18,12 @@ package org.apache.hadoop.hbase; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.apache.hadoop.hbase.exceptions.DeserializationException; import org.apache.hadoop.hbase.io.compress.Compression; import org.apache.hadoop.hbase.io.compress.Compression.Algorithm; import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding; -import org.apache.hadoop.hbase.io.hfile.BlockType; import org.apache.hadoop.hbase.regionserver.BloomType; import org.junit.experimental.categories.Category; @@ -96,71 +94,4 @@ public void testAddGetRemoveConfiguration() throws Exception { desc.removeConfiguration(key); assertEquals(null, desc.getConfigurationValue(key)); } - - @Test - public void testEqualsWithFamilyName() { - final String name1 = ""someFamilyName""; - HColumnDescriptor hcd1 = new HColumnDescriptor(name1); - HColumnDescriptor hcd2 = new HColumnDescriptor(""someOtherFamilyName""); - HColumnDescriptor hcd3 = new HColumnDescriptor(name1); - - assertFalse(hcd1.equals(hcd2)); - assertFalse(hcd2.equals(hcd1)); - - assertTrue(hcd3.equals(hcd1)); - assertTrue(hcd1.equals(hcd3)); - } - - @Test - public void testEqualsWithAdditionalProperties() { - final String name1 = ""someFamilyName""; - HColumnDescriptor hcd1 = new HColumnDescriptor(name1); - HColumnDescriptor hcd2 = new HColumnDescriptor(name1); - hcd2.setBlocksize(4); - - assertFalse(hcd1.equals(hcd2)); - assertFalse(hcd2.equals(hcd1)); - - hcd1.setBlocksize(4); - - assertTrue(hcd2.equals(hcd1)); - assertTrue(hcd1.equals(hcd2)); - } - - @Test - public void testEqualsWithDifferentNumberOfProperties() { - final String name1 = ""someFamilyName""; - HColumnDescriptor hcd1 = new HColumnDescriptor(name1); - HColumnDescriptor hcd2 = new HColumnDescriptor(name1); - hcd2.setBlocksize(4); - hcd1.setBlocksize(4); - - assertTrue(hcd2.equals(hcd1)); - assertTrue(hcd1.equals(hcd2)); - - hcd2.setBloomFilterType(BloomType.ROW); - - assertFalse(hcd1.equals(hcd2)); - assertFalse(hcd2.equals(hcd1)); - } - - @Test - public void testEqualsWithDifferentOrderingOfProperties() { - final String name1 = ""someFamilyName""; - HColumnDescriptor hcd1 = new HColumnDescriptor(name1); - HColumnDescriptor hcd2 = new HColumnDescriptor(name1); - hcd2.setBlocksize(4); - hcd2.setBloomFilterType(BloomType.ROW); - hcd1.setBloomFilterType(BloomType.ROW); - hcd1.setBlocksize(4); - - assertTrue(hcd2.equals(hcd1)); - assertTrue(hcd1.equals(hcd2)); - } - - @Test - public void testEqualityWithSameObject() { - HColumnDescriptor hcd1 = new HColumnDescriptor(""someName""); - assertTrue(hcd1.equals(hcd1)); - } } diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/TestHTableDescriptor.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/TestHTableDescriptor.java index 5f06b429c91a..bc8e72c8689c 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/TestHTableDescriptor.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/TestHTableDescriptor.java @@ -198,173 +198,4 @@ public void testAddGetRemoveConfiguration() throws Exception { desc.removeConfiguration(key); assertEquals(null, desc.getConfigurationValue(key)); } - - @Test - public void testEqualsWithDifferentProperties() { - // Test basic property difference - HTableDescriptor h1 = new HTableDescriptor(); - h1.setName(Bytes.toBytes(""n1"")); - - HTableDescriptor h2 = new HTableDescriptor(); - h2.setName(Bytes.toBytes(""n2"")); - - assertFalse(h2.equals(h1)); - assertFalse(h1.equals(h2)); - - h2.setName(Bytes.toBytes(""n1"")); - assertTrue(h2.equals(h1)); - assertTrue(h1.equals(h2)); - } - - @Test - public void testEqualsWithDifferentNumberOfItems() { - HTableDescriptor h1 = new HTableDescriptor(); - HTableDescriptor h2 = new HTableDescriptor(); - - // Test diff # of items - h1 = new HTableDescriptor(); - h1.setName(Bytes.toBytes(""n1"")); - - h2 = new HTableDescriptor(); - h2.setName(Bytes.toBytes(""n1"")); - - HColumnDescriptor hcd1 = new HColumnDescriptor(Bytes.toBytes(""someName"")); - HColumnDescriptor hcd2 = new HColumnDescriptor(Bytes.toBytes(""someOtherName"")); - - h1.addFamily(hcd1); - h2.addFamily(hcd1); - h1.addFamily(hcd2); - - assertFalse(h2.equals(h1)); - assertFalse(h1.equals(h2)); - - h2.addFamily(hcd2); - - assertTrue(h2.equals(h1)); - assertTrue(h1.equals(h2)); - } - - @Test - public void testNotEqualsWithDifferentHCDs() { - HTableDescriptor h1 = new HTableDescriptor(); - HTableDescriptor h2 = new HTableDescriptor(); - - // Test diff # of items - h1 = new HTableDescriptor(); - h1.setName(Bytes.toBytes(""n1"")); - - h2 = new HTableDescriptor(); - h2.setName(Bytes.toBytes(""n1"")); - - HColumnDescriptor hcd1 = new HColumnDescriptor(Bytes.toBytes(""someName"")); - HColumnDescriptor hcd2 = new HColumnDescriptor(Bytes.toBytes(""someOtherName"")); - - h1.addFamily(hcd1); - h2.addFamily(hcd2); - - assertFalse(h2.equals(h1)); - assertFalse(h1.equals(h2)); - } - - @Test - public void testEqualsWithDifferentHCDObjects() { - HTableDescriptor h1 = new HTableDescriptor(); - HTableDescriptor h2 = new HTableDescriptor(); - - // Test diff # of items - h1 = new HTableDescriptor(); - h1.setName(Bytes.toBytes(""n1"")); - - h2 = new HTableDescriptor(); - h2.setName(Bytes.toBytes(""n1"")); - - HColumnDescriptor hcd1 = new HColumnDescriptor(Bytes.toBytes(""someName"")); - HColumnDescriptor hcd2 = new HColumnDescriptor(Bytes.toBytes(""someName"")); - - h1.addFamily(hcd1); - h2.addFamily(hcd2); - - assertTrue(h2.equals(h1)); - assertTrue(h1.equals(h2)); - } - - @Test - public void testNotEqualsWithDifferentItems() { - HTableDescriptor h1 = new HTableDescriptor(); - HTableDescriptor h2 = new HTableDescriptor(); - - // Test diff # of items - h1 = new HTableDescriptor(); - h1.setName(Bytes.toBytes(""n1"")); - - h2 = new HTableDescriptor(); - h2.setName(Bytes.toBytes(""n1"")); - - HColumnDescriptor hcd1 = new HColumnDescriptor(Bytes.toBytes(""someName"")); - HColumnDescriptor hcd2 = new HColumnDescriptor(Bytes.toBytes(""someOtherName"")); - h1.addFamily(hcd1); - h2.addFamily(hcd2); - - assertFalse(h2.equals(h1)); - assertFalse(h1.equals(h2)); - } - - @Test - public void testEqualsWithDifferentOrderingsOfItems() { - HTableDescriptor h1 = new HTableDescriptor(); - HTableDescriptor h2 = new HTableDescriptor(); - - //Test diff # of items - h1 = new HTableDescriptor(); - h1.setName(Bytes.toBytes(""n1"")); - - h2 = new HTableDescriptor(); - h2.setName(Bytes.toBytes(""n1"")); - - HColumnDescriptor hcd1 = new HColumnDescriptor(Bytes.toBytes(""someName"")); - HColumnDescriptor hcd2 = new HColumnDescriptor(Bytes.toBytes(""someOtherName"")); - h1.addFamily(hcd1); - h2.addFamily(hcd2); - h1.addFamily(hcd2); - h2.addFamily(hcd1); - - assertTrue(h2.equals(h1)); - assertTrue(h1.equals(h2)); - } - - @Test - public void testSingleItemEquals() { - HTableDescriptor h1 = new HTableDescriptor(); - HTableDescriptor h2 = new HTableDescriptor(); - - //Test diff # of items - h1 = new HTableDescriptor(); - h1.setName(Bytes.toBytes(""n1"")); - - h2 = new HTableDescriptor(); - h2.setName(Bytes.toBytes(""n1"")); - - HColumnDescriptor hcd1 = new HColumnDescriptor(Bytes.toBytes(""someName"")); - HColumnDescriptor hcd2 = new HColumnDescriptor(Bytes.toBytes(""someName"")); - h1.addFamily(hcd1); - h2.addFamily(hcd2); - - assertTrue(h2.equals(h1)); - assertTrue(h1.equals(h2)); - } - - @Test - public void testEmptyEquals() { - HTableDescriptor h1 = new HTableDescriptor(); - HTableDescriptor h2 = new HTableDescriptor(); - - assertTrue(h2.equals(h1)); - assertTrue(h1.equals(h2)); - } - - @Test - public void testEqualityWithSameObject() { - HTableDescriptor htd = new HTableDescriptor(""someName""); - assertTrue(htd.equals(htd)); - } }" 57cf199d7477ddba4c623960c265f356304f4045,drools,fix WELD problem caused by having a beans.xml in- drools-compiler--,c,https://github.com/kiegroup/drools,"diff --git a/drools-compiler/src/main/resources/META-INF/beans.xml b/drools-compiler/src/main/resources/META-INF/beans.xml deleted file mode 100644 index b87599caa0a..00000000000 --- a/drools-compiler/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - \ No newline at end of file diff --git a/drools-compiler/src/test/java/org/drools/kproject/KProjectTest.java b/drools-compiler/src/test/java/org/drools/kproject/KProjectTest.java index 2a3de24eb45..b43c20a870e 100644 --- a/drools-compiler/src/test/java/org/drools/kproject/KProjectTest.java +++ b/drools-compiler/src/test/java/org/drools/kproject/KProjectTest.java @@ -250,6 +250,12 @@ public void testCompileAndCDI() throws IOException, File fle1 = fld1.getFile( ""KProjectTestClassImpl.java"" ); fle1.create( new ByteArrayInputStream( generateKProjectTestClassImpl( kproj ).getBytes() ) ); + Folder fld2 = trgMfs.getFolder( ""META-INF"" ); + fld2.create(); + File fle2 = fld2.getFile( ""beans.xml"" ); + fle2.create( new ByteArrayInputStream( generateBeansXML( kproj ).getBytes() ) ); + + List inputClasses = new ArrayList(); inputClasses.add( ""org/drools/cdi/test/KProjectTestClassImpl.java"" ); @@ -445,6 +451,14 @@ public String generateKProjectTestClassImpl(KProject kproject) { return s; } + public String generateBeansXML(KProject kproject) { + String s = ""\n"" + + ""\n"" + + """"; + + return s; + } + public static String filenameToClassname(String filename) { return filename.substring( 0, filename.lastIndexOf( "".java"" ) ).replace( '/', '.' ).replace( '\\', '.' ); }" c03ff2ec9b64d6073b9130e11af00d0c655f25b6,drools,Implementing support to incremental updates on- kcontainers--,a,https://github.com/kiegroup/drools,"diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieModule.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieModule.java index ad8e834922c..7a75099054d 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieModule.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieModule.java @@ -1,6 +1,8 @@ package org.drools.compiler.kie.builder.impl; import static org.drools.compiler.kie.builder.impl.KieBuilderImpl.filterFileInKBase; +import static org.drools.core.rule.TypeMetaInfo.unmarshallMetaInfos; +import static org.drools.core.util.ClassUtils.convertResourceToClassName; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -16,16 +18,16 @@ import org.drools.compiler.kie.builder.impl.KieModuleCache.CompilationData; import org.drools.compiler.kie.builder.impl.KieModuleCache.Header; import org.drools.compiler.kie.builder.impl.KieModuleCache.KModuleCache; -import org.drools.compiler.kproject.models.KieModuleModelImpl; -import org.drools.core.rule.TypeMetaInfo; -import org.drools.core.util.StringUtils; import org.drools.compiler.kproject.models.KieBaseModelImpl; +import org.drools.compiler.kproject.models.KieModuleModelImpl; import org.drools.core.builder.conf.impl.DecisionTableConfigurationImpl; +import org.drools.core.rule.TypeMetaInfo; import org.drools.core.util.StringUtils; import org.kie.api.builder.ReleaseId; import org.kie.api.builder.Results; import org.kie.api.builder.model.KieBaseModel; import org.kie.api.builder.model.KieModuleModel; +import org.kie.api.io.Resource; import org.kie.api.io.ResourceConfiguration; import org.kie.api.io.ResourceType; import org.kie.internal.builder.CompositeKnowledgeBuilder; @@ -35,26 +37,11 @@ import org.kie.internal.builder.KnowledgeBuilderFactory; import org.kie.internal.definition.KnowledgePackage; import org.kie.internal.io.ResourceFactory; -import org.kie.api.io.ResourceConfiguration; -import org.kie.api.io.ResourceType; import org.kie.internal.io.ResourceTypeImpl; -import org.kie.internal.utils.CompositeClassLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.protobuf.ExtensionRegistry; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import static org.drools.compiler.kie.builder.impl.KieBuilderImpl.filterFileInKBase; -import static org.drools.core.rule.TypeMetaInfo.unmarshallMetaInfos; -import static org.drools.core.util.ClassUtils.convertResourceToClassName; public abstract class AbstractKieModule implements @@ -205,20 +192,7 @@ private static void addFiles( CompositeKnowledgeBuilder ckbuilder, int fileCount = 0; for ( String fileName : kieModule.getFileNames() ) { if ( filterFileInKBase(kieBaseModel, fileName) && !fileName.endsWith( "".properties"" ) ) { - ResourceConfiguration conf = getResourceConfiguration(kieModule, fileName); - byte[] bytes = kieModule.getBytes( fileName ); - if ( bytes == null || bytes.length == 0 ) { - continue; - } - if ( conf == null ) { - ckbuilder.add( ResourceFactory.newByteArrayResource( bytes ).setSourcePath( fileName ), - ResourceType.determineResourceType( fileName ) ); - } else { - ckbuilder.add( ResourceFactory.newByteArrayResource(bytes).setSourcePath(fileName), - ResourceType.determineResourceType( fileName ), - conf ); - } - fileCount++; + fileCount += addFile( ckbuilder, kieModule, fileName ) ? 1 : 0; } } if ( fileCount == 0 ) { @@ -230,6 +204,33 @@ private static void addFiles( CompositeKnowledgeBuilder ckbuilder, } } + + public static boolean addFile(CompositeKnowledgeBuilder ckbuilder, + InternalKieModule kieModule, + String fileName ) { + ResourceConfiguration conf = getResourceConfiguration(kieModule, fileName); + Resource resource = kieModule.getResource( fileName ); + if ( resource != null ) { + if ( conf == null ) { + ckbuilder.add( resource, + ResourceType.determineResourceType( fileName ) ); + } else { + ckbuilder.add( resource, + ResourceType.determineResourceType( fileName ), + conf ); + } + return true; + } + return false; + } + + public Resource getResource( String fileName ) { + byte[] bytes = getBytes( fileName ); + if ( bytes != null && bytes.length > 0 ) { + return ResourceFactory.newByteArrayResource( bytes ).setSourcePath( fileName ); + } + return null; + } public static ResourceConfiguration getResourceConfiguration(InternalKieModule kieModule, String fileName) { ResourceConfiguration conf = null; diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieProject.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieProject.java index f4a0f1c9dc1..af72ac65289 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieProject.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/AbstractKieProject.java @@ -103,4 +103,12 @@ protected void indexParts(Collection kieModules, } } } + + protected void cleanIndex() { + kBaseModels.clear(); + kSessionModels.clear(); + defaultKieBase = null; + defaultKieSession = null; + defaultStatelessKieSession = null; + } } diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/InternalKieModule.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/InternalKieModule.java index 40f64e334c3..f9627acabb5 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/InternalKieModule.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/InternalKieModule.java @@ -5,6 +5,7 @@ import org.kie.api.builder.KieModule; import org.kie.api.builder.model.KieModuleModel; import org.kie.api.builder.Results; +import org.kie.api.io.Resource; import org.kie.internal.definition.KnowledgePackage; import java.io.File; @@ -25,7 +26,9 @@ public interface InternalKieModule extends KieModule { KieModuleModel getKieModuleModel(); - byte[] getBytes( ); + byte[] getBytes( ); + + Resource getResource( String fileName ); Map getDependencies(); 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 d3896a9203a..01cbc2693f6 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 @@ -325,8 +325,8 @@ private void addMetaInfBuilder() { } } - static boolean filterFileInKBase(KieBaseModel kieBase, - String fileName) { + public static boolean filterFileInKBase(KieBaseModel kieBase, + String fileName) { return FormatsManager.isKieExtension( fileName ) && isFileInKieBase( kieBase, fileName ); } diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieContainerImpl.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieContainerImpl.java index 4437446c5bb..37971dea921 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieContainerImpl.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieContainerImpl.java @@ -1,9 +1,22 @@ package org.drools.compiler.kie.builder.impl; +import static org.drools.compiler.kie.builder.impl.AbstractKieModule.buildKnowledgePackages; +import static org.drools.compiler.kie.util.CDIHelper.wireListnersAndWIHs; + +import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; +import java.util.Iterator; +import java.util.List; import java.util.Map; - +import java.util.Map.Entry; + +import org.drools.compiler.builder.impl.KnowledgeBuilderImpl; +import org.drools.compiler.compiler.PackageBuilder; +import org.drools.compiler.kie.util.ChangeSetBuilder; +import org.drools.compiler.kie.util.ChangeType; +import org.drools.compiler.kie.util.KieJarChangeSet; +import org.drools.compiler.kie.util.ResourceChangeSet; import org.drools.compiler.kproject.models.KieBaseModelImpl; import org.drools.compiler.kproject.models.KieSessionModelImpl; import org.drools.core.impl.InternalKnowledgeBase; @@ -20,15 +33,15 @@ import org.kie.api.runtime.KieSession; import org.kie.api.runtime.KieSessionConfiguration; import org.kie.api.runtime.StatelessKieSession; +import org.kie.internal.KnowledgeBase; import org.kie.internal.KnowledgeBaseFactory; +import org.kie.internal.builder.CompositeKnowledgeBuilder; import org.kie.internal.builder.KnowledgeBuilder; +import org.kie.internal.builder.KnowledgeBuilderFactory; import org.kie.internal.definition.KnowledgePackage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.drools.compiler.kie.builder.impl.AbstractKieModule.*; -import static org.drools.compiler.kie.util.CDIHelper.*; - public class KieContainerImpl implements InternalKieContainer { @@ -55,12 +68,78 @@ public ReleaseId getReleaseId() { return kProject.getGAV(); } - public void updateToVersion(ReleaseId releaseId) { - kBases.clear(); - this.kProject = new KieModuleKieProject( (InternalKieModule)kr.getKieModule(releaseId) ); - this.kProject.init(); + public void updateToVersion(ReleaseId newReleaseId) { + if( kProject instanceof ClasspathKieProject ) { + throw new UnsupportedOperationException( ""It is not possible to update a classpath container to a new version."" ); + } + ReleaseId currentReleaseId = kProject.getGAV(); + InternalKieModule currentKM = (InternalKieModule) kr.getKieModule( currentReleaseId ); + InternalKieModule newKM = (InternalKieModule) kr.getKieModule( newReleaseId ); + + ChangeSetBuilder csb = new ChangeSetBuilder(); + KieJarChangeSet cs = csb.build( currentKM, newKM ); + + ((KieModuleKieProject) kProject).updateToModule( newKM ); + + List kbasesToRemove = new ArrayList(); + for( Map.Entry kBaseEntry : kBases.entrySet() ) { + String kbaseName = kBaseEntry.getKey(); + KieBaseModel kieBaseModel = kProject.getKieBaseModel( kbaseName ); + // if a kbase no longer exists, just remove it from the cache + if( kieBaseModel == null ) { + // have to save for later removal to avoid iteration errors + kbasesToRemove.add( kbaseName ); + } else { + // attaching the builder to the kbase + KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder( (KnowledgeBase) kBaseEntry.getValue() ); + PackageBuilder pkgbuilder = kbuilder instanceof PackageBuilder ? ((PackageBuilder) kbuilder) : ((KnowledgeBuilderImpl)kbuilder).getPackageBuilder(); + CompositeKnowledgeBuilder ckbuilder = kbuilder.batch(); + int fileCount = 0; + + // remove resources first + for( ResourceChangeSet rcs : cs.getChanges().values() ) { + if( rcs.getChangeType().equals( ChangeType.REMOVED ) ) { + String resourceName = rcs.getResourceName(); + if( KieBuilderImpl.filterFileInKBase( kieBaseModel, resourceName ) && ! resourceName.endsWith( "".properties"" ) ) { + pkgbuilder.removeObjectsGeneratedFromResource( currentKM.getResource( resourceName ) ); + } + } + } + + // then update and add new resources + for( ResourceChangeSet rcs : cs.getChanges().values() ) { + if( ! rcs.getChangeType().equals( ChangeType.REMOVED ) ) { + String resourceName = rcs.getResourceName(); + if( KieBuilderImpl.filterFileInKBase( kieBaseModel, resourceName ) && ! resourceName.endsWith( "".properties"" ) ) { + fileCount += AbstractKieModule.addFile( ckbuilder, + newKM, + resourceName ) ? 1 : 0; + } + } + } + if( fileCount > 0 ) { + ckbuilder.build(); + } + } + } + + for( Iterator> it = this.kSessions.entrySet().iterator(); it.hasNext(); ) { + Entry ksession = it.next(); + if( kProject.getKieSessionModel( ksession.getKey() ) == null ) { + // remove sessions that no longer exist + it.remove(); + } + } + + for( Iterator> it = this.statelessKSessions.entrySet().iterator(); it.hasNext(); ) { + Entry ksession = it.next(); + if( kProject.getKieSessionModel( ksession.getKey() ) == null ) { + // remove sessions that no longer exist + it.remove(); + } + } } - + public KieBase getKieBase() { KieBaseModel defaultKieBaseModel = kProject.getDefaultKieBaseModel(); if (defaultKieBaseModel == null) { @@ -165,7 +244,7 @@ public KieSession newKieSession(Environment environment, KieSessionConfiguration private KieSessionModel findKieSessionModel(boolean stateless) { KieSessionModel defaultKieSessionModel = stateless ? kProject.getDefaultStatelessKieSession() : kProject.getDefaultKieSession(); if (defaultKieSessionModel == null) { - throw new RuntimeException(stateless ? ""Cannot find a defualt StatelessKieSession"" : ""Cannot find a defualt KieSession""); + throw new RuntimeException(stateless ? ""Cannot find a default StatelessKieSession"" : ""Cannot find a default KieSession""); } return defaultKieSessionModel; } diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieModuleKieProject.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieModuleKieProject.java index fc00c2c333a..40e3b59d18d 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieModuleKieProject.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieModuleKieProject.java @@ -22,15 +22,15 @@ */ public class KieModuleKieProject extends AbstractKieProject { - private static final Logger log = LoggerFactory.getLogger( KieModuleKieProject.class ); + private static final Logger log = LoggerFactory.getLogger( KieModuleKieProject.class ); - private List kieModules; + private List kieModules; - private final Map kJarFromKBaseName = new HashMap(); + private Map kJarFromKBaseName = new HashMap(); - private final InternalKieModule kieModule; + private InternalKieModule kieModule; - private final ProjectClassLoader cl; + private ProjectClassLoader cl; public KieModuleKieProject(InternalKieModule kieModule) { this.kieModule = kieModule; @@ -43,16 +43,16 @@ public void init() { kieModules.addAll( kieModule.getDependencies().values() ); kieModules.add( kieModule ); indexParts( kieModules, kJarFromKBaseName ); - initClassLoader(cl); + initClassLoader( cl ); } } private void initClassLoader(ProjectClassLoader projectCL) { - for (Map.Entry entry : getClassesMap().entrySet()) { - if (entry.getValue() != null) { + for ( Map.Entry entry : getClassesMap().entrySet() ) { + if ( entry.getValue() != null ) { String resourceName = entry.getKey(); - String className = convertResourceToClassName(resourceName); - projectCL.storeClass(className, resourceName, entry.getValue()); + String className = convertResourceToClassName( resourceName ); + projectCL.storeClass( className, resourceName, entry.getValue() ); } } } @@ -61,7 +61,7 @@ private Map getClassesMap() { Map classes = new HashMap(); for ( InternalKieModule kModule : kieModules ) { // avoid to take type declarations defined directly in this kieModule since they have to be recompiled - classes.putAll(kModule.getClassesMap(kModule != this.kieModule)); + classes.putAll( kModule.getClassesMap( kModule != this.kieModule ) ); } return classes; } @@ -71,7 +71,7 @@ public ReleaseId getGAV() { } public InternalKieModule getKieModuleForKBase(String kBaseName) { - return this.kJarFromKBaseName.get(kBaseName); + return this.kJarFromKBaseName.get( kBaseName ); } public ClassLoader getClassLoader() { @@ -79,8 +79,18 @@ public ClassLoader getClassLoader() { } public ClassLoader getClonedClassLoader() { - ProjectClassLoader clonedCL = createProjectClassLoader(cl.getParent()); - initClassLoader(clonedCL); + ProjectClassLoader clonedCL = createProjectClassLoader( cl.getParent() ); + initClassLoader( clonedCL ); return clonedCL; } + + public void updateToModule(InternalKieModule kieModule) { + this.kieModules = null; + this.kJarFromKBaseName.clear(); + cleanIndex(); + + this.kieModule = kieModule; + //this.cl.getStore().clear(); // can we do this in order to preserve the reference to the classloader? + this.init(); // this might override class definitions, not sure we can do it any other way though + } } diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieProject.java b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieProject.java index 6c6cc3d19cd..14e53a08419 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieProject.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/builder/impl/KieProject.java @@ -27,4 +27,5 @@ public interface KieProject { ClassLoader getClonedClassLoader(); ResultsImpl verify(); + } diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/IncrementalCompilationTest.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/IncrementalCompilationTest.java index 460d6355ed0..bd172104dca 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/IncrementalCompilationTest.java +++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/IncrementalCompilationTest.java @@ -1,21 +1,26 @@ package org.drools.compiler.integrationtests; +import static junit.framework.Assert.assertEquals; + import org.drools.compiler.Message; +import org.drools.compiler.kie.builder.impl.InternalKieModule; +import org.junit.Ignore; import org.junit.Test; import org.kie.api.KieServices; -import org.kie.internal.builder.IncrementalResults; -import org.kie.internal.builder.InternalKieBuilder; import org.kie.api.builder.KieBuilder; import org.kie.api.builder.KieFileSystem; +import org.kie.api.builder.KieModule; +import org.kie.api.builder.ReleaseId; +import org.kie.api.io.Resource; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; - -import static junit.framework.Assert.assertEquals; +import org.kie.internal.builder.IncrementalResults; +import org.kie.internal.builder.InternalKieBuilder; public class IncrementalCompilationTest { @Test - public void testIncrementalCompilation() throws Exception { + public void testKJarUpgrade() throws Exception { String drl1 = ""package org.drools.compiler\n"" + ""rule R1 when\n"" + "" $m : Message()\n"" + @@ -35,28 +40,97 @@ public void testIncrementalCompilation() throws Exception { ""end\n""; KieServices ks = KieServices.Factory.get(); + + // Create an in-memory jar for version 1.0.0 + ReleaseId releaseId1 = ks.newReleaseId(""org.kie"", ""test-upgrade"", ""1.0.0""); + KieModule km = createAndDeployJar( ks, releaseId1, drl1, drl2_1 ); + + // Create a session and fire rules + KieContainer kc = ks.newKieContainer( km.getReleaseId() ); + KieSession ksession = kc.newKieSession(); + ksession.insert(new Message(""Hello World"")); + assertEquals( 1, ksession.fireAllRules() ); + ksession.dispose(); - KieFileSystem kfs = ks.newKieFileSystem() - .write(""src/main/resources/r1.drl"", drl1) - .write(""src/main/resources/r2.drl"", drl2_1); + // Create a new jar for version 1.1.0 + ReleaseId releaseId2 = ks.newReleaseId(""org.kie"", ""test-upgrade"", ""1.1.0""); + km = createAndDeployJar( ks, releaseId2, drl1, drl2_2 ); - KieBuilder kieBuilder = ks.newKieBuilder( kfs ).buildAll(); - KieContainer kieContainer = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()); + // try to update the container to version 1.1.0 + kc.updateToVersion(releaseId2); + + // create and use a new session + ksession = kc.newKieSession(); + ksession.insert(new Message(""Hello World"")); + assertEquals( 2, ksession.fireAllRules() ); + } - KieSession ksession = kieContainer.newKieSession(); + @Test + public void testKJarUpgradeSameSession() throws Exception { + String drl1 = ""package org.drools.compiler\n"" + + ""rule R1 when\n"" + + "" $m : Message()\n"" + + ""then\n"" + + ""end\n""; + + String drl2_1 = ""package org.drools.compiler\n"" + + ""rule R2_1 when\n"" + + "" $m : Message( message == \""Hi Universe\"" )\n"" + + ""then\n"" + + ""end\n""; + + String drl2_2 = ""package org.drools.compiler\n"" + + ""rule R2_2 when\n"" + + "" $m : Message( message == \""Hello World\"" )\n"" + + ""then\n"" + + ""end\n""; + + KieServices ks = KieServices.Factory.get(); + + // Create an in-memory jar for version 1.0.0 + ReleaseId releaseId1 = ks.newReleaseId(""org.kie"", ""test-upgrade"", ""1.0.0""); + KieModule km = createAndDeployJar( ks, releaseId1, drl1, drl2_1 ); + + // Create a session and fire rules + KieContainer kc = ks.newKieContainer( km.getReleaseId() ); + KieSession ksession = kc.newKieSession(); ksession.insert(new Message(""Hello World"")); assertEquals( 1, ksession.fireAllRules() ); - kfs.write(""src/main/resources/r2.drl"", drl2_2); - ((InternalKieBuilder)kieBuilder).createFileSet(""src/main/resources/r2.drl"").build(); + // Create a new jar for version 1.1.0 + ReleaseId releaseId2 = ks.newReleaseId(""org.kie"", ""test-upgrade"", ""1.1.0""); + km = createAndDeployJar( ks, releaseId2, drl1, drl2_2 ); - kieContainer.updateToVersion(ks.getRepository().getDefaultReleaseId()); - ksession = kieContainer.newKieSession(); + // try to update the container to version 1.1.0 + kc.updateToVersion(releaseId2); + + // continue working with the session ksession.insert(new Message(""Hello World"")); - assertEquals( 2, ksession.fireAllRules() ); + assertEquals( 3, ksession.fireAllRules() ); + } + + private KieModule createAndDeployJar(KieServices ks, + ReleaseId releaseId, + String... drls ) { + KieFileSystem kfs = ks.newKieFileSystem() + .generateAndWritePomXML(releaseId); + for( int i = 0; i < drls.length; i++ ) { + if( drls[i] != null ) { + kfs.write(""src/main/resources/r""+i+"".drl"", drls[i]); + } + } + ks.newKieBuilder( kfs ).buildAll(); + InternalKieModule kieModule = (InternalKieModule) ks.getRepository().getKieModule( releaseId ); + byte[] jar = kieModule.getBytes(); + + // Deploy jar into the repository + Resource jarRes = ks.getResources().newByteArrayResource( jar ); + KieModule km = ks.getRepository().addKieModule( jarRes ); + return km; } @Test + @Ignore public void testDeletedFile() throws Exception { String drl1 = ""package org.drools.compiler\n"" + ""rule R1 when\n"" + @@ -72,21 +146,21 @@ public void testDeletedFile() throws Exception { KieServices ks = KieServices.Factory.get(); - KieFileSystem kfs = ks.newKieFileSystem() - .write(""src/main/resources/r1.drl"", drl1) - .write(""src/main/resources/r2.drl"", drl2); + // Create an in-memory jar for version 1.0.0 + ReleaseId releaseId1 = ks.newReleaseId(""org.kie"", ""test-delete"", ""1.0.0""); + KieModule km = createAndDeployJar( ks, releaseId1, drl1, drl2 ); - KieBuilder kieBuilder = ks.newKieBuilder( kfs ).buildAll(); - KieContainer kieContainer = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()); + KieContainer kieContainer = ks.newKieContainer(releaseId1); KieSession ksession = kieContainer.newKieSession(); ksession.insert(new Message(""Hello World"")); assertEquals( 2, ksession.fireAllRules() ); - kfs.delete(""src/main/resources/r1.drl""); - ((InternalKieBuilder)kieBuilder).createFileSet(""src/main/resources/r1.drl"").build(); + ReleaseId releaseId2 = ks.newReleaseId(""org.kie"", ""test-delete"", ""1.0.1""); + km = createAndDeployJar( ks, releaseId2, null, drl2 ); - kieContainer.updateToVersion(ks.getRepository().getDefaultReleaseId()); + kieContainer.updateToVersion(releaseId2); + ksession = kieContainer.newKieSession(); ksession.insert(new Message(""Hello World"")); assertEquals( 1, ksession.fireAllRules() ); diff --git a/drools-compiler/src/test/java/org/drools/compiler/kie/util/ChangeSetBuilderTest.java b/drools-compiler/src/test/java/org/drools/compiler/kie/util/ChangeSetBuilderTest.java index 901bb4e06ab..30e239ea8f1 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/kie/util/ChangeSetBuilderTest.java +++ b/drools-compiler/src/test/java/org/drools/compiler/kie/util/ChangeSetBuilderTest.java @@ -45,7 +45,6 @@ public void testNoChanges() { ChangeSetBuilder builder = new ChangeSetBuilder(); KieJarChangeSet changes = builder.build( kieJar1, kieJar2 ); - System.out.println( builder.toProperties( changes ) ); assertThat( changes.getChanges().size(), is(0)); } @@ -85,9 +84,8 @@ public void testModified() { assertThat( cs.getChanges().get( 1 ), is( new ResourceChange(ChangeType.ADDED, Type.RULE, ""R3"") ) ); assertThat( cs.getChanges().get( 0 ), is( new ResourceChange(ChangeType.REMOVED, Type.RULE, ""R2"") ) ); - ChangeSetBuilder builder = new ChangeSetBuilder(); - System.out.println( builder.toProperties( changes ) ); - +// ChangeSetBuilder builder = new ChangeSetBuilder(); +// System.out.println( builder.toProperties( changes ) ); } @Test @@ -166,7 +164,7 @@ public void testModified2() { ChangeSetBuilder builder = new ChangeSetBuilder(); KieJarChangeSet changes = builder.build( kieJar1, kieJar2 ); - System.out.println( builder.toProperties( changes ) ); +// System.out.println( builder.toProperties( changes ) ); String modifiedFile = (String) kieJar2.getFileNames().toArray()[0]; String addedFile = (String) kieJar2.getFileNames().toArray()[1]; @@ -202,7 +200,7 @@ private InternalKieModule createKieJar( String... drls) { for( int i=0; i org.apache.xmlbeans xmlbeans - 2.4.0 + 2.3.0 diff --git a/src/main/java/org/isatools/isacreator/common/FileSelectionPanel.java b/src/main/java/org/isatools/isacreator/common/FileSelectionPanel.java index 919410f8..7efd9b92 100644 --- a/src/main/java/org/isatools/isacreator/common/FileSelectionPanel.java +++ b/src/main/java/org/isatools/isacreator/common/FileSelectionPanel.java @@ -96,7 +96,7 @@ public FileSelectionPanel(String text, JFileChooser fileChooser, Font textFont, this.textColor = textColor; setLayout(new GridLayout(2, 1)); - setSize(new Dimension(400, 60)); + setSize(new Dimension(400, 70)); ResourceInjector.get(""common-package.style"").inject(this); diff --git a/src/main/java/org/isatools/isacreator/externalutils/convertvalidate/ConversionTarget.java b/src/main/java/org/isatools/isacreator/externalutils/convertvalidate/ConversionTarget.java new file mode 100644 index 00000000..3a3bd11b --- /dev/null +++ b/src/main/java/org/isatools/isacreator/externalutils/convertvalidate/ConversionTarget.java @@ -0,0 +1,45 @@ +package org.isatools.isacreator.externalutils.convertvalidate; + +import org.isatools.isatab.gui_invokers.AllowedConversions; + +/** + * Created by the ISA team + * + * @author Eamonn Maguire (eamonnmag@gmail.com) + *

+ * Date: 08/09/2011 + * Time: 13:54 + */ +public class ConversionTarget { + + private AllowedConversions target; + private int numValidAssays; + private boolean selected; + + public ConversionTarget(AllowedConversions target, int numValidAssays, boolean selected) { + this.target = target; + this.numValidAssays = numValidAssays; + this.selected = selected; + } + + public AllowedConversions getTarget() { + return target; + } + + public int getNumValidAssays() { + return numValidAssays; + } + + public int incrementNumValidAssays() { + numValidAssays++; + return numValidAssays; + } + + public boolean isSelected() { + return selected; + } + + public void setSelected(boolean selected) { + this.selected = selected; + } +} diff --git a/src/main/java/org/isatools/isacreator/externalutils/convertvalidate/ConversionTargetInformationPanel.java b/src/main/java/org/isatools/isacreator/externalutils/convertvalidate/ConversionTargetInformationPanel.java new file mode 100644 index 00000000..552dfeaa --- /dev/null +++ b/src/main/java/org/isatools/isacreator/externalutils/convertvalidate/ConversionTargetInformationPanel.java @@ -0,0 +1,100 @@ +package org.isatools.isacreator.externalutils.convertvalidate; + +import org.isatools.errorreporter.ui.borders.RoundedBorder; +import org.isatools.errorreporter.ui.utils.UIHelper; +import org.jdesktop.fuse.InjectedResource; +import org.jdesktop.fuse.ResourceInjector; + +import javax.swing.*; +import javax.swing.border.EmptyBorder; +import java.awt.*; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +public class ConversionTargetInformationPanel extends JPanel { + + private Color hoverColor = new Color(249, 249, 249); + + @InjectedResource + private ImageIcon unselected, selected; + + private JLabel selectionIndicator; + private ConversionTarget conversionTarget; + + + public ConversionTargetInformationPanel(ConversionTarget conversionTarget) { + + ResourceInjector.get(""validator-package.style"").inject(this); + + this.conversionTarget = conversionTarget; + + createGUI(); + } + + public ConversionTarget getConversionTarget() { + return conversionTarget; + } + + public void createGUI() { + setLayout(new BorderLayout()); + setBorder(new RoundedBorder(UIHelper.LIGHT_GREEN_COLOR, 5)); + + add(createTopSection(), BorderLayout.NORTH); + add(createAssayInfoSection(), BorderLayout.CENTER); + + addMouseListener(new MouseAdapter() { + @Override + public void mouseExited(MouseEvent mouseEvent) { + setBackground(conversionTarget.isSelected() ? hoverColor : UIHelper.BG_COLOR); + } + + @Override + public void mouseEntered(MouseEvent mouseEvent) { + setBackground(hoverColor); + } + + @Override + public void mousePressed(MouseEvent mouseEvent) { + + firePropertyChange(""conversionTargetSelected"", false, true); + conversionTarget.setSelected(!conversionTarget.isSelected()); + updateSelection(); + } + }); + + } + + private Container createTopSection() { + Box topSection = Box.createHorizontalBox(); + + selectionIndicator = new JLabel(); + updateSelection(); + + topSection.add(selectionIndicator); + topSection.add(Box.createHorizontalStrut(5)); + topSection.add(UIHelper.createLabel(conversionTarget.getTarget().getType(), UIHelper.VER_11_BOLD, UIHelper.DARK_GREEN_COLOR, SwingConstants.LEFT)); + + return topSection; + } + + public void clearSelection() { + conversionTarget.setSelected(false); + updateSelection(); + } + + private Container createAssayInfoSection() { + Box infoPane = Box.createVerticalBox(); + infoPane.setPreferredSize(new Dimension(130, 35)); + infoPane.add(Box.createVerticalStrut(5)); + infoPane.add(UIHelper.createLabel(""conversion possible on "" + + conversionTarget.getNumValidAssays() + "" assay type"" + (conversionTarget.getNumValidAssays() > 1 ? ""s"" : """") + """", + UIHelper.VER_8_PLAIN, UIHelper.DARK_GREEN_COLOR, SwingConstants.LEFT)); + + infoPane.setBorder(new EmptyBorder(2, 1, 2, 1)); + return infoPane; + } + + public void updateSelection() { + selectionIndicator.setIcon(conversionTarget.isSelected() ? selected : unselected); + } +} diff --git a/src/main/java/org/isatools/isacreator/externalutils/convertvalidate/ConvertUI.java b/src/main/java/org/isatools/isacreator/externalutils/convertvalidate/ConvertUI.java new file mode 100644 index 00000000..9989cf1e --- /dev/null +++ b/src/main/java/org/isatools/isacreator/externalutils/convertvalidate/ConvertUI.java @@ -0,0 +1,171 @@ +package org.isatools.isacreator.externalutils.convertvalidate; + +import com.explodingpixels.macwidgets.IAppWidgetFactory; +import org.isatools.errorreporter.ui.utils.UIHelper; +import org.isatools.isacreator.common.FileSelectionPanel; +import org.isatools.isatab.gui_invokers.AllowedConversions; +import org.jdesktop.fuse.InjectedResource; +import org.jdesktop.fuse.ResourceInjector; + +import javax.swing.*; +import javax.swing.border.EmptyBorder; +import java.awt.*; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * Created by the ISA team + */ +public class ConvertUI extends JPanel { + + + static { + ResourceInjector.addModule(""org.jdesktop.fuse.swing.SwingModule""); + + ResourceInjector.get(""validator-package.style"").load( + ConvertUI.class.getResource(""/dependency-injections/validator-package.properties"")); + + ResourceInjector.get(""common-package.style"").load( + ConvertUI.class.getResource(""/dependency-injections/common-package.properties"")); + + } + + private Collection conversionTargets; + + + private List conversionTargetInformationPanels; + private JPanel conversionTargetContainer; + private FileSelectionPanel fileSelectionPanel; + + @InjectedResource + private ImageIcon startConversion, startConversionOver; + + public ConvertUI(Collection conversionTargets) { + + ResourceInjector.get(""validator-package.style"").inject(this); + + this.conversionTargets = conversionTargets; + } + + public void createGUI() { + setLayout(new BorderLayout()); + setOpaque(false); + + createSelectionPane(); + } + + private void createSelectionPane() { + conversionTargetContainer = new JPanel(new FlowLayout(FlowLayout.LEFT)); + conversionTargetContainer.setOpaque(false); + + conversionTargetInformationPanels = new ArrayList(); + + + for (ConversionTarget conversionTarget : conversionTargets) { + ConversionTargetInformationPanel conversionTargetInformationPanel = new ConversionTargetInformationPanel(conversionTarget); + + conversionTargetInformationPanel.addPropertyChangeListener(""conversionTargetSelected"", new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent propertyChangeEvent) { + // clear selection on all panels... + for (ConversionTargetInformationPanel panel : conversionTargetInformationPanels) { + panel.clearSelection(); + } + } + }); + + conversionTargetInformationPanels.add(conversionTargetInformationPanel); + conversionTargetContainer.add(conversionTargetInformationPanel); + } + + JScrollPane scroller = new JScrollPane(conversionTargetContainer, + JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + + scroller.getViewport().setOpaque(false); + scroller.setOpaque(false); + scroller.setBorder(new EmptyBorder(1, 1, 1, 1)); + scroller.setPreferredSize(new Dimension(400, 80)); + + IAppWidgetFactory.makeIAppScrollPane(scroller); + + Box container = Box.createVerticalBox(); + container.setOpaque(false); + + container.add(UIHelper.wrapComponentInPanel( + UIHelper.createLabel(""1. Choose your conversion target(s):"", + UIHelper.VER_11_PLAIN, UIHelper.DARK_GREEN_COLOR, SwingConstants.LEFT))); + + container.add(Box.createVerticalStrut(5)); + + container.add(UIHelper.wrapComponentInPanel( + UIHelper.createLabel(""weÕve filtered out conversion targets not applicable to your data. just click on a box to select the format."", + UIHelper.VER_9_PLAIN, UIHelper.GREY_COLOR, SwingConstants.LEFT))); + + container.add(Box.createVerticalStrut(15)); + container.add(scroller); + container.add(Box.createVerticalStrut(15)); + + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + fileChooser.setDialogTitle(""Choose conversion output directory""); + fileChooser.setControlButtonsAreShown(true); + fileChooser.setApproveButtonText(""Put it here""); + + fileSelectionPanel = new FileSelectionPanel(""2. Choose the output directory"", + fileChooser, UIHelper.VER_11_BOLD, UIHelper.DARK_GREEN_COLOR); + + container.add(fileSelectionPanel); + + container.add(Box.createVerticalStrut(10)); + + container.add(createButtonPanel()); + + add(container, BorderLayout.NORTH); + } + + private JPanel createButtonPanel() { + JPanel buttonContainer = new JPanel(new BorderLayout()); + + final JLabel convertButton = new JLabel(startConversion); + convertButton.addMouseListener(new MouseAdapter() { + @Override + public void mouseEntered(MouseEvent mouseEvent) { + convertButton.setIcon(startConversionOver); + } + + @Override + public void mouseExited(MouseEvent mouseEvent) { + convertButton.setIcon(startConversion); + } + + @Override + public void mousePressed(MouseEvent mouseEvent) { + convertButton.setIcon(startConversion); + firePropertyChange(""startConversion"", false, true); + } + }); + + buttonContainer.add(convertButton, BorderLayout.CENTER); + + return buttonContainer; + } + + public AllowedConversions getConversionToPerform() { + for (ConversionTargetInformationPanel panel : conversionTargetInformationPanels) { + if (panel.getConversionTarget().isSelected()) { + return panel.getConversionTarget().getTarget(); + } + } + + return AllowedConversions.ALL; + } + + public String getOutputLocation() { + return fileSelectionPanel.getSelectedFilePath(); + } + +} diff --git a/src/main/java/org/isatools/isacreator/externalutils/convertvalidate/OperatingMode.java b/src/main/java/org/isatools/isacreator/externalutils/convertvalidate/OperatingMode.java new file mode 100644 index 00000000..60873732 --- /dev/null +++ b/src/main/java/org/isatools/isacreator/externalutils/convertvalidate/OperatingMode.java @@ -0,0 +1,14 @@ +package org.isatools.isacreator.externalutils.convertvalidate; + +/** + * Created by the ISA team + * + * @author Eamonn Maguire (eamonnmag@gmail.com) + *

+ * Date: 08/09/2011 + * Time: 12:02 + */ +public enum OperatingMode { + + VALIDATE, CONVERT; +} diff --git a/src/main/java/org/isatools/isacreator/validate/ui/ValidateUI.java b/src/main/java/org/isatools/isacreator/externalutils/convertvalidate/ValidateUI.java similarity index 54% rename from src/main/java/org/isatools/isacreator/validate/ui/ValidateUI.java rename to src/main/java/org/isatools/isacreator/externalutils/convertvalidate/ValidateUI.java index 66f3a668..ec84013d 100644 --- a/src/main/java/org/isatools/isacreator/validate/ui/ValidateUI.java +++ b/src/main/java/org/isatools/isacreator/externalutils/convertvalidate/ValidateUI.java @@ -1,8 +1,9 @@ -package org.isatools.isacreator.validate.ui; +package org.isatools.isacreator.externalutils.convertvalidate; import com.sun.awt.AWTUtilities; import org.apache.log4j.Level; +import org.apache.log4j.spi.LoggingEvent; import org.isatools.errorreporter.model.ErrorLevel; import org.isatools.errorreporter.model.ErrorMessage; import org.isatools.errorreporter.model.FileType; @@ -14,12 +15,15 @@ import org.isatools.isacreator.gui.ISAcreator; import org.isatools.isacreator.gui.menu.ImportFilesMenu; import org.isatools.isacreator.model.Assay; -import org.isatools.isacreator.ontologiser.ui.OntologyHelpPane; +import org.isatools.isacreator.model.Study; import org.isatools.isacreator.settings.ISAcreatorProperties; import org.isatools.isacreator.utils.datastructures.ISAPair; +import org.isatools.isatab.gui_invokers.AllowedConversions; +import org.isatools.isatab.gui_invokers.GUIISATABConverter; import org.isatools.isatab.gui_invokers.GUIISATABValidator; import org.isatools.isatab.gui_invokers.GUIInvokerResult; import org.isatools.isatab.isaconfigurator.ISAConfigurationSet; +import org.isatools.tablib.utils.BIIObjectStore; import org.isatools.tablib.utils.logging.TabLoggingEventWrapper; import org.jdesktop.fuse.InjectedResource; import org.jdesktop.fuse.ResourceInjector; @@ -29,45 +33,31 @@ import javax.swing.border.EmptyBorder; import javax.swing.border.EtchedBorder; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; import java.util.*; import java.util.List; -/** - * Created by the ISA team - * - * @author Eamonn Maguire (eamonnmag@gmail.com) - *

- * Date: 17/08/2011 - * Time: 13:38 - */ public class ValidateUI extends JFrame { - static { ResourceInjector.addModule(""org.jdesktop.fuse.swing.SwingModule""); ResourceInjector.get(""validator-package.style"").load( - OntologyHelpPane.class.getResource(""/dependency-injections/validator-package.properties"")); - + ValidateUI.class.getResource(""/dependency-injections/validator-package.properties"")); } @InjectedResource - private Image validateIcon, validateIconInactive; + private Image validateIcon, validateIconInactive, convertIcon, convertIconInactive; @InjectedResource - private ImageIcon validationSuccess; + private ImageIcon validationSuccess, conversionSuccess; private ISAcreator isacreatorEnvironment; protected static ImageIcon validateISAAnimation = new ImageIcon(ImportFilesMenu.class.getResource(""/images/validator/validating.gif"")); + protected static ImageIcon convertISAAnimation = new ImageIcon(ImportFilesMenu.class.getResource(""/images/validator/converting.gif"")); - public static final int INCOMING = 1; - public static final int OUTGOING = -1; - - public static final float ANIMATION_DURATION = 500f; - public static final int ANIMATION_SLEEP = 10; public static final float DESIRED_OPACITY = .93f; private Timer animationTimer; @@ -78,9 +68,16 @@ public class ValidateUI extends JFrame { private long animationStart; private JPanel swappableContainer; + private OperatingMode mode; public ValidateUI(ISAcreator isacreatorEnvironment) { + this(isacreatorEnvironment, OperatingMode.VALIDATE); + } + + public ValidateUI(ISAcreator isacreatorEnvironment, OperatingMode mode) { + this.mode = mode; + ResourceInjector.get(""validator-package.style"").inject(this); this.isacreatorEnvironment = isacreatorEnvironment; @@ -88,7 +85,7 @@ public ValidateUI(ISAcreator isacreatorEnvironment) { public void createGUI() { - setTitle(""Validate ISAtab""); + setTitle(mode == OperatingMode.VALIDATE ? ""Validate ISAtab"" : ""Convert ISAtab""); setUndecorated(true); setLayout(new BorderLayout()); @@ -96,7 +93,10 @@ public void createGUI() { AWTUtilities.setWindowOpacity(this, DESIRED_OPACITY); - HUDTitleBar titlePanel = new HUDTitleBar(validateIcon, validateIconInactive); + HUDTitleBar titlePanel = new HUDTitleBar( + mode == OperatingMode.VALIDATE ? validateIcon : convertIcon, + mode == OperatingMode.VALIDATE ? validateIconInactive : convertIconInactive); + add(titlePanel, BorderLayout.NORTH); titlePanel.installListeners(); @@ -117,7 +117,6 @@ public void createGUI() { pack(); } - public void validateISAtab() { Thread performer = new Thread(new Runnable() { @@ -127,13 +126,34 @@ public void run() { ISAConfigurationSet.setConfigPath(ISAcreatorProperties.getProperty(ISAcreatorProperties.CURRENT_CONFIGURATION)); final GUIISATABValidator isatabValidator = new GUIISATABValidator(); + GUIInvokerResult result = isatabValidator.validate(ISAcreatorProperties.getProperty(ISAcreatorProperties.CURRENT_ISATAB)); if (result == GUIInvokerResult.SUCCESS) { Container successfulValidationContainer = UIHelper.padComponentVerticalBox(70, new JLabel(validationSuccess)); swapContainers(successfulValidationContainer); - } else { + if (mode == OperatingMode.CONVERT) { + + final ConvertUI convertUI = new ConvertUI(constructConversionTargets()); + convertUI.setPreferredSize(new Dimension(750, 440)); + convertUI.createGUI(); + + convertUI.addPropertyChangeListener(""startConversion"", new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent propertyChangeEvent) { + + swapContainers(UIHelper.padComponentVerticalBox(100, new JLabel(convertISAAnimation))); + convertISAtab(isatabValidator.getStore(), convertUI.getConversionToPerform(), + ISAcreatorProperties.getProperty(ISAcreatorProperties.CURRENT_ISATAB), + convertUI.getOutputLocation()); + } + }); + + swapContainers(convertUI); + + swapContainers(convertUI); + } + } else { SwingUtilities.invokeLater(new Runnable() { public void run() { @@ -157,7 +177,6 @@ public void run() { } } - for (String fileName : fileToErrors.keySet()) { ISAPair assayAndType = ValidationUtils.resolveFileTypeFromFileName(fileName, @@ -182,12 +201,95 @@ public void run() { } }); } + } }); performer.start(); } + private void convertISAtab(BIIObjectStore store, AllowedConversions conversion, + String isatabLocation, String outputLocation) { + + + GUIISATABConverter converter = new GUIISATABConverter(); + GUIInvokerResult result = converter.convert(store, isatabLocation, outputLocation, conversion); + + if (result == GUIInvokerResult.SUCCESS) { + + Box successContainer = Box.createVerticalBox(); + + successContainer.add(Box.createVerticalStrut(50)); + successContainer.add(UIHelper.wrapComponentInPanel(new JLabel(conversionSuccess))); + + successContainer.add(UIHelper.wrapComponentInPanel(UIHelper.createLabel("""" + + ""Conversion was a success."" + + ""

Files stored in "" + outputLocation + ""

"" + + """", UIHelper.VER_11_PLAIN, UIHelper.DARK_GREEN_COLOR))); + + swapContainers(successContainer); + + } else { + String topMostError = """"; + swapContainers(UIHelper.padComponentVerticalBox(100, UIHelper.createLabel(""Conversion failed. Here is why:"", + UIHelper.VER_11_PLAIN, UIHelper.DARK_GREEN_COLOR))); + + // todo show error panel to say it didn't convert.... + + for (TabLoggingEventWrapper tlew : converter.getLog()) { + LoggingEvent le = tlew.getLogEvent(); + System.out.println(le.getMessage()); + } + + + } + } + + + private Collection constructConversionTargets() { + Map conversionTargets = new HashMap(); + + Map studies = isacreatorEnvironment.getDataEntryEnvironment().getInvestigation().getStudies(); + + int totalAssays = 0; + + for (Study study : studies.values()) { + boolean add = false; + AllowedConversions conversionType = null; + for (Assay assay : study.getAssays().values()) { + String technology = assay.getTechnologyType(); + + if (technology.contains(FileType.MICROARRAY.getType())) { + add = true; + conversionType = AllowedConversions.MAGETAB; + } else if (technology.contains(FileType.MASS_SPECTROMETRY.getType())) { + add = true; + conversionType = AllowedConversions.PRIDEML; + } else if (technology.contains(FileType.NMR.getType())) { + add = true; + conversionType = AllowedConversions.PRIDEML; + } else if (technology.contains(FileType.SEQUENCING.getType())) { + add = true; + conversionType = AllowedConversions.SRA; + } + + if (add) { + if (!conversionTargets.containsKey(technology)) { + conversionTargets.put(technology, new ConversionTarget(conversionType, 1, false)); + } else { + conversionTargets.get(technology).incrementNumValidAssays(); + } + totalAssays++; + } + + } + } + + conversionTargets.put(""all"", new ConversionTarget(AllowedConversions.ALL, totalAssays, true)); + + return conversionTargets.values(); + } + private void swapContainers(Container newContainer) { if (newContainer != null) { swappableContainer.removeAll(); diff --git a/src/main/java/org/isatools/isacreator/validate/ui/ValidationUtils.java b/src/main/java/org/isatools/isacreator/externalutils/convertvalidate/ValidationUtils.java similarity index 97% rename from src/main/java/org/isatools/isacreator/validate/ui/ValidationUtils.java rename to src/main/java/org/isatools/isacreator/externalutils/convertvalidate/ValidationUtils.java index f1d11c35..ea3e1a48 100644 --- a/src/main/java/org/isatools/isacreator/validate/ui/ValidationUtils.java +++ b/src/main/java/org/isatools/isacreator/externalutils/convertvalidate/ValidationUtils.java @@ -1,4 +1,4 @@ -package org.isatools.isacreator.validate.ui; +package org.isatools.isacreator.externalutils.convertvalidate; import org.apache.log4j.spi.LoggingEvent; import org.isatools.errorreporter.model.FileType; diff --git a/src/main/java/org/isatools/isacreator/gui/ISAcreator.java b/src/main/java/org/isatools/isacreator/gui/ISAcreator.java index 1c2023e4..f38cc658 100755 --- a/src/main/java/org/isatools/isacreator/gui/ISAcreator.java +++ b/src/main/java/org/isatools/isacreator/gui/ISAcreator.java @@ -67,11 +67,8 @@ ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) import org.isatools.isacreator.spreadsheet.Spreadsheet; import org.isatools.isacreator.spreadsheet.TableReferenceObject; import org.isatools.isacreator.utils.IncorrectColumnPositioning; +import org.isatools.isacreator.externalutils.convertvalidate.*; import org.isatools.isacreator.utils.PropertyFileIO; -import org.isatools.isacreator.validate.ui.ValidateUI; -import org.isatools.isatab.gui_invokers.GUIISATABValidator; -import org.isatools.isatab.gui_invokers.GUIInvokerResult; -import org.isatools.tablib.utils.logging.TabLoggingEventWrapper; import org.jdesktop.fuse.InjectedResource; import org.jdesktop.fuse.ResourceInjector; @@ -112,9 +109,9 @@ public class ISAcreator extends AnimatableJFrame implements WindowFocusListener @InjectedResource private Image isacreatorIcon; @InjectedResource - private ImageIcon saveIcon, saveMenuIcon, saveLogoutIcon, saveExitIcon, + private ImageIcon saveIcon, saveMenuIcon, saveLogoutIcon, saveExitIcon, convertIcon, validateIcon, logoutIcon, menuIcon, exitIcon, exportArchiveIcon, addStudyIcon, - removeStudyIcon, fullScreenIcon, defaultScreenIcon, aboutIcon, helpIcon, mgRastIcon, qrCodeIcon, + removeStudyIcon, fullScreenIcon, defaultScreenIcon, aboutIcon, helpIcon, supportIcon, feedbackIcon, confirmLogout, confirmMenu, confirmExit; private AboutPanel aboutPanel; @@ -404,6 +401,44 @@ public void run() { file.add(exportISArchive); + JMenuItem validate = new JMenuItem(""Validate ISAtab"", validateIcon); + validate.addMouseListener(new MouseAdapter() { + public void mousePressed(MouseEvent mouseEvent) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + ValidateUI validateUI = new ValidateUI(ISAcreator.this, OperatingMode.VALIDATE); + validateUI.createGUI(); + validateUI.setLocationRelativeTo(ISAcreator.this); + validateUI.setVisible(true); + validateUI.validateISAtab(); + + } + }); + + } + }); + + JMenuItem convert = new JMenuItem(""Convert ISAtab"", convertIcon); + convert.addMouseListener(new MouseAdapter() { + public void mousePressed(MouseEvent mouseEvent) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + ValidateUI validateUI = new ValidateUI(ISAcreator.this, OperatingMode.CONVERT); + validateUI.createGUI(); + validateUI.setLocationRelativeTo(ISAcreator.this); + validateUI.setVisible(true); + validateUI.validateISAtab(); + + } + }); + + } + }); + + file.add(new JSeparator()); + file.add(validate); + file.add(convert); + menuBar.add(file); @@ -484,30 +519,12 @@ public void mousePressed(MouseEvent mouseEvent) { }); JMenu qrCodeExport = new JMenu(""generate QR codes for Study samples""); - qrCodeExport.setIcon(qrCodeIcon); menusRequiringStudyIds.put(""qr"", qrCodeExport); sampleTracking.add(qrCodeExport); - JMenuItem validate = new JMenuItem(""Validate ISAtab""); - validate.addMouseListener(new MouseAdapter() { - public void mousePressed(MouseEvent mouseEvent) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - ValidateUI validateUI = new ValidateUI(ISAcreator.this); - validateUI.createGUI(); - validateUI.setLocationRelativeTo(ISAcreator.this); - validateUI.setVisible(true); - validateUI.validateISAtab(); - - } - }); - - } - }); plugins.add(sampleTracking); plugins.add(tagInvestigation); - plugins.add(validate); menuBar.add(plugins); diff --git a/src/main/java/org/isatools/isacreator/io/importisa/ISAtabImporter.java b/src/main/java/org/isatools/isacreator/io/importisa/ISAtabImporter.java index 165888e4..42b2efbb 100644 --- a/src/main/java/org/isatools/isacreator/io/importisa/ISAtabImporter.java +++ b/src/main/java/org/isatools/isacreator/io/importisa/ISAtabImporter.java @@ -194,7 +194,7 @@ public boolean importFile(String parentDir) { lastConfigurationUsed = lastConfigurationUsed.substring(lastConfigurationUsed.lastIndexOf(File.separator) + 1); } - if (!lastConfigurationUsed.equals("""")) { + if (!investigation.getLastConfigurationUsed().equals("""")) { if (!lastConfigurationUsed.equals(investigation.getLastConfigurationUsed())) { messages.add(new ErrorMessage(ErrorLevel.WARNING, ""The last configuration used to load this ISAtab file was "" + investigation.getLastConfigurationUsed() + "". The currently loaded configuration is "" + lastConfigurationUsed + "". You can continue to load, but "" + ""the settings from "" + investigation.getLastConfigurationUsed() + "" may be important."")); diff --git a/src/main/java/org/isatools/isacreator/mgrast/conceptmapper/DefiniteArticlesAndConjunctions.java b/src/main/java/org/isatools/isacreator/mgrast/conceptmapper/DefiniteArticlesAndConjunctions.java deleted file mode 100644 index 410b8e07..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/conceptmapper/DefiniteArticlesAndConjunctions.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.conceptmapper; - -/** - * DefiniteArticles - * - * @author eamonnmaguire - * @date Sep 23, 2010 - */ - - -public enum DefiniteArticlesAndConjunctions { - A(""a""), AN(""an""), THE(""the""), AND(""and""); - - private String representation; - - - DefiniteArticlesAndConjunctions(String representation) { - this.representation = representation; - } - - @Override - public String toString() { - return representation; - } - - public static String buildRegexForDetection() { - return GrammarUtil.buildRegexForDetection(values()); - } -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/conceptmapper/GrammarUtil.java b/src/main/java/org/isatools/isacreator/mgrast/conceptmapper/GrammarUtil.java deleted file mode 100644 index 72ba2e61..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/conceptmapper/GrammarUtil.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.conceptmapper; - -/** - * GrammarUtil - * - * @author eamonnmaguire - * @date Sep 23, 2010 - */ - - -public class GrammarUtil { - - public static String buildRegexForDetection(Object[] values) { - StringBuilder regex = new StringBuilder(); - - int count = 0; - - for (Object prep : values) { - regex.append(""(\\b"").append(prep).append(""\\b)""); - if (count < values.length - 1) { - regex.append(""|""); - } - } - - return regex.toString(); - } - - public static String removeValuesFromString(String value, String elementsToRemove) { - return value.replaceAll(elementsToRemove, """"); - } - - public static String removeCharacterFromEndOfString(String value) { - if (value.length() > 0) { - return value.substring(0, value.length() - 1); - } - - return value; - } -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/conceptmapper/MGRastConceptIndexer.java b/src/main/java/org/isatools/isacreator/mgrast/conceptmapper/MGRastConceptIndexer.java deleted file mode 100644 index 54bad024..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/conceptmapper/MGRastConceptIndexer.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.conceptmapper; - -import jxl.Sheet; -import jxl.Workbook; -import jxl.read.biff.BiffException; -import org.apache.commons.collections15.set.ListOrderedSet; - -import java.io.File; -import java.io.IOException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -/** - * MGRastConceptIndexer - * - * @author eamonnmaguire - * @date Sep 22, 2010 - */ - - -public class MGRastConceptIndexer { - - private Map> conceptsToMGRastTerm; - - public void createIndex(File mappingFile) { - - conceptsToMGRastTerm = new HashMap>(); - Workbook w; - - try { - if (!mappingFile.isHidden()) { - w = Workbook.getWorkbook(mappingFile); - // Get the first sheet - for (Sheet s : w.getSheets()) { - if (s.getRows() > 0) { - for (int row = 0; row < s.getRows(); row++) { - String concept = s.getCell(1, row).getContents().toLowerCase(); - String mgrastKey = s.getCell(2, row).getContents(); - - if (!conceptsToMGRastTerm.containsKey(concept)) { - conceptsToMGRastTerm.put(concept, new HashSet()); - } - conceptsToMGRastTerm.get(concept).add(mgrastKey); - - } - } - } - } - - } catch (BiffException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public Map> getConceptsToMGRastTerm() { - return conceptsToMGRastTerm; - } - - public Set getAllConcepts() { - Set conceptSet = new ListOrderedSet(); - - for (String key : conceptsToMGRastTerm.keySet()) { - for (String value : conceptsToMGRastTerm.get(key)) { - conceptSet.add(value); - } - } - return conceptSet; - } -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/conceptmapper/MGRastConceptMapper.java b/src/main/java/org/isatools/isacreator/mgrast/conceptmapper/MGRastConceptMapper.java deleted file mode 100644 index 80ce6d37..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/conceptmapper/MGRastConceptMapper.java +++ /dev/null @@ -1,283 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.conceptmapper; - - -import org.isatools.isacreator.mgrast.model.ConfidenceLevel; -import org.isatools.isacreator.mgrast.model.FieldMapping; - -import java.io.File; -import java.io.FileNotFoundException; -import java.util.HashSet; -import java.util.Map; -import java.util.Scanner; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * MGRastConceptMapper - * - * @author eamonnmaguire - * @date Sep 22, 2010 - */ - - -public class MGRastConceptMapper { - - private String mappingFileLocation = ""Data"" + File.separator + ""metadata_list.xls""; - public static final String TEST_FILE = ""Data"" + File.separator + ""air_test.txt""; - - private Map> conceptsToMGRastTerm; - - private Set allMgRastConcepts; - - private Pattern toFind; - - public MGRastConceptMapper() { - createIndex(); - } - - private void createIndex() { - MGRastConceptIndexer indexCreator = new MGRastConceptIndexer(); - - File mgRastMappingFile = new File(mappingFileLocation); - - if (mgRastMappingFile.exists()) { - // continue - indexCreator.createIndex(mgRastMappingFile); - conceptsToMGRastTerm = indexCreator.getConceptsToMGRastTerm(); - allMgRastConcepts = indexCreator.getAllConcepts(); - } else { - System.err.println(""No mapping file found at : "" + mgRastMappingFile.getAbsolutePath()); - } - } - - public FieldMapping getMGRastTermFromGSCTerm(String isaTerm, String checkListType) { - - String lcISATerm = isaTerm.toLowerCase(); - - Set tuplesForGSCTerm = null; - if (conceptsToMGRastTerm != null) { - for (String value : conceptsToMGRastTerm.keySet()) { - // Since the mgrast ter - - // if the word length is too short we perform a direct match on the term. Since checking to see if - // ph is contained in something like phenotype will not give us the correct result... - if (value.length() > 4) { - // Simplest case. - if (lcISATerm.contains(value)) { - String term = interrogatePossibilitiesForCorrectTerm( - conceptsToMGRastTerm.get(value), checkListType); - - - return new FieldMapping(isaTerm, term, term.equals("""") ? ConfidenceLevel.ZERO_PERCENT : ConfidenceLevel.SEVENTY_FIVE_PERCENT); - } - // replace or insert '_' | "" "" where applicable since some terms are represented - // inconsistently. e.g.alkyl_diether could be matched by alkyl diether - else if (replaceSpacesWithUnderscores(lcISATerm).contains(value) || replaceUnderscoresWithSpaces(lcISATerm).contains(value)) { - - String term = interrogatePossibilitiesForCorrectTerm( - conceptsToMGRastTerm.get(value), checkListType); - - return new FieldMapping(isaTerm, term, term.equals("""") ? ConfidenceLevel.ZERO_PERCENT : ConfidenceLevel.SEVENTY_FIVE_PERCENT); - } - // else, when all else has failed, if the value has more than one word, we build k-tuples of the strings - // to check for presence of values - else { - if (tuplesForGSCTerm == null) { - String tmpISATerm = cleanupString(isaTerm.toLowerCase()); - tuplesForGSCTerm = buildKTuples(tmpISATerm); - } - - for (String tuple : tuplesForGSCTerm) { - if (value.contains(tuple)) { - - String term = interrogatePossibilitiesForCorrectTerm( - conceptsToMGRastTerm.get(value), checkListType); - - return new FieldMapping(isaTerm, term, term.equals("""") ? ConfidenceLevel.ZERO_PERCENT : ConfidenceLevel.FIFTY_PERCENT); - } - } - } - - } else { - String tmpISATerm = cleanupString(isaTerm.toLowerCase()); - - if (value.equalsIgnoreCase(tmpISATerm)) { - - String term = interrogatePossibilitiesForCorrectTerm( - conceptsToMGRastTerm.get(value), checkListType); - - return new FieldMapping(isaTerm, term, term.equals("""") ? ConfidenceLevel.ZERO_PERCENT : ConfidenceLevel.SEVENTY_FIVE_PERCENT); - } - } - } - } - - return new FieldMapping(isaTerm, """", ConfidenceLevel.ZERO_PERCENT); - - } - - private String replaceSpacesWithUnderscores(String toModify) { - return toModify.replaceAll(""\\s+"", ""_""); - } - - private String replaceUnderscoresWithSpaces(String toModify) { - return toModify.replaceAll(""_"", ""+""); - } - - private String cleanupString(String toClean) { - return toClean.replaceAll(""(characteristics\\[)|(factor value\\[)|(parameter value\\[)|(comment\\[)|\\]"", """"); - } - - /** - * Method builds all the permutations of a number of words, removing prepositions and definite/indefinite articles - * - * @param toPermutate String to split and move words around in - * @return Set representating all permutations. - */ - private Set buildKTuples(String toPermutate) { - // prepare the String by removing all definite/indefinite articles and removing prepositions - - toPermutate = GrammarUtil.removeValuesFromString(toPermutate, DefiniteArticlesAndConjunctions.buildRegexForDetection()); - toPermutate = GrammarUtil.removeValuesFromString(toPermutate, Prepositions.buildRegexForDetection()); - - String[] words = toPermutate.split(""\\s+|_""); - - Set result = new HashSet(); - - for (int outerLoop = 0; outerLoop < words.length; outerLoop++) { - for (int innerLoop = 0; innerLoop < words.length; innerLoop++) { - // miss doubling the same word - if (outerLoop != innerLoop) { - result.add(words[outerLoop] + "" "" + words[innerLoop]); - } - } - } - - return result; - } - - - private String interrogatePossibilitiesForCorrectTerm(Set possibleConcepts, String checkListType) { - - if (possibleConcepts != null) { - if (possibleConcepts.size() == 1) { - return possibleConcepts.iterator().next(); - } else { - for (String candidateConcept : possibleConcepts) { - - if (findChecklist(candidateConcept)) { - return candidateConcept; - } - - } - } - } - - return """"; - - } - - private boolean findChecklist(String text) { - if (toFind == null) { - toFind = Pattern.compile(""(air)|(sample-origin)|(sample-isolation)|(host)|(human)|(microbial)|(miscellaneous)|(plant)|(sediment)|(water)|(soil)""); - } - - Matcher m = toFind.matcher(text); - return m.find(); - } - - private Set createTestDataFromFile() { - File testData = new File(TEST_FILE); - - Set testTerms = new HashSet(); - - if (testData.exists()) { - try { - Scanner fileScanner = new Scanner(testData); - - while (fileScanner.hasNextLine()) { - String value = fileScanner.nextLine().trim().toLowerCase(); - testTerms.add(value); - } - - } catch (FileNotFoundException e) { - System.err.println(""File not found""); - } - - - } else { - System.err.println(""Test data doesn't exist""); - - } - return testTerms; - } - - - public static void main(String[] args) { - MGRastConceptMapper mapper = new MGRastConceptMapper(); - - Set testData = mapper.createTestDataFromFile(); - - System.out.println(""Testing with "" + testData.size() + "" terms""); - - StringBuffer buffer = new StringBuffer(); - - int failCount = 0; - for (String testItem : testData) { - FieldMapping mgRastTerm = mapper.getMGRastTermFromGSCTerm(testItem, ""air""); - if (mgRastTerm.getConfidenceLevel() == ConfidenceLevel.ZERO_PERCENT) { - failCount++; - } - buffer.append(testItem).append(""\t"").append(mgRastTerm).append(""\n""); - } - - System.out.println(""Success matched = "" + (testData.size() - failCount) + ""/"" + testData.size()); - - System.out.println(); - - System.out.println(buffer.toString()); - - } - - public Set getAllMgRastConcepts() { - return allMgRastConcepts; - } -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/conceptmapper/Prepositions.java b/src/main/java/org/isatools/isacreator/mgrast/conceptmapper/Prepositions.java deleted file mode 100644 index a8a71762..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/conceptmapper/Prepositions.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.conceptmapper; - -/** - * Prepositions - * - * @author eamonnmaguire - * @date Sep 23, 2010 - */ -public enum Prepositions { - BENEATH(""beneath""), AGAINST(""against""), BESIDE(""beside""), DURING(""during""), ABOUT(""about""), - ABOVE(""above""), ACROSS(""across""), AFTER(""after""), ALONG(""along""), AMONG(""among""), AROUND(""around""), AT(""at""), BEFORE(""before""), - BEHIND(""behind""), BELOW(""below""), BETWEEN(""betwen""), BEYOND(""beyond""), BUT(""but""), BY(""by""), DESPITE(""despite""), DOWN(""down""), - EXCEPT(""except""), FOR(""for""), FROM(""from""), IN(""in""), INSIDE(""inside""), INTO(""into""), LIKE(""like""), NEAR(""near""), OF(""of""), - OFF(""off""), ON(""on""), ONTO(""onto""), OUT(""out""), OUTSIDE(""outside""), OVER(""over""), PAST(""past""), SINCE(""since""), THROUGH(""through""), - THROUGHOUT(""throughout""), TILL(""till""), TO(""to""), TOWARD(""toward""), UNDER(""under""), UNDERNEATH(""underneath""), UNTIL(""until""), UP(""up""), - UPON(""upon""), WITH(""with""), WITHIN(""within""), WITHOUT(""without""); - - private String representation; - - Prepositions(String representation) { - this.representation = representation; - } - - @Override - public String toString() { - return representation; - } - - public static String buildRegexForDetection() { - return GrammarUtil.buildRegexForDetection(values()); - } -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/io/FileExporter.java b/src/main/java/org/isatools/isacreator/mgrast/io/FileExporter.java deleted file mode 100644 index 2a9f51a4..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/io/FileExporter.java +++ /dev/null @@ -1,155 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.io; - -import org.apache.log4j.Logger; -import org.isatools.isacreator.mgrast.model.*; -import org.isatools.isacreator.mgrast.ui.ExtraMetaDataPane; -import org.isatools.isacreator.mgrast.utils.APIHook; -import org.isatools.isacreator.utils.PropertyFileIO; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.PrintStream; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -/** - * FileExporter - * - * @author eamonnmaguire - * @date Oct 1, 2010 - */ - - -public class FileExporter { - - private static final Logger log = Logger.getLogger(FileExporter.class.getName()); - public static final String MAPPING_HISTORY_FILE = ""mgRastMappingHistory.properties""; - - public FileExporter() { - - } - - public void outputFiles(File outputDirectory, Map fieldMappings, List sampleExtIds, ExtraMetaDataPane metaData, APIHook apiHook) { - - // try to map out files - StringBuilder projectMetadata = new ProjectMetadataAdapter(metaData).getDataFromMetaDataPane(); - - Map>> sampleToData = apiHook.getDataForSamples(apiHook.getSampleNames()); - - - // for each sample, we want to output 1 or more files (more in case of replicates...) - for (SampleExternalIds seId : sampleExtIds) { - Map samplesToOutput = new HashMap(); - - StringBuilder sampleDescription = new StringBuilder(); - sampleDescription.append(""project-description_metagenome_name"").append(""\t"").append(seId.getSampleName()).append(""\n""); - - sampleDescription.append(projectMetadata); - - for (ExternalResources er : seId.getExternalIds().keySet()) { - sampleDescription.append(er.getMgRastTerm()).append(""\t"").append(seId.getExternalIds().get(er)).append(""\n""); - } - - for (String dataColumn : sampleToData.get(seId.getSampleName()).keySet()) { - if (fieldMappings.containsKey(dataColumn)) { - // get mg_rast term if one exists. if no mapping exists, don't output it. - FieldMapping fm = fieldMappings.get(dataColumn); - if (fm.getConfidenceLevel() != ConfidenceLevel.ZERO_PERCENT) { - List columnValues = sampleToData.get(seId.getSampleName()).get(dataColumn); - - for (int valueCount = 0; valueCount < columnValues.size(); valueCount++) { - if (!samplesToOutput.containsKey(valueCount)) { - samplesToOutput.put(valueCount, new StringBuilder()); - } - - // todo look here at what happens - samplesToOutput.get(valueCount).append(fm.getMgRastTermMappedTo()).append(""\t"") - .append(sampleToData.get(seId.getSampleName()).get(dataColumn).get(valueCount)).append(""\n""); - } - } - } - } - - for (int samples : samplesToOutput.keySet()) { - outputFileToDirectory(outputDirectory, seId.getSampleName(), sampleDescription.append(samplesToOutput.get(samples)), samples); - } - } - } - - private void outputFileToDirectory(File outputDirectory, String sampleName, StringBuilder output, int count) { - - File enclosingDir = new File(outputDirectory.getAbsolutePath() + File.separator + ""MGRastExport""); - - if (!enclosingDir.exists()) { - enclosingDir.mkdir(); - } - - File newFile = new File(enclosingDir.getAbsolutePath() + File.separator + sampleName + (count == 0 ? """" : ""-"" + (count + 1)) + ""-mgrast.txt""); - - try { - PrintStream ps = new PrintStream(newFile); - - ps.print(output.toString()); - - ps.close(); - - } catch (FileNotFoundException e) { - System.err.println(e.getMessage()); - log.error(e); - } - } - - public Properties loadMappingHistory() { - Properties mappings = PropertyFileIO.loadSettings(MAPPING_HISTORY_FILE); - if (mappings == null) { - mappings = new Properties(); - } - - return mappings; - } - - public void saveMappingHistory(Properties toSave) { - PropertyFileIO.saveProperties(toSave, MAPPING_HISTORY_FILE); - } - - -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/model/ConfidenceLevel.java b/src/main/java/org/isatools/isacreator/mgrast/model/ConfidenceLevel.java deleted file mode 100644 index d5ab0b77..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/model/ConfidenceLevel.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.model; - -/** - * ConfidenceLevel - *

- * Represents levels of confidence in some assumption. - * - * @author eamonnmaguire - * @date Sep 29, 2010 - */ -public enum ConfidenceLevel { - ONE_HUNDRED_PERCENT, SEVENTY_FIVE_PERCENT, FIFTY_PERCENT, TWENTY_FIVE_PERCENT, ZERO_PERCENT -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/model/ExternalResources.java b/src/main/java/org/isatools/isacreator/mgrast/model/ExternalResources.java deleted file mode 100644 index 42ca5966..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/model/ExternalResources.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.model; - -/** - * ExternalResources - * - * @author eamonnmaguire - * @date Sep 28, 2010 - */ -public enum ExternalResources { - - GOLD(""GOLD Id"", ""external-Ids_gold_id""); - private String uiId; - private String mgRastTerm; - - ExternalResources(String uiId, String mgRastTerm) { - this.uiId = uiId; - this.mgRastTerm = mgRastTerm; - } - - public String getUiId() { - return uiId; - } - - public String getMgRastTerm() { - return mgRastTerm; - } - - public String toString() { - return getUiId(); - } -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/model/FieldMapping.java b/src/main/java/org/isatools/isacreator/mgrast/model/FieldMapping.java deleted file mode 100644 index c99b09c9..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/model/FieldMapping.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.model; - -/** - * FieldMapping - *

- * Represents a mapping between an ISAtab field and a concept in MG-Rast with a confidence level in the mapping. - *

- * Confidence levels are calculated based on the way the mapping was performed. E.g. in the algorithm, if a direct mapping - * was found, the level would be 100%, however, if there is any doubt in the final mapping, as a result of undefined checklist - * type, e.g. not specifying that the checklist is defining air samples, the mapping confidence will immediately drop to 50%. - *

- * If the user manually selects a mapping after the automatic mapping was performed, the confidence level will be set at 100% - * since we assume the selection is correct...perhaps wrongly? - * - * @author eamonnmaguire - * @date Sep 29, 2010 - */ - - -public class FieldMapping { - - private String isatabFieldName; - private String mgRastTermMappedTo; - private ConfidenceLevel confidenceLevel; - - public FieldMapping(String isatabFieldName, String mgRastTermMappedTo, ConfidenceLevel confidenceLevel) { - this.isatabFieldName = isatabFieldName; - this.mgRastTermMappedTo = mgRastTermMappedTo; - this.confidenceLevel = confidenceLevel; - } - - public ConfidenceLevel getConfidenceLevel() { - return confidenceLevel; - } - - public String getIsatabFieldName() { - return isatabFieldName; - } - - public String getMgRastTermMappedTo() { - return mgRastTermMappedTo; - } - - public String toString() { - return isatabFieldName; - } - - public void setConfidenceLevel(ConfidenceLevel confidenceLevel) { - this.confidenceLevel = confidenceLevel; - } - - public void setMgRastTermMappedTo(String mgRastTermMappedTo) { - this.mgRastTermMappedTo = mgRastTermMappedTo; - } -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/model/ProjectMetadataAdapter.java b/src/main/java/org/isatools/isacreator/mgrast/model/ProjectMetadataAdapter.java deleted file mode 100644 index e58c5abe..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/model/ProjectMetadataAdapter.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.model; - -import org.isatools.isacreator.mgrast.ui.ExtraMetaDataPane; -import org.isatools.isacreator.model.Contact; - -/** - * ProjectMetadataAdapter - * Attaches on to an ExtraMetaDataPane UI component to extract it's information and prepare it for output. - * - * @author eamonnmaguire - * @date Oct 1, 2010 - */ - - -public class ProjectMetadataAdapter { - private static final String ADMIN_CONTACT_PREFIX = ""administrative-contact_PI_""; - private static final String TECHNICAL_CONTACT_PREFIX = ""technical-contact_""; - - - private ExtraMetaDataPane metaDataPane; - - public ProjectMetadataAdapter(ExtraMetaDataPane metaDataPane) { - - this.metaDataPane = metaDataPane; - } - - public StringBuilder getDataFromMetaDataPane() { - StringBuilder output = new StringBuilder(); - - output.append(""project-description_internal_project_ID"").append(""\t"").append(metaDataPane.getInternalProjectId()).append(""\n""); - output.append(""project-description_project_name"").append(""\t"").append(metaDataPane.getProjectName()).append(""\n""); - output.append(""project-description_project_description"").append(""\t\"""").append(metaDataPane.getProjectDescription()).append(""\"""").append(""\n""); - output.append(""external-ids_pubmed_id"").append(""\t"").append(metaDataPane.getPubmedId()).append(""\n""); - output.append(""external-ids_project_id"").append(""\t"").append(metaDataPane.getNCBIProjectId()).append(""\n""); - output.append(""external-ids_greengenes_study_id"").append(""\t"").append(metaDataPane.getGreenegenesStudyId()).append(""\n""); - - buildContactSection(output, metaDataPane.getAdminContact(), ADMIN_CONTACT_PREFIX); - buildContactSection(output, metaDataPane.getTechnicalContact(), TECHNICAL_CONTACT_PREFIX); - - return output; - } - - private void buildContactSection(StringBuilder output, Contact contact, String sectionPrefix) { - output.append(sectionPrefix).append(""firstname"").append(""\t"").append(contact.getFirstName()).append(""\n""); - output.append(sectionPrefix).append(""lastname"").append(""\t"").append(contact.getLastName()).append(""\n""); - output.append(sectionPrefix).append(""email"").append(""\t"").append(contact.getEmail()).append(""\n""); - output.append(sectionPrefix).append(""organization"").append(""\t"").append(contact.getAffiliation()).append(""\n""); - output.append(sectionPrefix).append(""organization_address"").append(""\t"").append(contact.getAddress()).append(""\n""); - output.append(sectionPrefix).append(""url"").append(""\t"").append("""").append(""\n""); - - } -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/model/SampleExternalIds.java b/src/main/java/org/isatools/isacreator/mgrast/model/SampleExternalIds.java deleted file mode 100644 index 8d54cbb1..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/model/SampleExternalIds.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.model; - -import java.util.HashMap; -import java.util.Map; - -/** - * SampleExternalIds - * - * @author Eamonn Maguire - * @date Sep 28, 2010 - */ - - -public class SampleExternalIds { - - private String sampleName; - - private Map externalIds; - - public SampleExternalIds(String sampleName) { - this.sampleName = sampleName; - externalIds = new HashMap(); - } - - public String getSampleName() { - return sampleName; - } - - public Map getExternalIds() { - return externalIds; - } - - - /** - * Returns a value for an ExternalResources type given an External resource. R - * - * @param resource - @see ExternalResources - * @return null if no value available, a String otherwise. - */ - public String getValueByExternalResource(ExternalResources resource) { - if (externalIds.containsKey(resource)) { - return externalIds.get(resource); - } - - return """"; - } - - @Override - public String toString() { - return sampleName; - } -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/ui/ExternalIdListCellRenderer.java b/src/main/java/org/isatools/isacreator/mgrast/ui/ExternalIdListCellRenderer.java deleted file mode 100644 index 4c644899..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/ui/ExternalIdListCellRenderer.java +++ /dev/null @@ -1,142 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.ui; - -import org.isatools.isacreator.common.UIHelper; -import org.isatools.isacreator.mgrast.model.ExternalResources; -import org.isatools.isacreator.mgrast.model.SampleExternalIds; -import org.jdesktop.fuse.InjectedResource; -import org.jdesktop.fuse.ResourceInjector; - -import javax.swing.*; -import javax.swing.border.EmptyBorder; -import java.awt.*; - -/** - * ExternalIdListCellRenderer - * - * @author eamonnmaguire - * @date Sep 28, 2010 - */ - - -public class ExternalIdListCellRenderer extends JComponent - implements ListCellRenderer { - - @InjectedResource - private ImageIcon idEntered, noIdEntered; - - private DefaultListCellRenderer listCellRenderer; - - public ExternalIdListCellRenderer() { - setLayout(new BorderLayout()); - setBackground(Color.WHITE); - - ResourceInjector.get(""exporter-package.style"").inject(this); - - add(new IDEnteredListCellmage(), BorderLayout.WEST); - - listCellRenderer = new DefaultListCellRenderer(); - add(listCellRenderer, BorderLayout.CENTER); - - setBorder(new EmptyBorder(2, 2, 2, 2)); - } - - - public Component getListCellRendererComponent(JList list, Object value, int index, boolean selected, boolean cellGotFocus) { - listCellRenderer.getListCellRendererComponent(list, value, index, - selected, cellGotFocus); - listCellRenderer.setBorder(null); - - //image.checkIsIdEntered(selected); - Component[] components = getComponents(); - - SampleExternalIds sampleObj = (SampleExternalIds) value; - - for (Component c : components) { - ((JComponent) c).setToolTipText(value.toString()); - if (c instanceof IDEnteredListCellmage) { - ((IDEnteredListCellmage) c).checkIsIdEntered(sampleObj); - } else { - if (selected) { - c.setForeground(UIHelper.GREY_COLOR); - c.setBackground(UIHelper.BG_COLOR); - c.setFont(UIHelper.VER_11_BOLD); - } else { - c.setForeground(UIHelper.LIGHT_GREEN_COLOR); - c.setBackground(UIHelper.BG_COLOR); - c.setFont(UIHelper.VER_11_BOLD); - } - } - } - - - return this; - } - - class IDEnteredListCellmage extends JPanel { - // this will contain the general panel layout for the list item and modifier elements to allow for changing of images - // when rendering an item as being selected and so forth. - private JLabel itemSelectedIndicator; - - IDEnteredListCellmage() { - setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); - itemSelectedIndicator = new JLabel(noIdEntered); - - add(itemSelectedIndicator); - add(Box.createHorizontalStrut(2)); - } - - public void checkIsIdEntered(SampleExternalIds sampleId) { - - boolean valueEntered = false; - for (ExternalResources er : sampleId.getExternalIds().keySet()) { - if (!sampleId.getExternalIds().get(er).trim().equals("""")) { - valueEntered = true; - break; - } - } - - if (valueEntered) { - itemSelectedIndicator.setIcon(idEntered); - } else { - itemSelectedIndicator.setIcon(noIdEntered); - } - } - } -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/ui/ExtraMetaDataPane.java b/src/main/java/org/isatools/isacreator/mgrast/ui/ExtraMetaDataPane.java deleted file mode 100644 index 3657438b..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/ui/ExtraMetaDataPane.java +++ /dev/null @@ -1,266 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.ui; - -import com.explodingpixels.macwidgets.IAppWidgetFactory; -import org.isatools.isacreator.common.CustomTextField; -import org.isatools.isacreator.common.UIHelper; -import org.isatools.isacreator.model.Contact; - -import javax.swing.*; -import javax.swing.border.LineBorder; -import java.awt.*; -import java.util.List; - -/** - * ExtraMetaDataPane contains the entry fields for extra metadata items such as external project ids - * and so forth. - * - * @author Eamonn Maguire - * @date Sep 24, 2010 - */ - - -public class ExtraMetaDataPane extends JPanel { - - // fields required for: - // - project name - internal project id - technical contact - administrative contact - ncbi project id - - private CustomTextField projectName; - private JTextArea projectDescription; - - private CustomTextField pubmedId; - private CustomTextField ncbiProjectId; - private CustomTextField internalProjectId; - private CustomTextField greengenesStudyId; - - private JComboBox technicalContact; - private JComboBox administrativeContact; - private List contacts; - - // COMBO box for technical contact - // COMBO box for administrative contact - - public ExtraMetaDataPane() { - - createGUI(); - } - - private void createGUI() { - setLayout(new BorderLayout()); - setBackground(UIHelper.BG_COLOR); - createDataEntryFields(); - layoutItemsOnScreen(); - } - - private void createDataEntryFields() { - // should be set to the study id. - projectName = new CustomTextField(""project name"", true, new Dimension(160, 18)); - pubmedId = new CustomTextField(""pubmed id"", false, new Dimension(110, 18)); - ncbiProjectId = new CustomTextField(""ncbi project id"", false, new Dimension(130, 18)); - internalProjectId = new CustomTextField(""internal project id"", false, new Dimension(110, 18)); - greengenesStudyId = new CustomTextField(""greengenes study id"", false, new Dimension(130, 18)); - - createComboBoxes(); - - } - - private Container createTextAreaEntry() { - - // should be set to the study description. - projectDescription = new JTextArea(); - UIHelper.renderComponent(projectDescription, UIHelper.VER_10_BOLD, UIHelper.GREY_COLOR, UIHelper.BG_COLOR); - projectDescription.setLineWrap(true); - projectDescription.setWrapStyleWord(true); - - JScrollPane projectDescScroller = new JScrollPane(projectDescription, - JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); - - projectDescScroller.setBorder(new LineBorder(UIHelper.GREY_COLOR, 1)); - projectDescScroller.getViewport().setBackground(UIHelper.BG_COLOR); - projectDescScroller.setPreferredSize(new Dimension(140, 40)); - - IAppWidgetFactory.makeIAppScrollPane(projectDescScroller); - - // add text editor button here? I think I will :) - - return projectDescScroller; - } - - private void createComboBoxes() { - - String[] contactsAsArray = new String[]{""nothing""}; - - technicalContact = new JComboBox(contactsAsArray); - technicalContact.setPreferredSize(new Dimension(140, 20)); - UIHelper.renderComponent(technicalContact, UIHelper.VER_10_BOLD, UIHelper.GREY_COLOR, UIHelper.BG_COLOR); - UIHelper.setJComboBoxAsHeavyweight(technicalContact); - - administrativeContact = new JComboBox(contactsAsArray); - administrativeContact.setPreferredSize(new Dimension(140, 20)); - UIHelper.renderComponent(administrativeContact, UIHelper.VER_10_BOLD, UIHelper.GREY_COLOR, UIHelper.BG_COLOR); - UIHelper.setJComboBoxAsHeavyweight(administrativeContact); - } - - private void layoutItemsOnScreen() { - - Box container = Box.createHorizontalBox(); - - Box g1 = Box.createVerticalBox(); - g1.add(projectName); - g1.add(prepareComponentForInsertion(""project description"", createTextAreaEntry(), 6)); - - // add project description here - - container.add(g1); - - Box g2 = Box.createVerticalBox(); - g2.add(internalProjectId); - g2.add(pubmedId); - container.add(g2); - - Box g3 = Box.createVerticalBox(); - g3.add(ncbiProjectId); - g3.add(greengenesStudyId); - - container.add(g3); - - Box g4 = Box.createVerticalBox(); - g4.add(prepareComponentForInsertion(""admin contact"", administrativeContact, 0)); - g4.add(prepareComponentForInsertion(""technical contact"", technicalContact, 0)); - - container.add(g4); - - add(container, BorderLayout.WEST); - } - - private Container prepareComponentForInsertion(String componentLabel, Component c, int leftPadding) { - Box container = Box.createVerticalBox(); - - Box labelContainer = Box.createHorizontalBox(); - - JLabel field = UIHelper.createLabel(componentLabel, UIHelper.VER_10_BOLD, UIHelper.GREY_COLOR, SwingConstants.LEFT); - labelContainer.add(Box.createHorizontalStrut(leftPadding)); - labelContainer.add(UIHelper.wrapComponentInPanel(field)); - - container.add(labelContainer); - - Box componentContainer = Box.createHorizontalBox(); - - componentContainer.add(Box.createHorizontalStrut(leftPadding)); - componentContainer.add(c); - componentContainer.add(Box.createHorizontalStrut(18)); - - container.add(componentContainer); - - return container; - } - - public void setContacts(List contacts) { - this.contacts = contacts; - - technicalContact.removeAllItems(); - administrativeContact.removeAllItems(); - - for (Contact c : contacts) { - technicalContact.addItem(c); - administrativeContact.addItem(c); - } - } - - public boolean areAllFieldsValid() { - return projectName.isValidInput(); - } - - public void setPubmedId(String projectIdentifier) { - pubmedId.setText(projectIdentifier); - } - - public String getPubmedId() { - return pubmedId.getText(); - } - - public void setProjectName(String projectName) { - this.projectName.setText(projectName); - } - - public String getProjectName() { - return projectName.getText(); - } - - public void setProjectDescription(String projectDesc) { - projectDescription.setText(projectDesc); - } - - public String getProjectDescription() { - return projectDescription.getText(); - } - - public void setInternalProjectId(String internalProjectIdentifier) { - internalProjectId.setText(internalProjectIdentifier); - } - - public String getInternalProjectId() { - return internalProjectId.getText(); - } - - public void setNCBIProjectId(String ncbiProjectIdentifier) { - ncbiProjectId.setText(ncbiProjectIdentifier); - } - - public String getNCBIProjectId() { - return ncbiProjectId.getText(); - } - - public void setGreenegenesStudyId(String greenegenesStudyIdentifier) { - greengenesStudyId.setText(greenegenesStudyIdentifier); - } - - public String getGreenegenesStudyId() { - return greengenesStudyId.getText(); - } - - public Contact getAdminContact() { - return (Contact) administrativeContact.getSelectedItem(); - } - - public Contact getTechnicalContact() { - return (Contact) technicalContact.getSelectedItem(); - } - -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/ui/HelpPane.java b/src/main/java/org/isatools/isacreator/mgrast/ui/HelpPane.java deleted file mode 100644 index a93a4f80..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/ui/HelpPane.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.ui; - -import org.isatools.isacreator.common.UIHelper; -import org.jdesktop.fuse.InjectedResource; -import org.jdesktop.fuse.ResourceInjector; - -import javax.swing.*; -import java.awt.*; - -/** - * HelpPane - * - * @author eamonnmaguire - * @date Sep 24, 2010 - */ - - -public class HelpPane extends JPanel { - - @InjectedResource - private ImageIcon helpImage; - - public HelpPane() { - ResourceInjector.get(""exporters-package.style"").inject(this); - setLayout(new BorderLayout()); - setBackground(UIHelper.BG_COLOR); - } - - public void createGUI() { - JLabel helpContainer = new JLabel(helpImage); - add(UIHelper.wrapComponentInPanel(helpContainer)); - } - - -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/ui/MGRastConceptListCellRenderer.java b/src/main/java/org/isatools/isacreator/mgrast/ui/MGRastConceptListCellRenderer.java deleted file mode 100644 index 8ed29232..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/ui/MGRastConceptListCellRenderer.java +++ /dev/null @@ -1,135 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.ui; - -import org.isatools.isacreator.common.UIHelper; -import org.jdesktop.fuse.InjectedResource; -import org.jdesktop.fuse.ResourceInjector; - -import javax.swing.*; -import javax.swing.border.EmptyBorder; -import java.awt.*; - -/** - * MGRastConceptListCellRenderer - * - * @author eamonnmaguire - * @date Sep 28, 2010 - */ - - -public class MGRastConceptListCellRenderer extends JComponent - implements ListCellRenderer { - - - @InjectedResource - private ImageIcon mappedTo, notMappedTo; - // renderer will show which MGrast concept is mapped to the selected - // ISAtab file term. - private DefaultListCellRenderer listCellRenderer; - - - public MGRastConceptListCellRenderer() { - setLayout(new BorderLayout()); - setBackground(Color.WHITE); - - ResourceInjector.get(""exporters-package.style"").inject(this); - - add(new CellImage(), BorderLayout.WEST); - - listCellRenderer = new DefaultListCellRenderer(); - - - add(listCellRenderer, BorderLayout.CENTER); - - setBorder(new EmptyBorder(2, 2, 2, 2)); - } - - public Component getListCellRendererComponent(JList list, Object value, int index, boolean selected, boolean cellGotFocus) { - listCellRenderer.getListCellRendererComponent(list, value, index, - selected, cellGotFocus); - listCellRenderer.setBorder(null); - - //image.checkIsIdEntered(selected); - Component[] components = getComponents(); - - for (Component c : components) { - ((JComponent) c).setToolTipText(value.toString()); - if (c instanceof CellImage) { - ((CellImage) c).setSelected(selected); - } else { - if (selected) { - c.setForeground(UIHelper.GREY_COLOR); - c.setBackground(UIHelper.BG_COLOR); - c.setFont(UIHelper.VER_11_BOLD); - - } else { - c.setForeground(UIHelper.LIGHT_GREEN_COLOR); - c.setBackground(UIHelper.BG_COLOR); - c.setFont(UIHelper.VER_11_BOLD); - } - } - } - - - return this; - } - - class CellImage extends JPanel { - // this will contain the general panel layout for the list item and modifier elements to allow for changing of images - // when rendering an item as being selected and so forth. - private JLabel itemSelectedIndicator; - - CellImage() { - setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); - itemSelectedIndicator = new JLabel(notMappedTo); - - add(itemSelectedIndicator); - add(Box.createHorizontalStrut(2)); - } - - public void setSelected(boolean selected) { - - if (selected) { - itemSelectedIndicator.setIcon(mappedTo); - } else { - itemSelectedIndicator.setIcon(notMappedTo); - } - } - } -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/ui/MGRastUI.java b/src/main/java/org/isatools/isacreator/mgrast/ui/MGRastUI.java deleted file mode 100644 index a4b4022f..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/ui/MGRastUI.java +++ /dev/null @@ -1,564 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.ui; - -import org.isatools.isacreator.archiveoutput.ArchiveOutputWindow; -import org.isatools.isacreator.common.SelectOutputDirectoryDialog; -import org.isatools.isacreator.common.UIHelper; -import org.isatools.isacreator.common.dialog.ConfirmationDialog; -import org.isatools.isacreator.common.dialog.WarningDialog; -import org.isatools.isacreator.gui.ISAcreator; -import org.isatools.isacreator.mgrast.conceptmapper.MGRastConceptMapper; -import org.isatools.isacreator.mgrast.io.FileExporter; -import org.isatools.isacreator.mgrast.model.ConfidenceLevel; -import org.isatools.isacreator.mgrast.model.FieldMapping; -import org.isatools.isacreator.mgrast.model.SampleExternalIds; -import org.isatools.isacreator.mgrast.utils.APIHook; -import org.isatools.isacreator.model.Publication; -import org.isatools.isacreator.model.Study; -import org.jdesktop.fuse.InjectedResource; -import org.jdesktop.fuse.ResourceInjector; - -import javax.swing.*; -import javax.swing.border.EtchedBorder; -import java.awt.*; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.File; -import java.util.*; -import java.util.List; - -/** - * MGRastUI - * - * @author eamonnmaguire - * @date Sep 24, 2010 - */ - - -public class MGRastUI extends JDialog { - - static { - ResourceInjector.addModule(""org.jdesktop.fuse.swing.SwingModule""); - - ResourceInjector.get(""exporters-package.style"").load( - ArchiveOutputWindow.class.getResource(""/dependency-injections/exporters-package.properties"")); - ResourceInjector.get(""common-package.style"").load( - ArchiveOutputWindow.class.getResource(""/dependency-injections/common-package.properties"")); - ResourceInjector.get(""longtexteditor-package.style"").load( - ArchiveOutputWindow.class.getResource(""/dependency-injections/longtexteditor-package.properties"")); - - } - - - private ConfirmationDialog confirmChoice; - - public static final int MAPPING_INFO = 0; - public static final int SAMPLE_INFO = 1; - public static final int HELP = 2; - - @InjectedResource - private ImageIcon mgRastHeader, mgRastExportSampleSection, weKnowIcon, weKnowIconOver, weDoNotKnowIcon, - weDoNotKnowIconOver, helpIcon, helpIconOver, closeWindowIcon, closeWindowIconOver, exportIcon, - exportIconOver, buttonPanelSeparator, loadingSamples, mappingConcepts, noProjectNameWarning, exportHeader; - - private JPanel swappableContainer; - - private JLabel mappingInfoButton, sampleInfoButton, helpButton; - - private int selectedSection = HELP; - - private HelpPane helpPane; - private ExtraMetaDataPane projectMetadata; - private SampleInfoPane sampleInfoPane; - private TermMappingUI termMappingPane; - private ISAcreator isacreatorEnvironment; - private APIHook mgRastAPIHook; - - private FileExporter fileUtils; - private Properties mappingHistory; - - private Map fieldMappings; - private List externalIds; - - public MGRastUI(ISAcreator isacreatorEnvironment) { - this.isacreatorEnvironment = isacreatorEnvironment; - ResourceInjector.get(""exporters-package.style"").inject(this); - projectMetadata = new ExtraMetaDataPane(); - fileUtils = new FileExporter(); - } - - public void createGUI() { - setBackground(UIHelper.BG_COLOR); - setUndecorated(true); - setLayout(new BorderLayout()); - setPreferredSize(new Dimension(650, 560)); - ((JComponent) getContentPane()).setBorder(new EtchedBorder(UIHelper.GREY_COLOR, UIHelper.GREY_COLOR)); - - - add(createTopPanel(), BorderLayout.NORTH); - - swappableContainer = new JPanel(); - swappableContainer.setPreferredSize(new Dimension(650, 340)); - helpPane = new HelpPane(); - helpPane.createGUI(); - - swappableContainer.add(helpPane); - - add(swappableContainer, BorderLayout.CENTER); - add(createSouthPanel(), BorderLayout.SOUTH); - - pack(); - } - - private Container createSouthPanel() { - Box southPanel = Box.createHorizontalBox(); - southPanel.setBackground(UIHelper.BG_COLOR); - - final JLabel closeButton = new JLabel(closeWindowIcon); - closeButton.addMouseListener(new MouseAdapter() { - @Override - public void mouseEntered(MouseEvent mouseEvent) { - closeButton.setIcon(closeWindowIconOver); - } - - @Override - public void mouseExited(MouseEvent mouseEvent) { - closeButton.setIcon(closeWindowIcon); - } - - @Override - public void mousePressed(MouseEvent mouseEvent) { - confirmChoice = new ConfirmationDialog(); - - confirmChoice.addPropertyChangeListener(ConfirmationDialog.NO, new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent propertyChangeEvent) { - confirmChoice.hideDialog(); - confirmChoice.dispose(); - } - }); - - confirmChoice.addPropertyChangeListener(ConfirmationDialog.YES, new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent propertyChangeEvent) { - confirmChoice.hideDialog(); - confirmChoice.dispose(); - closeWindow(); - } - }); - - SwingUtilities.invokeLater(new Runnable() { - public void run() { - confirmChoice.createGUI(); - confirmChoice.showDialog(isacreatorEnvironment); - } - }); - - - } - }); - - final JLabel export = new JLabel(exportIcon); - export.addMouseListener(new MouseAdapter() { - @Override - public void mouseEntered(MouseEvent mouseEvent) { - export.setIcon(exportIconOver); - } - - @Override - public void mouseExited(MouseEvent mouseEvent) { - export.setIcon(exportIcon); - } - - @Override - public void mousePressed(MouseEvent mouseEvent) { - final SelectOutputDirectoryDialog outputDir = new SelectOutputDirectoryDialog(exportHeader); - - - outputDir.addPropertyChangeListener(SelectOutputDirectoryDialog.CANCEL, new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent propertyChangeEvent) { - outputDir.hideDialog(); - outputDir.dispose(); - } - }); - - outputDir.addPropertyChangeListener(SelectOutputDirectoryDialog.CONTINUE, new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent propertyChangeEvent) { - outputDir.hideDialog(); - outputDir.dispose(); - - // precautionary measure in case the user has not selected sample ids tab. - if (externalIds == null) { - constructSampleIds(); - } - - System.out.println(""dir selected = "" + propertyChangeEvent.getNewValue().toString()); - - fileUtils.outputFiles(new File(propertyChangeEvent.getNewValue().toString()), - fieldMappings, externalIds, projectMetadata, mgRastAPIHook); - - // todo should we store confidence levels as well? - for (String isaField : fieldMappings.keySet()) { - FieldMapping fm = fieldMappings.get(isaField); - if (fm.getConfidenceLevel() != ConfidenceLevel.ZERO_PERCENT) { - mappingHistory.setProperty(isaField, fm.getMgRastTermMappedTo()); - } - } - - fileUtils.saveMappingHistory(mappingHistory); - - // if successful, close window! - closeWindow(); - } - }); - - if (projectMetadata.areAllFieldsValid()) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - outputDir.createGUI(); - outputDir.showDialog(MGRastUI.this); - } - }); - - } else { - final WarningDialog warningDialog = new WarningDialog(noProjectNameWarning); - - - warningDialog.addPropertyChangeListener(WarningDialog.OK, new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent propertyChangeEvent) { - warningDialog.hideDialog(); - warningDialog.dispose(); - } - }); - - - SwingUtilities.invokeLater(new Runnable() { - public void run() { - warningDialog.createGUI(); - warningDialog.showDialog(isacreatorEnvironment); - } - }); - - } - } - }); - - southPanel.add(closeButton); - southPanel.add(new JLabel(buttonPanelSeparator)); - southPanel.add(export); - - return southPanel; - } - - public void loadAndMapData(String studyId) { - mgRastAPIHook = new APIHook(isacreatorEnvironment, studyId); - setProjectMetadataFromStudyInformation(isacreatorEnvironment.getDataEntryEnvironment() - .getInvestigation().getStudies().get(studyId)); - } - - private void setProjectMetadataFromStudyInformation(Study study) { - projectMetadata.setContacts(study.getContacts()); - - String pubmedIds = """"; - if (study.getPublications().size() > 0) { - int count = 0; - for (Publication pub : study.getPublications()) { - if (pub.getPubmedId() != null) { - if (!pub.getPubmedId().isEmpty()) { - pubmedIds += pub.getPubmedId(); - if (count != study.getPublications().size() - 1) { - pubmedIds += "", ""; - } - } - } - count++; - } - } - - projectMetadata.setPubmedId(pubmedIds); - projectMetadata.setProjectName(study.getStudyTitle()); - projectMetadata.setProjectDescription(study.getStudyDesc()); - projectMetadata.setInternalProjectId(study.getStudyId()); - } - - private void closeWindow() { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - isacreatorEnvironment.hideSheet(); - } - }); - } - - private Container createTopPanel() { - - Box topContainer = Box.createVerticalBox(); - - JLabel mgRastExporterHeader = new JLabel(mgRastHeader); - mgRastExporterHeader.setHorizontalAlignment(SwingConstants.LEFT); - - topContainer.add(UIHelper.wrapComponentInPanel(mgRastExporterHeader)); - - - topContainer.add(projectMetadata); - - Box topPanel = Box.createHorizontalBox(); - - JLabel mgRastLogo = new JLabel(mgRastExportSampleSection); - mgRastLogo.setHorizontalAlignment(SwingConstants.LEFT); - - mappingInfoButton = new JLabel(weKnowIcon); - mappingInfoButton.setHorizontalAlignment(SwingConstants.LEFT); - - mappingInfoButton.addMouseListener(new MouseAdapter() { - @Override - public void mouseEntered(MouseEvent mouseEvent) { - mappingInfoButton.setIcon(weKnowIconOver); - } - - @Override - public void mouseExited(MouseEvent mouseEvent) { - - mappingInfoButton.setIcon(selectedSection == MAPPING_INFO ? weKnowIconOver : weKnowIcon); - } - - @Override - public void mousePressed(MouseEvent mouseEvent) { - resetButtons(); - mappingInfoButton.setIcon(weKnowIconOver); - selectedSection = MAPPING_INFO; - - - if (termMappingPane == null) { - - Thread performer = new Thread(new Runnable() { - public void run() { - try { - - Set isatabFields = mgRastAPIHook.getISAtabFields(); - - fieldMappings = new HashMap(); - - MGRastConceptMapper mapper = new MGRastConceptMapper(); - - // check properties file to see if mapping exists here. - mappingHistory = fileUtils.loadMappingHistory(); - - for (String isaField : isatabFields) { - FieldMapping fm; - - boolean mappingHistoryTermAvailable = mappingHistory.containsKey(isaField); - - if (!mappingHistoryTermAvailable) { - fm = mapper.getMGRastTermFromGSCTerm(isaField, """"); - } else { - fm = new FieldMapping(isaField, mappingHistory.getProperty(isaField), ConfidenceLevel.ONE_HUNDRED_PERCENT); - } - fieldMappings.put(isaField, fm); - } - - termMappingPane = new TermMappingUI(fieldMappings, mapper.getAllMgRastConcepts()); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - termMappingPane.createGUI(); - swapContainers(termMappingPane); - } - }); - } catch (Exception e) { - System.err.println(""Problem occured whilst loading samples: "" + e.getMessage()); - e.printStackTrace(); - } - } - }); - - - swapContainers(UIHelper.wrapComponentInPanel(new JLabel(mappingConcepts))); - - performer.start(); - - - } else { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - swapContainers(termMappingPane); - } - }); - } - } - }); - - sampleInfoButton = new JLabel(weDoNotKnowIcon); - sampleInfoButton.setHorizontalAlignment(SwingConstants.LEFT); - - sampleInfoButton.addMouseListener(new MouseAdapter() { - @Override - public void mouseEntered(MouseEvent mouseEvent) { - sampleInfoButton.setIcon(weDoNotKnowIconOver); - } - - @Override - public void mouseExited(MouseEvent mouseEvent) { - - sampleInfoButton.setIcon(selectedSection == SAMPLE_INFO ? weDoNotKnowIconOver : weDoNotKnowIcon); - } - - @Override - public void mousePressed(MouseEvent mouseEvent) { - resetButtons(); - sampleInfoButton.setIcon(weDoNotKnowIconOver); - selectedSection = SAMPLE_INFO; - - if (sampleInfoPane == null) { - - Thread performer = new Thread(new Runnable() { - public void run() { - try { - - constructSampleIds(); - - sampleInfoPane = new SampleInfoPane(externalIds); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - sampleInfoPane.createGUI(); - swapContainers(sampleInfoPane); - } - }); - } catch (Exception e) { - System.err.println(""Problem occured whilst loading samples: "" + e.getMessage()); - e.printStackTrace(); - } - } - }); - - - swapContainers(UIHelper.wrapComponentInPanel(new JLabel(loadingSamples))); - - performer.start(); - - - } else { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - swapContainers(sampleInfoPane); - } - }); - } - } - }); - - helpButton = new JLabel(helpIconOver); - helpButton.setHorizontalAlignment(SwingConstants.LEFT); - - helpButton.addMouseListener(new MouseAdapter() { - @Override - public void mouseEntered(MouseEvent mouseEvent) { - helpButton.setIcon(helpIconOver); - } - - @Override - public void mouseExited(MouseEvent mouseEvent) { - helpButton.setIcon(selectedSection == HELP ? helpIconOver : helpIcon); - } - - @Override - public void mousePressed(MouseEvent mouseEvent) { - resetButtons(); - selectedSection = HELP; - helpButton.setIcon(helpIconOver); - - if (helpPane == null) { - helpPane = new HelpPane(); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - helpPane.createGUI(); - } - }); - } - - SwingUtilities.invokeLater(new Runnable() { - public void run() { - swapContainers(helpPane); - } - }); - } - }); - - topPanel.add(mgRastLogo); - topPanel.add(mappingInfoButton); - topPanel.add(sampleInfoButton); - topPanel.add(helpButton); - - topContainer.add(topPanel); - - return topContainer; - } - - private void constructSampleIds() { - Set sampleNames = mgRastAPIHook.getSampleNames(); - - externalIds = new ArrayList(); - - for (String sampleName : sampleNames) { - externalIds.add(new SampleExternalIds(sampleName)); - } - } - - private void resetButtons() { - mappingInfoButton.setIcon(weKnowIcon); - sampleInfoButton.setIcon(weDoNotKnowIcon); - helpButton.setIcon(helpIcon); - } - - private void swapContainers(Container newContainer) { - if (newContainer != null) { - swappableContainer.removeAll(); - swappableContainer.add(newContainer); - swappableContainer.repaint(); - swappableContainer.validate(); - } - } - - public static void main(String[] args) { - final MGRastUI mgRastUI = new MGRastUI(null); - EventQueue.invokeLater(new Runnable() { - public void run() { - mgRastUI.createGUI(); - } - }); - } -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/ui/MappingConfidenceListCellRenderer.java b/src/main/java/org/isatools/isacreator/mgrast/ui/MappingConfidenceListCellRenderer.java deleted file mode 100644 index ec8d65e7..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/ui/MappingConfidenceListCellRenderer.java +++ /dev/null @@ -1,144 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.ui; - -import org.isatools.isacreator.common.UIHelper; -import org.isatools.isacreator.mgrast.model.ConfidenceLevel; -import org.isatools.isacreator.mgrast.model.FieldMapping; -import org.jdesktop.fuse.InjectedResource; -import org.jdesktop.fuse.ResourceInjector; - -import javax.swing.*; -import javax.swing.border.EmptyBorder; -import java.awt.*; - -/** - * MappingConfidenceListCellRenderer - * - * @author eamonnmaguire - * @date Sep 28, 2010 - */ - - -public class MappingConfidenceListCellRenderer extends JComponent - implements ListCellRenderer { - - @InjectedResource - private ImageIcon oneHundredPercent, seventyFivePercent, - fiftyPercent, twentyFivePercent, zeroPercent; - - private DefaultListCellRenderer listCellRenderer; - - public MappingConfidenceListCellRenderer() { - setLayout(new BorderLayout()); - setBackground(Color.WHITE); - - ResourceInjector.get(""exporters-package.style"").inject(this); - - add(new ConfidenceLevelCellImage(), BorderLayout.WEST); - - listCellRenderer = new DefaultListCellRenderer(); - - add(listCellRenderer, BorderLayout.CENTER); - - setBorder(new EmptyBorder(2, 2, 2, 2)); - } - - public Component getListCellRendererComponent(JList list, Object value, int index, boolean selected, boolean cellGotFocus) { - listCellRenderer.getListCellRendererComponent(list, value, index, - selected, cellGotFocus); - listCellRenderer.setBorder(null); - - //image.checkIsIdEntered(selected); - Component[] components = getComponents(); - - for (Component c : components) { - ((JComponent) c).setToolTipText(value.toString()); - if (c instanceof ConfidenceLevelCellImage) { - if (value instanceof FieldMapping) { - ((ConfidenceLevelCellImage) c).setConfidenceLevel((FieldMapping) value); - } - } else { - if (selected) { - c.setForeground(UIHelper.GREY_COLOR); - c.setBackground(UIHelper.BG_COLOR); - c.setFont(UIHelper.VER_11_BOLD); - - } else { - c.setForeground(UIHelper.LIGHT_GREEN_COLOR); - c.setBackground(UIHelper.BG_COLOR); - c.setFont(UIHelper.VER_11_BOLD); - } - } - } - - - return this; - } - - class ConfidenceLevelCellImage extends JPanel { - // this will contain the general panel layout for the list item and modifier elements to allow for changing of images - // when rendering an item as being selected and so forth. - private JLabel itemSelectedIndicator; - - ConfidenceLevelCellImage() { - setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); - itemSelectedIndicator = new JLabel(zeroPercent); - - add(itemSelectedIndicator); - add(Box.createHorizontalStrut(2)); - } - - public void setConfidenceLevel(FieldMapping fieldMapping) { - - ConfidenceLevel level = fieldMapping.getConfidenceLevel(); - - if (level == ConfidenceLevel.ONE_HUNDRED_PERCENT) { - itemSelectedIndicator.setIcon(oneHundredPercent); - } else if (level == ConfidenceLevel.SEVENTY_FIVE_PERCENT) { - itemSelectedIndicator.setIcon(seventyFivePercent); - } else if (level == ConfidenceLevel.FIFTY_PERCENT) { - itemSelectedIndicator.setIcon(fiftyPercent); - } else if (level == ConfidenceLevel.TWENTY_FIVE_PERCENT) { - itemSelectedIndicator.setIcon(twentyFivePercent); - } else { - itemSelectedIndicator.setIcon(zeroPercent); - } - } - } -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/ui/SampleInfoPane.java b/src/main/java/org/isatools/isacreator/mgrast/ui/SampleInfoPane.java deleted file mode 100644 index 39ffbcd6..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/ui/SampleInfoPane.java +++ /dev/null @@ -1,256 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.ui; - -import com.explodingpixels.macwidgets.IAppWidgetFactory; -import org.isatools.isacreator.autofilteringlist.ExtendedJList; -import org.isatools.isacreator.common.ClearFieldUtility; -import org.isatools.isacreator.common.CustomTextField; -import org.isatools.isacreator.common.UIHelper; -import org.isatools.isacreator.effects.borders.RoundedBorder; -import org.isatools.isacreator.mgrast.model.ExternalResources; -import org.isatools.isacreator.mgrast.model.SampleExternalIds; -import org.jdesktop.fuse.InjectedResource; -import org.jdesktop.fuse.ResourceInjector; - -import javax.swing.*; -import javax.swing.border.EmptyBorder; -import javax.swing.border.TitledBorder; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import java.awt.*; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.List; - -/** - * SampleInfoPane - * - * @author eamonnmaguire - * @date Sep 24, 2010 - */ - - -public class SampleInfoPane extends JPanel { - - @InjectedResource - private ImageIcon externalReferencesHeader, externalReferenceInfo, key; - - private ExtendedJList sampleList; - private List samples; - - private JLabel sampleReferenceInformation; - - private SampleExternalIds currentSample; - - private CustomTextField goldIdField; - - public SampleInfoPane(List samples) { - this.samples = samples; - ResourceInjector.get(""exporters-package.style"").inject(this); - } - - public void createGUI() { - setLayout(new BorderLayout()); - setBackground(UIHelper.BG_COLOR); - createAndAddSampleList(); - updateSampleReferenceInfo(); - createAndAddIDPane(); - updateIdFields(); - } - - - private void createAndAddSampleList() { - - JPanel container = new JPanel(new BorderLayout()); - container.setPreferredSize(new Dimension(315, 300)); - container.setBackground(UIHelper.BG_COLOR); - - sampleList = new ExtendedJList(new ExternalIdListCellRenderer(), true); - - updateListContents(); - - - if (sampleList.getItems().size() > 0) { - try { - sampleList.setSelectedIndex(0); - currentSample = samples.get(sampleList.getSelectedIndex()); - - } catch (Exception e) { - e.printStackTrace(); - } - } - - sampleList.addPropertyChangeListener(""itemSelected"", new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent propertyChangeEvent) { - currentSample = (SampleExternalIds) propertyChangeEvent.getNewValue(); - updateIdFields(); - goldIdField.getTextField().setEnabled(true); - } - }); - - sampleList.addPropertyChangeListener(""zeroTerms"", new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent propertyChangeEvent) { - currentSample = null; - goldIdField.setText(""no sample selected""); - goldIdField.getTextField().setEnabled(false); - } - }); - - JScrollPane historyScroll = new JScrollPane(sampleList, - JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, - JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - - historyScroll.setBorder(new EmptyBorder(1, 1, 1, 1)); - - IAppWidgetFactory.makeIAppScrollPane(historyScroll); - - - UIHelper.renderComponent(sampleList.getFilterField(), UIHelper.VER_11_BOLD, UIHelper.GREY_COLOR, false); - - Box fieldContainer = Box.createHorizontalBox(); - fieldContainer.add(sampleList.getFilterField()); - fieldContainer.add(new ClearFieldUtility(sampleList.getFilterField())); - - container.add(fieldContainer, BorderLayout.NORTH); - container.add(historyScroll, BorderLayout.CENTER); - - Box infoPanel = Box.createVerticalBox(); - infoPanel.setBackground(UIHelper.BG_COLOR); - - JLabel infoKey = new JLabel(key); - infoKey.setHorizontalAlignment(SwingConstants.LEFT); - - sampleReferenceInformation = UIHelper.createLabel("""", UIHelper.VER_10_PLAIN, UIHelper.GREY_COLOR, SwingConstants.LEFT); - - infoPanel.add(infoKey); - infoPanel.add(Box.createVerticalStrut(5)); - infoPanel.add(sampleReferenceInformation); - - container.add(infoPanel, BorderLayout.SOUTH); - container.setBorder(new TitledBorder(new RoundedBorder(UIHelper.GREY_COLOR, 3), ""Samples"", - TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, UIHelper.VER_11_BOLD, - UIHelper.GREY_COLOR)); - - add(container, BorderLayout.WEST); - } - - private void updateIdFields() { - if (currentSample != null) { - goldIdField.setText(currentSample.getValueByExternalResource(ExternalResources.GOLD)); - } - } - - private void createAndAddIDPane() { - JPanel container = new JPanel(new BorderLayout()); - container.setBackground(UIHelper.BG_COLOR); - container.setPreferredSize(new Dimension(325, 300)); - - Box idsContainer = Box.createVerticalBox(); - - JLabel headerImage = new JLabel(externalReferencesHeader); - headerImage.setHorizontalAlignment(SwingConstants.RIGHT); - - idsContainer.add(UIHelper.wrapComponentInPanel(headerImage)); - idsContainer.add(Box.createVerticalStrut(10)); - - JLabel infoImage = new JLabel(externalReferenceInfo); - infoImage.setHorizontalAlignment(SwingConstants.LEFT); - - idsContainer.add(UIHelper.wrapComponentInPanel(infoImage)); - idsContainer.add(Box.createVerticalStrut(5)); - - goldIdField = new CustomTextField(ExternalResources.GOLD.getUiId(), false, - UIHelper.VER_11_BOLD, UIHelper.GREY_COLOR, new Dimension(150, 20), false); - - goldIdField.getTextField().getDocument().addDocumentListener(new DocumentListener() { - - public void insertUpdate(DocumentEvent event) { - - setValidityIndicator(); - } - - public void removeUpdate(DocumentEvent event) { - setValidityIndicator(); - } - - public void changedUpdate(DocumentEvent event) { - setValidityIndicator(); - } - - private void setValidityIndicator() { - if (currentSample != null) { - currentSample.getExternalIds().put(ExternalResources.GOLD, goldIdField.getText()); - updateSampleReferenceInfo(); - sampleList.validate(); - sampleList.repaint(); - } - } - }); - - idsContainer.add(goldIdField); - container.add(idsContainer, BorderLayout.NORTH); - add(container, BorderLayout.EAST); - } - - private void updateListContents() { - sampleList.getItems().clear(); - for (SampleExternalIds seId : samples) { - sampleList.addItem(seId); - } - } - - private void updateSampleReferenceInfo() { - - int annotatedCount = 0; - for (SampleExternalIds seId : samples) { - for (ExternalResources er : seId.getExternalIds().keySet()) { - if (!seId.getExternalIds().get(er).trim().equals("""")) { - annotatedCount++; - } - } - } - - - StringBuffer information = new StringBuffer(); - information.append("""").append(samples.size()) - .append("" samples of which "").append(annotatedCount).append("" have ids assigned""); - - sampleReferenceInformation.setText(information.toString()); - } -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/ui/TermMappingUI.java b/src/main/java/org/isatools/isacreator/mgrast/ui/TermMappingUI.java deleted file mode 100644 index 4d398561..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/ui/TermMappingUI.java +++ /dev/null @@ -1,423 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.ui; - -import com.explodingpixels.macwidgets.IAppWidgetFactory; -import org.isatools.isacreator.autofilteringlist.ExtendedJList; -import org.isatools.isacreator.common.ClearFieldUtility; -import org.isatools.isacreator.common.UIHelper; -import org.isatools.isacreator.effects.borders.RoundedBorder; -import org.isatools.isacreator.mgrast.model.ConfidenceLevel; -import org.isatools.isacreator.mgrast.model.FieldMapping; -import org.jdesktop.fuse.InjectedResource; -import org.jdesktop.fuse.ResourceInjector; - -import javax.swing.*; -import javax.swing.border.EmptyBorder; -import javax.swing.border.TitledBorder; -import java.awt.*; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.Map; -import java.util.Set; - -/** - * TermMappingUI - * - * @author eamonnmaguire - * @date Sep 24, 2010 - */ - - -public class TermMappingUI extends JPanel { - - @InjectedResource - private ImageIcon confidenceKey, attentionIcon, confirmIcon, confirmIconOver, rejectIcon, rejectIconOver, mappedToIcon; - - private ExtendedJList isatabFieldsList; - private ExtendedJList mgrastFieldsList; - - private FieldMapping currentlySelectedField; - - private JPanel questionPanel; - - private Set mgRastConcepts; - private Map fieldMappings; - - - public TermMappingUI(Map fieldMappings, Set mgRastConcepts) { - ResourceInjector.get(""exporters-package.style"").inject(this); - this.fieldMappings = fieldMappings; - this.mgRastConcepts = mgRastConcepts; - } - - public void createGUI() { - setLayout(new BorderLayout()); - setBackground(UIHelper.BG_COLOR); - createISAtabFieldListPane(); - createMGRastConceptsListPane(); - - updateMGRastListContents(); - updateISAListContents(); - } - - private void createISAtabFieldListPane() { - isatabFieldsList = new ExtendedJList(new MappingConfidenceListCellRenderer(), true); - - // todo add property change listener to detect itemselected and zeroItem events. - isatabFieldsList.addPropertyChangeListener(""itemSelected"", new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent propertyChangeEvent) { - currentlySelectedField = (FieldMapping) propertyChangeEvent.getNewValue(); - if (mgrastFieldsList != null) { - - if (currentlySelectedField.getMgRastTermMappedTo() == null) { - currentlySelectedField.setMgRastTermMappedTo(""""); - } - - if (currentlySelectedField.getMgRastTermMappedTo().equals("""")) { - mgrastFieldsList.clearSelection(); - checkAndDisplayAppropriateQuestion(currentlySelectedField.getMgRastTermMappedTo()); - } else { - mgrastFieldsList.setSelectedValue(currentlySelectedField.getMgRastTermMappedTo(), true); - } - } - } - }); - - JPanel container = createListPanel(isatabFieldsList); - container.setBorder(new TitledBorder(new RoundedBorder(UIHelper.GREY_COLOR, 3), ""ISAtab fields"", - TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, UIHelper.VER_11_BOLD, - UIHelper.GREY_COLOR)); - - JLabel infoKey = new JLabel(confidenceKey); - infoKey.setHorizontalAlignment(SwingConstants.LEFT); - - container.add(UIHelper.wrapComponentInPanel(infoKey), BorderLayout.SOUTH); - add(container, BorderLayout.WEST); - } - - private void createMGRastConceptsListPane() { - mgrastFieldsList = new ExtendedJList(new MGRastConceptListCellRenderer(), false); - - questionPanel = new JPanel(); - questionPanel.setPreferredSize(new Dimension(315, 60)); - questionPanel.setLayout(new BoxLayout(questionPanel, BoxLayout.LINE_AXIS)); - - mgrastFieldsList.addPropertyChangeListener(""itemSelected"", new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent propertyChangeEvent) { - checkAndDisplayAppropriateQuestion(propertyChangeEvent.getNewValue().toString()); - } - }); - - mgrastFieldsList.setAutoscrolls(true); - - JPanel container = new JPanel(new BorderLayout()); - container.setBackground(UIHelper.BG_COLOR); - - JPanel listContainer = createListPanel(mgrastFieldsList); - listContainer.setBorder(new TitledBorder(new RoundedBorder(UIHelper.GREY_COLOR, 3), ""MG-Rast concepts"", - TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, UIHelper.VER_11_BOLD, - UIHelper.GREY_COLOR)); - updateMGRastListContents(); - - container.add(listContainer); - - container.add(questionPanel, BorderLayout.SOUTH); - - add(container, BorderLayout.EAST); - } - - private JPanel createListPanel(ExtendedJList list) { - - - JPanel listContainer = new JPanel(new BorderLayout()); - listContainer.setPreferredSize(new Dimension(315, 270)); - listContainer.setBackground(UIHelper.BG_COLOR); - - JScrollPane mgRastConceptScroller = new JScrollPane(list, - JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, - JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - mgRastConceptScroller.setBorder(new EmptyBorder(1, 1, 1, 1)); - - IAppWidgetFactory.makeIAppScrollPane(mgRastConceptScroller); - - UIHelper.renderComponent(list.getFilterField(), UIHelper.VER_11_BOLD, UIHelper.GREY_COLOR, false); - - Box fieldContainer = Box.createHorizontalBox(); - fieldContainer.add(list.getFilterField()); - fieldContainer.add(new ClearFieldUtility(list.getFilterField())); - - listContainer.add(fieldContainer, BorderLayout.NORTH); - listContainer.add(mgRastConceptScroller, BorderLayout.CENTER); - - return listContainer; - } - - private void updateISAListContents() { - isatabFieldsList.getItems().clear(); - - for (String isaField : fieldMappings.keySet()) { - isatabFieldsList.addItem(fieldMappings.get(isaField)); - } - - if (isatabFieldsList.getItems().size() > 0) { - isatabFieldsList.setSelectedIndex(0); - if (mgrastFieldsList != null) { - mgrastFieldsList.setSelectedValue(currentlySelectedField.getMgRastTermMappedTo(), true); - checkAndDisplayAppropriateQuestion(currentlySelectedField.getMgRastTermMappedTo()); - } - } - } - - /** - * show confirm box if confidence level is below 100% or change info if the item selected is different - * to that already stored. - * - * @param newValue - mgRast value entered. - */ - private void checkAndDisplayAppropriateQuestion(String newValue) { - - if (newValue.equals(currentlySelectedField.getMgRastTermMappedTo()) && !newValue.equals("""")) { - if (currentlySelectedField.getConfidenceLevel() != ConfidenceLevel.ONE_HUNDRED_PERCENT) { - changeQuestionPanelContents(createConfirmMappingPanel()); - } else { - changeQuestionPanelContents(createMappedToInfo()); - } - } else if (newValue == null || newValue.equals("""")) { - changeQuestionPanelContents(createMappedToInfo()); - } else { - changeQuestionPanelContents(createChangeMappingPanel()); - } - } - - private Container createConfirmMappingPanel() { - Box confirmMappingPane = Box.createVerticalBox(); - confirmMappingPane.setBackground(UIHelper.BG_COLOR); - - JLabel question = UIHelper.createLabel(""confirm this mapping?"", UIHelper.VER_10_BOLD, UIHelper.GREY_COLOR); - question.setIcon(attentionIcon); - - confirmMappingPane.add(UIHelper.wrapComponentInPanel(question)); - - confirmMappingPane.add(createMappedToInfo()); - - Box mappingInfo = Box.createHorizontalBox(); - - final JLabel confirmMapping = new JLabel(confirmIcon); - confirmMapping.addMouseListener(new MouseAdapter() { - @Override - public void mouseEntered(MouseEvent mouseEvent) { - confirmMapping.setIcon(confirmIconOver); - } - - @Override - public void mouseExited(MouseEvent mouseEvent) { - confirmMapping.setIcon(confirmIcon); - } - - @Override - public void mousePressed(MouseEvent mouseEvent) { - confirmMapping.setIcon(confirmIcon); - currentlySelectedField.setMgRastTermMappedTo(mgrastFieldsList.getSelectedTerm()); - currentlySelectedField.setConfidenceLevel(ConfidenceLevel.ONE_HUNDRED_PERCENT); - - SwingUtilities.invokeLater(new Runnable() { - public void run() { - changeQuestionPanelContents(createMappedToInfo()); - isatabFieldsList.validate(); - isatabFieldsList.repaint(); - } - }); - } - }); - - final JLabel rejectMapping = new JLabel(rejectIcon); - rejectMapping.addMouseListener(new MouseAdapter() { - @Override - public void mouseEntered(MouseEvent mouseEvent) { - rejectMapping.setIcon(rejectIconOver); - } - - @Override - public void mouseExited(MouseEvent mouseEvent) { - rejectMapping.setIcon(rejectIcon); - } - - @Override - public void mousePressed(MouseEvent mouseEvent) { - rejectMapping.setIcon(rejectIcon); - currentlySelectedField.setMgRastTermMappedTo(""""); - currentlySelectedField.setConfidenceLevel(ConfidenceLevel.ZERO_PERCENT); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - changeQuestionPanelContents(createMappedToInfo()); - isatabFieldsList.validate(); - isatabFieldsList.repaint(); - } - }); - - - } - }); - - mappingInfo.add(Box.createHorizontalStrut(5)); - mappingInfo.add(confirmMapping); - mappingInfo.add(rejectMapping); - - confirmMappingPane.add(mappingInfo); - - return confirmMappingPane; - } - - private Container createMappedToInfo() { - Box mappingInfo = Box.createHorizontalBox(); - mappingInfo.setBackground(UIHelper.BG_COLOR); - - JLabel isaField = UIHelper.createLabel(currentlySelectedField.getIsatabFieldName(), UIHelper.VER_9_BOLD, UIHelper.LIGHT_GREEN_COLOR); - isaField.setPreferredSize(new Dimension(120, 20)); - - mappingInfo.add(isaField); - mappingInfo.add(new JLabel(mappedToIcon)); - - JLabel mgRastTerm = UIHelper.createLabel(mgrastFieldsList.getSelectedTerm(), UIHelper.VER_9_BOLD, UIHelper.GREY_COLOR); - mgRastTerm.setPreferredSize(new Dimension(120, 20)); - mappingInfo.add(mgRastTerm); - - return mappingInfo; - } - - private Container createChangeMappingPanel() { - Box confirmMappingPane = Box.createVerticalBox(); - confirmMappingPane.setBackground(UIHelper.BG_COLOR); - - JLabel question = UIHelper.createLabel(""change to this mapping?"", UIHelper.VER_10_BOLD, UIHelper.GREY_COLOR); - question.setIcon(attentionIcon); - - confirmMappingPane.add(UIHelper.wrapComponentInPanel(question)); - - confirmMappingPane.add(createMappedToInfo()); - - Box mappingInfo = Box.createHorizontalBox(); - - final JLabel confirmMapping = new JLabel(confirmIcon); - confirmMapping.addMouseListener(new MouseAdapter() { - @Override - public void mouseEntered(MouseEvent mouseEvent) { - confirmMapping.setIcon(confirmIconOver); - } - - @Override - public void mouseExited(MouseEvent mouseEvent) { - confirmMapping.setIcon(confirmIcon); - } - - @Override - public void mousePressed(MouseEvent mouseEvent) { - confirmMapping.setIcon(confirmIcon); - currentlySelectedField.setMgRastTermMappedTo(mgrastFieldsList.getSelectedTerm()); - currentlySelectedField.setConfidenceLevel(ConfidenceLevel.ONE_HUNDRED_PERCENT); - - SwingUtilities.invokeLater(new Runnable() { - public void run() { - changeQuestionPanelContents(createMappedToInfo()); - isatabFieldsList.validate(); - isatabFieldsList.repaint(); - } - }); - } - }); - - final JLabel rejectMapping = new JLabel(rejectIcon); - rejectMapping.addMouseListener(new MouseAdapter() { - @Override - public void mouseEntered(MouseEvent mouseEvent) { - rejectMapping.setIcon(rejectIconOver); - } - - @Override - public void mouseExited(MouseEvent mouseEvent) { - rejectMapping.setIcon(rejectIcon); - } - - @Override - public void mousePressed(MouseEvent mouseEvent) { - rejectMapping.setIcon(rejectIcon); - mgrastFieldsList.setSelectedValue(currentlySelectedField.getMgRastTermMappedTo(), true); - - SwingUtilities.invokeLater(new Runnable() { - public void run() { - checkAndDisplayAppropriateQuestion(currentlySelectedField.getMgRastTermMappedTo()); - isatabFieldsList.validate(); - isatabFieldsList.repaint(); - } - }); - } - }); - - mappingInfo.add(Box.createHorizontalStrut(5)); - mappingInfo.add(confirmMapping); - mappingInfo.add(rejectMapping); - - confirmMappingPane.add(mappingInfo); - - return confirmMappingPane; - } - - private void updateMGRastListContents() { - mgrastFieldsList.getItems().clear(); - - for (String mgRastConcept : mgRastConcepts) { - mgrastFieldsList.addItem(mgRastConcept); - } - } - - private void changeQuestionPanelContents(final Container newContainer) { - if (newContainer != null) { - questionPanel.removeAll(); - questionPanel.add(newContainer); - questionPanel.repaint(); - questionPanel.validate(); - } - } - - - // two extended JLists - one containing the headers from ISAcreator - the merging of the study sample table and the - // assay table of interest. the other containing the mgrast terms. -} diff --git a/src/main/java/org/isatools/isacreator/mgrast/utils/APIHook.java b/src/main/java/org/isatools/isacreator/mgrast/utils/APIHook.java deleted file mode 100644 index 1c105743..00000000 --- a/src/main/java/org/isatools/isacreator/mgrast/utils/APIHook.java +++ /dev/null @@ -1,281 +0,0 @@ -/** - ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) - - License: - ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) - - EXHIBIT A. CPAL version 1.0 - ÒThe contents of this file are subject to the CPAL version 1.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://isa-tools.org/licenses/ISAcreator-license.html. - The License is based on the Mozilla Public License version 1.1 but Sections - 14 and 15 have been added to cover use of software over a computer network and - provide for limited attribution for the Original Developer. In addition, Exhibit - A has been modified to be consistent with Exhibit B. - - Software distributed under the License is distributed on an ÒAS ISÓ basis, - WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for - the specific language governing rights and limitations under the License. - - The Original Code is ISAcreator. - The Original Developer is the Initial Developer. The Initial Developer of the - Original Code is the ISA Team (Eamonn Maguire, eamonnmag@gmail.com; - Philippe Rocca-Serra, proccaserra@gmail.com; Susanna-Assunta Sansone, sa.sanson@gmail.com; - http://www.isa-tools.org). All portions of the code written by the ISA Team are - Copyright (c) 2007-2011 ISA Team. All Rights Reserved. - - EXHIBIT B. Attribution Information - Attribution Copyright Notice: Copyright (c) 2008-2011 ISA Team - Attribution Phrase: Developed by the ISA Team - Attribution URL: http://www.isa-tools.org - Graphic Image provided in the Covered Code as file: http://isa-tools.org/licenses/icons/poweredByISAtools.png - Display of Attribution Information is required in Larger Works which are defined in the CPAL as a work which combines Covered Code or portions thereof with code not governed by the terms of the CPAL. - - Sponsors: - The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). - */ - -package org.isatools.isacreator.mgrast.utils; - -import org.apache.commons.collections15.set.ListOrderedSet; -import org.isatools.isacreator.apiutils.SpreadsheetUtils; -import org.isatools.isacreator.gui.ISAcreator; -import org.isatools.isacreator.model.Assay; -import org.isatools.isacreator.model.Investigation; -import org.isatools.isacreator.model.Study; -import org.isatools.isacreator.spreadsheet.Spreadsheet; - -import java.util.*; - -/** - * APIHook - * - * @author eamonnmaguire - * @date Sep 30, 2010 - */ - - -public class APIHook { - private ISAcreator isacreatorEnvironment; - private String studyId; - - // Map contains mapping from either - private Map> isatabFields; - private Map studyOrAssayToSampleNameColumn; - private Set sampleNames; - - public APIHook(ISAcreator isacreatorEnvironment, String studyId) { - - this.isacreatorEnvironment = isacreatorEnvironment; - this.studyId = studyId; - } - - /** - * Method goes through the ISAtab model and pulls out the fields describing the sample (from study sample files) and - * and fields describing - */ - private Map> loadFields() { - isatabFields = new HashMap>(); - - Set unwantedColumns = generateUnwantedColumnsSet(""Unit"", ""Protocol REF"", ""File""); - - Study study = getInvestigation().getStudies().get(studyId); - - if (study != null) { - isatabFields.put(study, - SpreadsheetUtils.getColumnNames(study.getStudySample().getSpreadsheetUI().getTable(), unwantedColumns)); - - for (Assay a : study.getAssays().values()) { - if (a.getTechnologyType().contains(""sequencing"")) { - isatabFields.put(a, - SpreadsheetUtils.getColumnNames(a.getSpreadsheetUI().getTable(), unwantedColumns)); - } - } - } - return isatabFields; - } - - /** - * Method pulls out all the information of interest for output. It returns each sample along with the data corresponding to - * that sample. - * - * @param sampleNames - Sample names we are looking for. - * @return Map> - SampleName ->Columns|Values - */ - public Map>> getDataForSamples(Set sampleNames) { - // map of column name to value - Map>> sampleData = new HashMap>>(); - - // precautionary measure in case the user hasn't looked at the sample id assignments! - if (studyOrAssayToSampleNameColumn == null) { - getSampleNames(); - } - - for (Object assayOrStudy : isatabFields.keySet()) { - // check for rows of interest. - - // get table - Spreadsheet spreadsheet; - - if (assayOrStudy instanceof Study) { - spreadsheet = ((Study) assayOrStudy).getStudySample().getSpreadsheetUI().getTable(); - } else { - spreadsheet = ((Assay) assayOrStudy).getSpreadsheetUI().getTable(); - } - - for (int rowNo = 0; rowNo < spreadsheet.getTable().getRowCount(); rowNo++) { - // test to ensure that the row contains the sample we want - String candidateSample = spreadsheet.getTable().getValueAt(rowNo, studyOrAssayToSampleNameColumn.get(assayOrStudy)).toString(); - - if (sampleNames.contains(candidateSample)) { - // then proceed with adding details to the record - if (!sampleData.containsKey(candidateSample)) { - sampleData.put(candidateSample, new HashMap>()); - } - - for (String field : isatabFields.get(assayOrStudy).keySet()) { - - int column = isatabFields.get(assayOrStudy) - .get(field); - - String value = spreadsheet.getTable().getValueAt(rowNo, column).toString(); - - // check if the field has a unit, if there is a unit, it will be added to the - String unit = spreadsheet.getAssignedUnitForColumn(column, rowNo); - - // try and pick out a unit from the header value - - if (unit.equals("""")) { - unit = extractUnitFromFieldName(field); - if (!unit.equals("""")) { - value += "" "" + unit; - } - } else { - value += "" "" + unit; - } - - if (!sampleData.get(candidateSample).containsKey(field)) { - sampleData.get(candidateSample).put(field, new ArrayList()); - } - // todo investigate why this is not adding multiple values for one sample (replicates)! - sampleData.get(candidateSample).get(field).add(value); - } - } - } - } - - return sampleData; - } - - /** - * If, for example we have mg/L as a string in the Characteristics[Chla mg/L] field, - * we want to extract this as the unit automatically - * - * @param fieldName - field to check - * @return Unit if one is available - */ - private String extractUnitFromFieldName(String fieldName) { - String unit = """"; - System.out.println(""attempting to extract unit from "" + fieldName); - if (fieldName.contains(""Characteristic"") || fieldName.contains(""Factor"") || fieldName.contains(""Parameter"") - || fieldName.contains(""Comment"")) { - String tmpField = cleanupString(fieldName); - String[] fragments = tmpField.split("" ""); - if (fragments.length > 1) { - String lastFragment = fragments[fragments.length - 1].trim(); - if (lastFragment.length() <= 4 || lastFragment.contains(""\\"") || lastFragment.contains(""/"")) { - return lastFragment; - } - } - } - - return unit; - } - - private String cleanupString(String toClean) { - return toClean.replaceAll(""(Characteristics\\[)|(Factor Value\\[)|(Parameter Value\\[)|(Comment\\[)|\\]"", """"); - } - - - public Set getISAtabFields() { - if (isatabFields == null) { - loadFields(); - } - - Set fields = new ListOrderedSet(); - - for (Object studyOrAssay : isatabFields.keySet()) { - Map columns = isatabFields.get(studyOrAssay); - fields.addAll(columns.keySet()); - } - - return fields; - } - - public Set getSampleNames() { - // if the set has already been created, the just use this :) - - if (sampleNames != null) { - return sampleNames; - } - - // else retrieve the sample names since it's being performed for the first time. - if (isatabFields == null) { - loadFields(); - } - - studyOrAssayToSampleNameColumn = new HashMap(); - - for (Object studyOrAssay : isatabFields.keySet()) { - - Map columns = isatabFields.get(studyOrAssay); - - for (String column : columns.keySet()) { - if (column.equalsIgnoreCase(""sample name"")) { - studyOrAssayToSampleNameColumn.put(studyOrAssay, columns.get(column)); - break; - } - } - - } - - return extractSampleIds(studyOrAssayToSampleNameColumn); - } - - private Set extractSampleIds(Map studyOrAssayToSampleNameColumn) { - sampleNames = new ListOrderedSet(); - - // add all sample names from all assays of interest (i.e. those employing sequencing)... - for (Object assay : studyOrAssayToSampleNameColumn.keySet()) { - - if (assay instanceof Assay) { -// -// JTable dataSource = ((Assay) assay).getSpreadsheetUI().getTable().getTable(); -// -// for (int rowNo = 0; rowNo < dataSource.getRowCount(); rowNo++) { -// String value = dataSource.getValueAt(rowNo, studyOrAssayToSampleNameColumn.get(assay)).toString(); -// if (value != null && !value.trim().equals("""")) { -// sampleNames.add(value); -// } -// } - - sampleNames.addAll(SpreadsheetUtils.getDataInColumn(((Assay) assay).getSpreadsheetUI().getTable(), - studyOrAssayToSampleNameColumn.get(assay))); - } - } - - return sampleNames; - } - - private Set generateUnwantedColumnsSet(String... unwantedColumns) { - Set result = new HashSet(); - - result.addAll(Arrays.asList(unwantedColumns)); - - return result; - } - - private Investigation getInvestigation() { - return isacreatorEnvironment.getDataEntryEnvironment().getInvestigation(); - } -} diff --git a/src/main/java/org/isatools/isacreator/qrcode/ui/QRCodeGeneratorUI.java b/src/main/java/org/isatools/isacreator/qrcode/ui/QRCodeGeneratorUI.java index c5dead7a..74cf22d6 100644 --- a/src/main/java/org/isatools/isacreator/qrcode/ui/QRCodeGeneratorUI.java +++ b/src/main/java/org/isatools/isacreator/qrcode/ui/QRCodeGeneratorUI.java @@ -79,8 +79,6 @@ public class QRCodeGeneratorUI extends JDialog { QRCodeGeneratorUI.class.getResource(""/dependency-injections/formatmappingutility-package.properties"")); ResourceInjector.get(""common-package.style"").load( QRCodeViewerPane.class.getResource(""/dependency-injections/common-package.properties"")); - ResourceInjector.get(""exporters-package.style"").load( - QRCodeViewerPane.class.getResource(""/dependency-injections/exporters-package.properties"")); } diff --git a/src/main/resources/dependency-injections/exporters-package.properties b/src/main/resources/dependency-injections/exporters-package.properties deleted file mode 100644 index 16369fc9..00000000 --- a/src/main/resources/dependency-injections/exporters-package.properties +++ /dev/null @@ -1,45 +0,0 @@ -MGRastUI.mgRastHeader=/images/exporters/mgrastexport/mgrast_export_header.png -MGRastUI.mgRastExportSampleSection=/images/exporters/mgrastexport/mgrast_1.png -MGRastUI.weKnowIcon=/images/exporters/mgrastexport/weknow.png -MGRastUI.weKnowIconOver=/images/exporters/mgrastexport/weknow_over.png -MGRastUI.weDoNotKnowIcon=/images/exporters/mgrastexport/dontknow.png -MGRastUI.weDoNotKnowIconOver=/images/exporters/mgrastexport/dontknow_over.png -MGRastUI.helpIcon=/images/exporters/mgrastexport/help.png -MGRastUI.helpIconOver=/images/exporters/mgrastexport/help_over.png -MGRastUI.closeWindowIcon=/images/exporters/mgrastexport/close_window.png -MGRastUI.closeWindowIconOver=/images/exporters/mgrastexport/close_window_over.png -MGRastUI.exportIcon=/images/exporters/mgrastexport/export.png -MGRastUI.exportIconOver=/images/exporters/mgrastexport/export_over.png -MGRastUI.buttonPanelSeparator=/images/exporters/mgrastexport/bottom_panel_sep.png -MGRastUI.loadingSamples=/images/exporters/mgrastexport/loading_samples.png -MGRastUI.mappingConcepts=/images/exporters/mgrastexport/mapping_concepts.png -MGRastUI.noProjectNameWarning=/images/exporters/mgrastexport/warning/no_pid-name_warning.png -MGRastUI.exportHeader=/images/exporters/mgrastexport/export/chooseOutputDirectory.png - -HelpPane.helpImage=/images/exporters/mgrastexport/help_image.png - -SampleInfoPane.externalReferencesHeader=/images/exporters/mgrastexport/external_references_image.png -SampleInfoPane.externalReferenceInfo=/images/exporters/mgrastexport/id_info.png -SampleInfoPane.key=/images/exporters/mgrastexport/key.png - -ExternalIdListCellRenderer.idEntered=/images/exporters/mgrastexport/id_entered.png -ExternalIdListCellRenderer.noIdEntered=/images/exporters/mgrastexport/no_id_entered.png - -MGRastConceptListCellRenderer.mappedTo=/images/exporters/mgrastexport/mapped_to.png -MGRastConceptListCellRenderer.notMappedTo=/images/exporters/mgrastexport/not_mapped_to.png - -MappingConfidenceListCellRenderer.oneHundredPercent=/images/exporters/mgrastexport/confidence_levels/100percent.png -MappingConfidenceListCellRenderer.seventyFivePercent=/images/exporters/mgrastexport/confidence_levels/75percent.png -MappingConfidenceListCellRenderer.fiftyPercent=/images/exporters/mgrastexport/confidence_levels/50percent.png -MappingConfidenceListCellRenderer.twentyFivePercent=/images/exporters/mgrastexport/confidence_levels/25percent.png -MappingConfidenceListCellRenderer.zeroPercent=/images/exporters/mgrastexport/confidence_levels/no_mapping.png - -TermMappingUI.confidenceKey=/images/exporters/mgrastexport/confidence_levels.png -TermMappingUI.attentionIcon=/images/exporters/mgrastexport/attention.png -TermMappingUI.confirmIcon=/images/exporters/mgrastexport/confirm_change.png -TermMappingUI.confirmIconOver=/images/exporters/mgrastexport/confirm_change_over.png -TermMappingUI.rejectIcon=/images/exporters/mgrastexport/reject_change.png -TermMappingUI.rejectIconOver=/images/exporters/mgrastexport/reject_change_over.png -TermMappingUI.mappedToIcon=/images/exporters/mgrastexport/is_mapped_to.png - - diff --git a/src/main/resources/dependency-injections/gui-package.properties b/src/main/resources/dependency-injections/gui-package.properties index 17ccc936..2af1e7b1 100644 --- a/src/main/resources/dependency-injections/gui-package.properties +++ b/src/main/resources/dependency-injections/gui-package.properties @@ -12,6 +12,8 @@ ISAcreator.logoutIcon=/images/gui/logout_menuitem.png ISAcreator.menuIcon=/images/gui/menu.png ISAcreator.exitIcon=/images/gui/exit.png ISAcreator.exportArchiveIcon=/images/gui/exportArchive_Menu.png +ISAcreator.convertIcon=/images/gui/menu_icon_convert.png +ISAcreator.validateIcon=/images/gui/menu_icon_validate.png # Study menu items ISAcreator.addStudyIcon=/images/gui/overtree-menu/add_study.png ISAcreator.removeStudyIcon=/images/gui/overtree-menu/remove_study.png @@ -24,7 +26,6 @@ ISAcreator.helpIcon=/images/gui/help.png ISAcreator.supportIcon=/images/gui/support.png ISAcreator.feedbackIcon=/images/gui/feedback.png # plugin menu items -ISAcreator.mgRastIcon=/images/gui/mgrast_export.png ISAcreator.qrCodeIcon=/images/gui/qr_code_generator.png # Other App images diff --git a/src/main/resources/dependency-injections/validator-package.properties b/src/main/resources/dependency-injections/validator-package.properties index 5629570b..672b082d 100644 --- a/src/main/resources/dependency-injections/validator-package.properties +++ b/src/main/resources/dependency-injections/validator-package.properties @@ -1,3 +1,13 @@ ValidateUI.validateIcon=/images/validator/validator-logo.png ValidateUI.validateIconInactive=/images/validator/validator-logo-inactive.png ValidateUI.validationSuccess=/images/validator/validation_successful.png + +ValidateUI.convertIcon=/images/validator/convert-logo.png +ValidateUI.convertIconInactive=/images/validator/convert-logo-inactive.png +ValidateUI.conversionSuccess=/images/validator/conversion-success.png + +ConvertUI.startConversion=/images/validator/start-conversion.png +ConvertUI.startConversionOver=/images/validator/start-conversion_over.png + +ConversionTargetInformationPanel.selected=/images/validator/selected.png +ConversionTargetInformationPanel.unselected=/images/validator/unselected.png diff --git a/src/main/resources/images/exporters/mgrastexport/attention.png b/src/main/resources/images/exporters/mgrastexport/attention.png deleted file mode 100644 index 3db37d97..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/attention.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/bottom_panel_sep.png b/src/main/resources/images/exporters/mgrastexport/bottom_panel_sep.png deleted file mode 100644 index 713e9b7f..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/bottom_panel_sep.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/close_window.png b/src/main/resources/images/exporters/mgrastexport/close_window.png deleted file mode 100644 index 556e937c..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/close_window.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/close_window_over.png b/src/main/resources/images/exporters/mgrastexport/close_window_over.png deleted file mode 100644 index f8292875..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/close_window_over.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/confidence_levels.png b/src/main/resources/images/exporters/mgrastexport/confidence_levels.png deleted file mode 100644 index b0c2001f..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/confidence_levels.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/confidence_levels/100percent.png b/src/main/resources/images/exporters/mgrastexport/confidence_levels/100percent.png deleted file mode 100644 index 8878455e..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/confidence_levels/100percent.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/confidence_levels/25percent.png b/src/main/resources/images/exporters/mgrastexport/confidence_levels/25percent.png deleted file mode 100644 index a2e31c76..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/confidence_levels/25percent.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/confidence_levels/50percent.png b/src/main/resources/images/exporters/mgrastexport/confidence_levels/50percent.png deleted file mode 100644 index 93d91953..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/confidence_levels/50percent.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/confidence_levels/75percent.png b/src/main/resources/images/exporters/mgrastexport/confidence_levels/75percent.png deleted file mode 100644 index 6be8180f..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/confidence_levels/75percent.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/confidence_levels/no_mapping.png b/src/main/resources/images/exporters/mgrastexport/confidence_levels/no_mapping.png deleted file mode 100644 index c6c5a413..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/confidence_levels/no_mapping.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/confirm_change.png b/src/main/resources/images/exporters/mgrastexport/confirm_change.png deleted file mode 100644 index 2ea62261..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/confirm_change.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/confirm_change_over.png b/src/main/resources/images/exporters/mgrastexport/confirm_change_over.png deleted file mode 100644 index ac1ef241..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/confirm_change_over.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/dontknow.png b/src/main/resources/images/exporters/mgrastexport/dontknow.png deleted file mode 100644 index 52ed3c91..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/dontknow.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/dontknow_over.png b/src/main/resources/images/exporters/mgrastexport/dontknow_over.png deleted file mode 100644 index e27e0ae6..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/dontknow_over.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/export.png b/src/main/resources/images/exporters/mgrastexport/export.png deleted file mode 100644 index 705c19d4..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/export.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/export/chooseOutputDirectory.png b/src/main/resources/images/exporters/mgrastexport/export/chooseOutputDirectory.png deleted file mode 100644 index e78704af..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/export/chooseOutputDirectory.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/export_over.png b/src/main/resources/images/exporters/mgrastexport/export_over.png deleted file mode 100644 index a24c2e11..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/export_over.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/external_references_image.png b/src/main/resources/images/exporters/mgrastexport/external_references_image.png deleted file mode 100644 index 9afc3f25..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/external_references_image.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/help.png b/src/main/resources/images/exporters/mgrastexport/help.png deleted file mode 100644 index f6e696c6..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/help.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/help_image.png b/src/main/resources/images/exporters/mgrastexport/help_image.png deleted file mode 100644 index 4fa76fa8..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/help_image.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/help_over.png b/src/main/resources/images/exporters/mgrastexport/help_over.png deleted file mode 100644 index 5281e332..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/help_over.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/id_entered.png b/src/main/resources/images/exporters/mgrastexport/id_entered.png deleted file mode 100644 index 7b872711..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/id_entered.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/id_info.png b/src/main/resources/images/exporters/mgrastexport/id_info.png deleted file mode 100644 index c76684d6..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/id_info.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/is_mapped_to.png b/src/main/resources/images/exporters/mgrastexport/is_mapped_to.png deleted file mode 100644 index 00d85826..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/is_mapped_to.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/key.png b/src/main/resources/images/exporters/mgrastexport/key.png deleted file mode 100644 index e8030a72..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/key.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/loading_samples.png b/src/main/resources/images/exporters/mgrastexport/loading_samples.png deleted file mode 100644 index 1e01497c..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/loading_samples.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/mapped_to.png b/src/main/resources/images/exporters/mgrastexport/mapped_to.png deleted file mode 100644 index 0980b36b..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/mapped_to.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/mapping_concepts.png b/src/main/resources/images/exporters/mgrastexport/mapping_concepts.png deleted file mode 100644 index ef1438be..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/mapping_concepts.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/mgrast_1.png b/src/main/resources/images/exporters/mgrastexport/mgrast_1.png deleted file mode 100644 index b34742dd..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/mgrast_1.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/mgrast_export_header.png b/src/main/resources/images/exporters/mgrastexport/mgrast_export_header.png deleted file mode 100644 index f3988f9c..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/mgrast_export_header.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/no_id_entered.png b/src/main/resources/images/exporters/mgrastexport/no_id_entered.png deleted file mode 100644 index 8ef35b7f..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/no_id_entered.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/not_mapped_to.png b/src/main/resources/images/exporters/mgrastexport/not_mapped_to.png deleted file mode 100644 index 66b6ce0e..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/not_mapped_to.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/reject_change.png b/src/main/resources/images/exporters/mgrastexport/reject_change.png deleted file mode 100644 index 8575a3dd..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/reject_change.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/reject_change_over.png b/src/main/resources/images/exporters/mgrastexport/reject_change_over.png deleted file mode 100644 index 35c9275b..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/reject_change_over.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/warning/no_pid-name_warning.png b/src/main/resources/images/exporters/mgrastexport/warning/no_pid-name_warning.png deleted file mode 100644 index 9f8f791f..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/warning/no_pid-name_warning.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/weknow.png b/src/main/resources/images/exporters/mgrastexport/weknow.png deleted file mode 100644 index 6f5b268c..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/weknow.png and /dev/null differ diff --git a/src/main/resources/images/exporters/mgrastexport/weknow_over.png b/src/main/resources/images/exporters/mgrastexport/weknow_over.png deleted file mode 100644 index 37886839..00000000 Binary files a/src/main/resources/images/exporters/mgrastexport/weknow_over.png and /dev/null differ diff --git a/src/main/resources/images/gui/menu_icon_convert.png b/src/main/resources/images/gui/menu_icon_convert.png new file mode 100644 index 00000000..edb71565 Binary files /dev/null and b/src/main/resources/images/gui/menu_icon_convert.png differ diff --git a/src/main/resources/images/gui/menu_icon_validate.png b/src/main/resources/images/gui/menu_icon_validate.png new file mode 100644 index 00000000..008200a1 Binary files /dev/null and b/src/main/resources/images/gui/menu_icon_validate.png differ diff --git a/src/main/resources/images/validator/conversion-success.png b/src/main/resources/images/validator/conversion-success.png new file mode 100644 index 00000000..f8e9feec Binary files /dev/null and b/src/main/resources/images/validator/conversion-success.png differ diff --git a/src/main/resources/images/validator/convert-logo-inactive.png b/src/main/resources/images/validator/convert-logo-inactive.png new file mode 100644 index 00000000..0199eb2c Binary files /dev/null and b/src/main/resources/images/validator/convert-logo-inactive.png differ diff --git a/src/main/resources/images/validator/convert-logo.png b/src/main/resources/images/validator/convert-logo.png new file mode 100644 index 00000000..0b1f160b Binary files /dev/null and b/src/main/resources/images/validator/convert-logo.png differ diff --git a/src/main/resources/images/validator/converting.gif b/src/main/resources/images/validator/converting.gif new file mode 100644 index 00000000..01836882 Binary files /dev/null and b/src/main/resources/images/validator/converting.gif differ diff --git a/src/main/resources/images/validator/selected.png b/src/main/resources/images/validator/selected.png new file mode 100644 index 00000000..4f6247b1 Binary files /dev/null and b/src/main/resources/images/validator/selected.png differ diff --git a/src/main/resources/images/validator/start-conversion.png b/src/main/resources/images/validator/start-conversion.png new file mode 100644 index 00000000..cd774833 Binary files /dev/null and b/src/main/resources/images/validator/start-conversion.png differ diff --git a/src/main/resources/images/validator/start-conversion_over.png b/src/main/resources/images/validator/start-conversion_over.png new file mode 100644 index 00000000..9a774d68 Binary files /dev/null and b/src/main/resources/images/validator/start-conversion_over.png differ diff --git a/src/main/resources/images/validator/unselected.png b/src/main/resources/images/validator/unselected.png new file mode 100644 index 00000000..8724084b Binary files /dev/null and b/src/main/resources/images/validator/unselected.png differ" 0ebc701a71bd07a1aaaf2831d4fc15ac3808c43a,aeshell$aesh,"added more util methods to Parser to handle escaped space added handling of spaces in filenames for Console and RedirectionCompletion FileUtils also support escaped spaces + more tests ",a,https://github.com/aeshell/aesh,"diff --git a/src/main/java/org/jboss/jreadline/complete/CompleteOperation.java b/src/main/java/org/jboss/jreadline/complete/CompleteOperation.java index 636f5be46..31c8da22c 100644 --- a/src/main/java/org/jboss/jreadline/complete/CompleteOperation.java +++ b/src/main/java/org/jboss/jreadline/complete/CompleteOperation.java @@ -16,6 +16,8 @@ */ package org.jboss.jreadline.complete; +import org.jboss.jreadline.util.Parser; + import java.util.ArrayList; import java.util.List; @@ -75,7 +77,11 @@ public void addCompletionCandidate(String completionCandidate) { public void addCompletionCandidates(List completionCandidates) { this.completionCandidates.addAll(completionCandidates); } - + + public void removeEscapedSpacesFromCompletionCandidates() { + setCompletionCandidates(Parser.switchEscapedSpacesToSpacesInList(getCompletionCandidates())); + } + public List getFormattedCompletionCandidates() { if(offset < cursor) { List fixedCandidates = new ArrayList(completionCandidates.size()); diff --git a/src/main/java/org/jboss/jreadline/console/Console.java b/src/main/java/org/jboss/jreadline/console/Console.java index bb9da2a49..6e8a04ce7 100644 --- a/src/main/java/org/jboss/jreadline/console/Console.java +++ b/src/main/java/org/jboss/jreadline/console/Console.java @@ -1021,7 +1021,7 @@ private void displayCompletion(String fullCompletion, String completion, boolean */ private void displayCompletions(List completions) throws IOException { printNewline(); - terminal.writeToStdOut(Parser.formatCompletions(completions, terminal.getHeight(), terminal.getWidth())); + terminal.writeToStdOut(Parser.formatDisplayList(completions, terminal.getHeight(), terminal.getWidth())); terminal.writeToStdOut(buffer.getLineWithPrompt()); //if we do a complete and the cursor is not at the end of the //buffer we need to move it to the correct place @@ -1150,7 +1150,7 @@ else if(buffer.contains(""|"")) { private void persistRedirection(String fileName) throws IOException { try { - FileUtils.saveFile(new File(fileName), redirectPipeOutBuffer.toString(), false); + FileUtils.saveFile(new File(Parser.switchEscapedSpacesToSpacesInWord( fileName)), redirectPipeOutBuffer.toString(), false); } catch (IOException e) { pushToStdErr(e.getMessage()); diff --git a/src/main/java/org/jboss/jreadline/console/RedirectionCompletion.java b/src/main/java/org/jboss/jreadline/console/RedirectionCompletion.java index 2705b0341..272e8ed31 100644 --- a/src/main/java/org/jboss/jreadline/console/RedirectionCompletion.java +++ b/src/main/java/org/jboss/jreadline/console/RedirectionCompletion.java @@ -42,6 +42,9 @@ public void complete(CompleteOperation completeOperation) { completeOperation.setOffset(completeOperation.getCursor()); FileUtils.listMatchingDirectories(completeOperation, word, new File(System.getProperty(""user.dir""))); + //if we only have one complete candidate, leave the escaped space be + if(completeOperation.getCompletionCandidates().size() > 1) + completeOperation.removeEscapedSpacesFromCompletionCandidates(); } } } diff --git a/src/main/java/org/jboss/jreadline/util/FileUtils.java b/src/main/java/org/jboss/jreadline/util/FileUtils.java index 0c36f3467..37915a07a 100644 --- a/src/main/java/org/jboss/jreadline/util/FileUtils.java +++ b/src/main/java/org/jboss/jreadline/util/FileUtils.java @@ -51,7 +51,7 @@ public static void listMatchingDirectories(CompleteOperation completion, String List allFiles = listDirectory(cwd); for (String file : allFiles) if (file.startsWith(possibleDir)) - returnFiles.add(file.substring(possibleDir.length())); + returnFiles.add(Parser.switchSpacesToEscapedSpacesInWord( file.substring(possibleDir.length()))); completion.addCompletionCandidates(returnFiles); } @@ -64,8 +64,7 @@ else if (!startsWithSlash.matcher(possibleDir).matches() && } else { completion.addCompletionCandidates( listDirectory(new File(cwd.getAbsolutePath() + - Config.getPathSeparator() - +possibleDir))); + Config.getPathSeparator() +possibleDir))); } } else if(new File(cwd.getAbsolutePath() +Config.getPathSeparator()+ possibleDir).isFile()) { @@ -106,8 +105,6 @@ else if(new File(possibleDir).isDirectory() && rest = possibleDir; } } - //System.out.println(""rest:""+rest); - //System.out.println(""lastDir:""+lastDir); List allFiles; if(startsWithSlash.matcher(possibleDir).matches()) @@ -124,25 +121,25 @@ else if(lastDir != null) for (String file : allFiles) if (file.startsWith(rest)) //returnFiles.add(file); - returnFiles.add(file.substring(rest.length())); + returnFiles.add(Parser.switchSpacesToEscapedSpacesInWord( file.substring(rest.length()))); } else { for(String file : allFiles) - returnFiles.add(file); + returnFiles.add(Parser.switchSpacesToEscapedSpacesInWord(file)); } if(returnFiles.size() > 1) { String startsWith = Parser.findStartsWith(returnFiles); if(startsWith != null && startsWith.length() > 0) { returnFiles.clear(); - returnFiles.add(startsWith); + returnFiles.add(Parser.switchSpacesToEscapedSpacesInWord( startsWith)); } //need to list complete filenames else { returnFiles.clear(); for (String file : allFiles) if (file.startsWith(rest)) - returnFiles.add(file); + returnFiles.add(Parser.switchSpacesToEscapedSpacesInWord( file)); } } diff --git a/src/main/java/org/jboss/jreadline/util/Parser.java b/src/main/java/org/jboss/jreadline/util/Parser.java index 89e88ce53..1742bf8d6 100644 --- a/src/main/java/org/jboss/jreadline/util/Parser.java +++ b/src/main/java/org/jboss/jreadline/util/Parser.java @@ -22,6 +22,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.regex.Pattern; /** * String/Parser util methods @@ -31,34 +32,41 @@ public class Parser { + private static final String spaceEscapedMatcher = ""\\ ""; + private static final String SPACE = "" ""; + private static final char SLASH = '\\'; + private static final Pattern spaceEscapedPattern = Pattern.compile(""\\\\ ""); + private static final Pattern spacePattern = Pattern.compile("" ""); + private static final Pattern onlyEscapedSpacePattern = Pattern.compile(""[(\\\\ )&&[^(\\s)]]""); + /** * Format completions so that they look similar to GNU Readline * - * @param completions to format + * @param displayList to format * @param termHeight max height * @param termWidth max width * @return formatted string to be outputted */ - public static String formatCompletions(String[] completions, int termHeight, int termWidth) { - return formatCompletions(Arrays.asList(completions), termHeight, termWidth); + public static String formatDisplayList(String[] displayList, int termHeight, int termWidth) { + return formatDisplayList(Arrays.asList(displayList), termHeight, termWidth); } - public static String formatCompletions(List completions, int termHeight, int termWidth) { - if(completions == null || completions.size() < 1) + public static String formatDisplayList(List displayList, int termHeight, int termWidth) { + if(displayList == null || displayList.size() < 1) return """"; int maxLength = 0; - for(String completion : completions) + for(String completion : displayList) if(completion.length() > maxLength) maxLength = completion.length(); maxLength = maxLength +2; //adding two spaces for better readability int numColumns = termWidth / maxLength; - if(numColumns > completions.size()) // we dont need more columns than items - numColumns = completions.size(); - int numRows = completions.size() / numColumns; + if(numColumns > displayList.size()) // we dont need more columns than items + numColumns = displayList.size(); + int numRows = displayList.size() / numColumns; // add a row if we cant display all the items - if(numRows * numColumns < completions.size()) + if(numRows * numColumns < displayList.size()) numRows++; // build the completion listing @@ -66,8 +74,8 @@ public static String formatCompletions(List completions, int termHeight, for(int i=0; i < numRows; i++) { for(int c=0; c < numColumns; c++) { int fetch = i + (c * numRows); - if(fetch < completions.size()) - completionOutput.append(padRight(maxLength, completions.get(i + (c * numRows)))) ; + if(fetch < displayList.size()) + completionOutput.append(padRight(maxLength, displayList.get(i + (c * numRows)))) ; else break; } @@ -130,27 +138,107 @@ public static String findWordClosestToCursor(String text, int cursor) { if(text.length() <= cursor+1) { // return last word if(text.substring(0, cursor).contains("" "")) { - if(text.lastIndexOf("" "") >= cursor) //cant use lastIndexOf - return text.substring(text.substring(0, cursor).lastIndexOf("" "")).trim(); - else - return text.trim().substring(text.lastIndexOf("" "")).trim(); + if(doWordContainEscapedSpace(text)) { + if(doWordContainOnlyEscapedSpace(text)) + return switchEscapedSpacesToSpacesInWord(text); + else { + return switchEscapedSpacesToSpacesInWord(findEscapedSpaceWordCloseToEnd(text)); + } + } + else { + if(text.lastIndexOf("" "") >= cursor) //cant use lastIndexOf + return text.substring(text.substring(0, cursor).lastIndexOf("" "")).trim(); + else + return text.trim().substring(text.lastIndexOf("" "")).trim(); + } } else return text.trim(); } else { String rest = text.substring(0, cursor+1); - if(cursor > 1 && - text.charAt(cursor) == ' ' && text.charAt(cursor-1) == ' ') - return """"; - //only if it contains a ' ' and its not at the end of the string - if(rest.trim().contains("" "")) - return rest.substring(rest.trim().lastIndexOf("" "")).trim(); + if(doWordContainOnlyEscapedSpace(rest)) { + if(cursor > 1 && + text.charAt(cursor) == ' ' && text.charAt(cursor-1) == ' ') + return """"; + else + return switchEscapedSpacesToSpacesInWord(rest); + } + else { + if(cursor > 1 && + text.charAt(cursor) == ' ' && text.charAt(cursor-1) == ' ') + return """"; + //only if it contains a ' ' and its not at the end of the string + if(rest.trim().contains("" "")) + return rest.substring(rest.trim().lastIndexOf("" "")).trim(); + else + return rest.trim(); + } + } + } + + public static String findEscapedSpaceWordCloseToEnd(String text) { + int index; + String originalText = text; + while((index = text.lastIndexOf(SPACE)) > -1) { + if(index > 0 && text.charAt(index-1) == SLASH) { + text = text.substring(0,index-1); + } + else + return originalText.substring(index+1); + } + return originalText; + } + + public static String findEscapedSpaceWordCloseToBeginning(String text) { + int index; + int totalIndex = 0; + String originalText = text; + while((index = text.indexOf(SPACE)) > -1) { + if(index > 0 && text.charAt(index-1) == SLASH) { + text = text.substring(index+1); + totalIndex += index+1; + } else - return rest.trim(); + return originalText.substring(0, totalIndex+index); } + return originalText; } + public static boolean doWordContainOnlyEscapedSpace(String word) { + return (findAllOccurrences(word, spaceEscapedMatcher) == findAllOccurrences(word, SPACE)); + } + + public static boolean doWordContainEscapedSpace(String word) { + return spaceEscapedPattern.matcher(word).find(); + } + + public static int findAllOccurrences(String word, String pattern) { + int count = 0; + while(word.contains(pattern)) { + count++; + word = word.substring(word.indexOf(pattern)+pattern.length()); + } + return count; + } + + public static List switchEscapedSpacesToSpacesInList(List list) { + List newList = new ArrayList(list.size()); + for(String s : list) + newList.add(switchEscapedSpacesToSpacesInWord(s)); + return newList; + } + + public static String switchSpacesToEscapedSpacesInWord(String word) { + return spacePattern.matcher(word).replaceAll(""\\\\ ""); + } + + public static String switchEscapedSpacesToSpacesInWord(String word) { + return spaceEscapedPattern.matcher(word).replaceAll("" ""); + } + + + public static String findWordClosestToCursorDividedByRedirectOrPipe(String text, int cursor) { //1. find all occurrences of pipe/redirect. //2. find position thats closest to cursor. diff --git a/src/test/java/org/jboss/jreadline/complete/CompleteOperationTest.java b/src/test/java/org/jboss/jreadline/complete/CompleteOperationTest.java new file mode 100644 index 000000000..5220b31fc --- /dev/null +++ b/src/test/java/org/jboss/jreadline/complete/CompleteOperationTest.java @@ -0,0 +1,55 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2010, Red Hat Middleware LLC, and individual contributors + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.jboss.jreadline.complete; + +import junit.framework.TestCase; + +import java.util.List; + +/** + * @author Ståle W. Pedersen + */ +public class CompleteOperationTest extends TestCase { + + public CompleteOperationTest(String name) { + super(name); + } + + public void testGetFormattedCompletionCandidates() { + CompleteOperation co = new CompleteOperation(""ls foob"", 6); + co.addCompletionCandidate(""foobar""); + co.addCompletionCandidate(""foobars""); + co.setOffset(3); + + List formattedCandidates = co.getFormattedCompletionCandidates(); + + assertEquals(""bar"", formattedCandidates.get(0)); + assertEquals(""bars"", formattedCandidates.get(1)); + } + + public void testRemoveEscapedSpacesFromCompletionCandidates() { + CompleteOperation co = new CompleteOperation(""ls foob"", 6); + co.addCompletionCandidate(""foo\\ bar""); + co.addCompletionCandidate(""foo\\ bars""); + co.setOffset(3); + + co.removeEscapedSpacesFromCompletionCandidates(); + + assertEquals(""foo bar"", co.getCompletionCandidates().get(0)); + assertEquals(""foo bars"", co.getCompletionCandidates().get(1)); + } +} diff --git a/src/test/java/org/jboss/jreadline/util/ParserTestCase.java b/src/test/java/org/jboss/jreadline/util/ParserTestCase.java index f30edfa82..6a35dbb1e 100644 --- a/src/test/java/org/jboss/jreadline/util/ParserTestCase.java +++ b/src/test/java/org/jboss/jreadline/util/ParserTestCase.java @@ -44,6 +44,28 @@ public void testFindClosestWordToCursor() { assertEquals("""", Parser.findWordClosestToCursor(""ls org/jboss/jreadlineshell/Shell.class"", 3) ); } + public void testFindClosestWordWithEscapedSpaceToCursor() { + assertEquals(""foo bar"", Parser.findWordClosestToCursor(""foo\\ bar"", 7)); + assertEquals(""foo ba"", Parser.findWordClosestToCursor(""foo\\ bar"", 6)); + assertEquals(""foo bar"", Parser.findWordClosestToCursor(""ls foo\\ bar"", 11) ); + } + + public void testFindEscapedSpaceWordCloseToEnd() { + assertEquals(""ls\\ foo"", Parser.findEscapedSpaceWordCloseToEnd("" ls\\ foo"")); + assertEquals(""foo\\ bar"", Parser.findEscapedSpaceWordCloseToEnd(""ls foo\\ bar"")); + assertEquals(""bar"", Parser.findEscapedSpaceWordCloseToEnd(""ls foo bar"")); + assertEquals(""ls\\ foo\\ bar"", Parser.findEscapedSpaceWordCloseToEnd(""ls\\ foo\\ bar"")); + assertEquals(""\\ ls\\ foo\\ bar"", Parser.findEscapedSpaceWordCloseToEnd(""\\ ls\\ foo\\ bar"")); + assertEquals(""ls\\ foo\\ bar"", Parser.findEscapedSpaceWordCloseToEnd("" ls\\ foo\\ bar"")); + } + + public void testFindExcapedSpaceWordCloseToBeginning() { + assertEquals(""ls\\ foo"", Parser.findEscapedSpaceWordCloseToBeginning(""ls\\ foo "")); + assertEquals(""ls"", Parser.findEscapedSpaceWordCloseToBeginning(""ls foo"")); + assertEquals(""ls\\ foo\\ bar"", Parser.findEscapedSpaceWordCloseToBeginning(""ls\\ foo\\ bar"")); + assertEquals("""", Parser.findEscapedSpaceWordCloseToBeginning("" ls\\ foo\\ bar"")); + } + public void testFindWordClosestToCursorDividedByRedirectOrPipe() { assertEquals(""foo"", Parser.findWordClosestToCursorDividedByRedirectOrPipe(""ls > foo"", 8)); assertEquals(""foo"", Parser.findWordClosestToCursorDividedByRedirectOrPipe(""ls | foo"", 8)); @@ -57,4 +79,24 @@ public void testFindWordClosestToCursorDividedByRedirectOrPipe() { assertEquals("""", Parser.findWordClosestToCursorDividedByRedirectOrPipe(""ls | bla > "", 11)); } + public void testFindEscapedSpaceWord() { + assertTrue(Parser.doWordContainOnlyEscapedSpace(""foo\\ bar"")); + assertTrue(Parser.doWordContainOnlyEscapedSpace(""foo\\ bar\\ "")); + assertTrue(Parser.doWordContainOnlyEscapedSpace(""\\ foo\\ bar\\ "")); + assertFalse(Parser.doWordContainOnlyEscapedSpace("" foo\\ bar\\ "")); + assertFalse(Parser.doWordContainOnlyEscapedSpace(""foo bar\\ "")); + assertFalse(Parser.doWordContainOnlyEscapedSpace(""foo bar"")); + } + + public void testChangeWordWithSpaces() { + assertEquals(""foo bar"", Parser.switchEscapedSpacesToSpacesInWord(""foo\\ bar"") ); + assertEquals("" foo bar"", Parser.switchEscapedSpacesToSpacesInWord(""\\ foo\\ bar"") ); + assertEquals("" foo bar "", Parser.switchEscapedSpacesToSpacesInWord(""\\ foo\\ bar\\ "") ); + assertEquals("" foo bar"", Parser.switchEscapedSpacesToSpacesInWord(""\\ foo bar"") ); + + assertEquals(""foo\\ bar"", Parser.switchSpacesToEscapedSpacesInWord(""foo bar"")); + assertEquals(""\\ foo\\ bar"", Parser.switchSpacesToEscapedSpacesInWord("" foo bar"")); + assertEquals(""\\ foo\\ bar\\ "", Parser.switchSpacesToEscapedSpacesInWord("" foo bar "")); + } + }" a8dbce159679cd031f60e6151399fa2cd5ac9374,hadoop,HADOOP-7223. FileContext createFlag combinations- are not clearly defined. Contributed by Suresh Srinivas.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@1092565 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/hadoop,"diff --git a/CHANGES.txt b/CHANGES.txt index a6186537bdbb6..7a2ece8c71744 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,4 +1,4 @@ -Hadoop Change Log +Hn jaadoop Change Log Trunk (unreleased changes) @@ -139,6 +139,10 @@ Trunk (unreleased changes) HADOOP-7207. fs member of FSShell is not really needed (boryas) + HADOOP-7223. FileContext createFlag combinations are not clearly defined. + (suresh) + + Release 0.22.0 - Unreleased INCOMPATIBLE CHANGES diff --git a/src/java/org/apache/hadoop/fs/ChecksumFs.java b/src/java/org/apache/hadoop/fs/ChecksumFs.java index a55108598becd..87cd5a77dec39 100644 --- a/src/java/org/apache/hadoop/fs/ChecksumFs.java +++ b/src/java/org/apache/hadoop/fs/ChecksumFs.java @@ -337,8 +337,9 @@ public ChecksumFSOutputSummer(final ChecksumFs fs, final Path file, int bytesPerSum = fs.getBytesPerSum(); int sumBufferSize = fs.getSumBufferSize(bytesPerSum, bufferSize); this.sums = fs.getRawFs().createInternal(fs.getChecksumFile(file), - EnumSet.of(CreateFlag.OVERWRITE), absolutePermission, sumBufferSize, - replication, blockSize, progress, bytesPerChecksum, createParent); + EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE), + absolutePermission, sumBufferSize, replication, blockSize, progress, + bytesPerChecksum, createParent); sums.write(CHECKSUM_VERSION, 0, CHECKSUM_VERSION.length); sums.writeInt(bytesPerSum); } diff --git a/src/java/org/apache/hadoop/fs/CreateFlag.java b/src/java/org/apache/hadoop/fs/CreateFlag.java index 375876a8bdb40..4373124caabf4 100644 --- a/src/java/org/apache/hadoop/fs/CreateFlag.java +++ b/src/java/org/apache/hadoop/fs/CreateFlag.java @@ -17,49 +17,63 @@ */ package org.apache.hadoop.fs; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.EnumSet; + +import org.apache.hadoop.HadoopIllegalArgumentException; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; /**************************************************************** - *CreateFlag specifies the file create semantic. Users can combine flags like:
- * + * CreateFlag specifies the file create semantic. Users can combine flags like:
+ * * EnumSet.of(CreateFlag.CREATE, CreateFlag.APPEND) * - * and pass it to {@link org.apache.hadoop.fs.FileSystem #create(Path f, FsPermission permission, - * EnumSet flag, int bufferSize, short replication, long blockSize, - * Progressable progress)}. - * *

- * Combine {@link #OVERWRITE} with either {@link #CREATE} - * or {@link #APPEND} does the same as only use - * {@link #OVERWRITE}.
- * Combine {@link #CREATE} with {@link #APPEND} has the semantic: + * + * Use the CreateFlag as follows: + *

    + *
  1. CREATE - to create a file if it does not exist, + * else throw FileAlreadyExists.
  2. + *
  3. APPEND - to append to a file if it exists, + * else throw FileNotFoundException.
  4. + *
  5. OVERWRITE - to truncate a file if it exists, + * else throw FileNotFoundException.
  6. + *
  7. CREATE|APPEND - to create a file if it does not exist, + * else append to an existing file.
  8. + *
  9. CREATE|OVERWRITE - to create a file if it does not exist, + * else overwrite an existing file.
  10. + *
+ * + * Following combination is not valid and will result in + * {@link HadoopIllegalArgumentException}: *
    - *
  1. create the file if it does not exist; - *
  2. append the file if it already exists. + *
  3. APPEND|OVERWRITE
  4. + *
  5. CREATE|APPEND|OVERWRITE
  6. *
*****************************************************************/ @InterfaceAudience.Public -@InterfaceStability.Stable +@InterfaceStability.Evolving public enum CreateFlag { /** - * create the file if it does not exist, and throw an IOException if it + * Create a file. See javadoc for more description * already exists */ CREATE((short) 0x01), /** - * create the file if it does not exist, if it exists, overwrite it. + * Truncate/overwrite a file. Same as POSIX O_TRUNC. See javadoc for description. */ OVERWRITE((short) 0x02), /** - * append to a file, and throw an IOException if it does not exist + * Append to a file. See javadoc for more description. */ APPEND((short) 0x04); - private short mode; + private final short mode; private CreateFlag(short mode) { this.mode = mode; @@ -68,4 +82,49 @@ private CreateFlag(short mode) { short getMode() { return mode; } + + /** + * Validate the CreateFlag and throw exception if it is invalid + * @param flag set of CreateFlag + * @throws HadoopIllegalArgumentException if the CreateFlag is invalid + */ + public static void validate(EnumSet flag) { + if (flag == null || flag.isEmpty()) { + throw new HadoopIllegalArgumentException(flag + + "" does not specify any options""); + } + final boolean append = flag.contains(APPEND); + final boolean overwrite = flag.contains(OVERWRITE); + + // Both append and overwrite is an error + if (append && overwrite) { + throw new HadoopIllegalArgumentException( + flag + ""Both append and overwrite options cannot be enabled.""); + } + } + + /** + * Validate the CreateFlag for create operation + * @param path Object representing the path; usually String or {@link Path} + * @param pathExists pass true if the path exists in the file system + * @param flag set of CreateFlag + * @throws IOException on error + * @throws HadoopIllegalArgumentException if the CreateFlag is invalid + */ + public static void validate(Object path, boolean pathExists, + EnumSet flag) throws IOException { + validate(flag); + final boolean append = flag.contains(APPEND); + final boolean overwrite = flag.contains(OVERWRITE); + if (pathExists) { + if (!(append || overwrite)) { + throw new FileAlreadyExistsException(""File already exists: "" + + path.toString() + + "". Append or overwrite option must be specified in "" + flag); + } + } else if (!flag.contains(CREATE)) { + throw new FileNotFoundException(""Non existing file: "" + path.toString() + + "". Create option is not specified in "" + flag); + } + } } \ No newline at end of file diff --git a/src/java/org/apache/hadoop/fs/FileContext.java b/src/java/org/apache/hadoop/fs/FileContext.java index 2596daae5e7b4..e3163ea75e5b7 100644 --- a/src/java/org/apache/hadoop/fs/FileContext.java +++ b/src/java/org/apache/hadoop/fs/FileContext.java @@ -511,7 +511,7 @@ public Path makeQualified(final Path path) { * writing into the file. * * @param f the file name to open - * @param createFlag gives the semantics of create: overwrite, append etc. + * @param createFlag gives the semantics of create; see {@link CreateFlag} * @param opts file creation options; see {@link Options.CreateOpts}. *