commit_id
stringlengths
40
40
project
stringclasses
90 values
commit_message
stringlengths
5
2.21k
type
stringclasses
3 values
url
stringclasses
89 values
git_diff
stringlengths
283
4.32M
847fbb7e7e5692c23ff45717d80fd88f32da813a
Search_api
Issue #2013581 by drunken monkey: Added multi-valued field to test module.
a
https://github.com/lucidworks/drupal_search_api
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 0befa20d..0a21b9ea 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,5 +1,6 @@ Search API 1.x, dev (xx/xx/xxxx): --------------------------------- +- #2013581 by drunken monkey: Added multi-valued field to test module. - #1288724 by brunodbo, drunken monkey, fearlsgroove: Added option for using OR in Views fulltext search. - #1694832 by drunken monkey: Fixed index field settings getting stale when diff --git a/tests/search_api_test.install b/tests/search_api_test.install index f06f37d4..8dea6ebc 100644 --- a/tests/search_api_test.install +++ b/tests/search_api_test.install @@ -22,7 +22,7 @@ function search_api_test_schema() { 'description' => 'The title of the item.', 'type' => 'varchar', 'length' => 50, - 'not null' => TRUE, + 'not null' => FALSE, ), 'body' => array( 'description' => 'A text belonging to the item.', @@ -33,7 +33,13 @@ function search_api_test_schema() { 'description' => 'A string identifying the type of item.', 'type' => 'varchar', 'length' => 50, - 'not null' => TRUE, + 'not null' => FALSE, + ), + 'keywords' => array( + 'description' => 'A comma separated list of keywords.', + 'type' => 'varchar', + 'length' => 200, + 'not null' => FALSE, ), ), 'primary key' => array('id'), diff --git a/tests/search_api_test.module b/tests/search_api_test.module index 618e4f1c..67e33920 100644 --- a/tests/search_api_test.module +++ b/tests/search_api_test.module @@ -43,6 +43,9 @@ function search_api_test_insert_item(array $form, array &$form_state) { 'type' => array( '#type' => 'textfield', ), + 'keywords' => array( + '#type' => 'textfield', + ), 'submit' => array( '#type' => 'submit', '#value' => t('Save'), @@ -55,7 +58,7 @@ function search_api_test_insert_item(array $form, array &$form_state) { */ function search_api_test_insert_item_submit(array $form, array &$form_state) { form_state_values_clean($form_state); - db_insert('search_api_test')->fields($form_state['values'])->execute(); + db_insert('search_api_test')->fields(array_filter($form_state['values']))->execute(); module_invoke_all('entity_insert', search_api_test_load($form_state['values']['id']), 'search_api_test'); } @@ -78,24 +81,6 @@ function search_api_test_view($entity) { * Menu callback for executing a search. */ function search_api_test_query(SearchApiIndex $index, $keys = 'foo bar', $offset = 0, $limit = 10, $fields = NULL, $sort = NULL, $filters = NULL) { - // Slight "hack" for testing complex queries. - if ($keys == '|COMPLEX|') { - $keys = array( - '#conjunction' => 'AND', - 'test', - array( - '#conjunction' => 'OR', - 'baz', - 'foobar', - ), - array( - '#conjunction' => 'OR', - '#negation' => TRUE, - 'bar', - 'fooblob', - ), - ); - } $query = $index->query() ->keys($keys ? $keys : NULL) ->range($offset, $limit); @@ -178,6 +163,12 @@ function search_api_test_entity_property_info() { 'description' => "The item's parent.", 'getter callback' => 'search_api_test_parent', ), + 'keywords' => array( + 'label' => 'Keywords', + 'type' => 'list<string>', + 'description' => 'An optional collection of keywords describing the item.', + 'getter callback' => 'search_api_test_list_callback', + ), ); return $info; @@ -199,6 +190,20 @@ function search_api_test_parent($entity) { return search_api_test_load($entity->id - 1); } +/** + * List callback. + */ +function search_api_test_list_callback($data) { + //return is_array($entity->keywords) ? $entity->keywords : explode(',', $entity->keywords); + if (is_array($data)) { + $res = is_array($data['keywords']) ? $data['keywords'] : explode(',', $data['keywords']); + } + else { + $res = is_array($data->keywords) ? $data->keywords : explode(',', $data->keywords); + } + return array_filter($res); +} + /** * Implements hook_search_api_service_info(). */
f26b7b2321ba561c947da92510e95e22f059351c
ReactiveX-RxJava
Conditionals: Fix all but 2 tests--
c
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-contrib/rxjava-computation-expressions/src/test/java/rx/operators/OperationConditionalsTest.java b/rxjava-contrib/rxjava-computation-expressions/src/test/java/rx/operators/OperationConditionalsTest.java index f6c4f09ad0..44bb0c02c8 100644 --- a/rxjava-contrib/rxjava-computation-expressions/src/test/java/rx/operators/OperationConditionalsTest.java +++ b/rxjava-contrib/rxjava-computation-expressions/src/test/java/rx/operators/OperationConditionalsTest.java @@ -15,6 +15,7 @@ */ package rx.operators; +import static org.junit.Assert.*; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; @@ -33,8 +34,10 @@ import rx.Observer; import rx.Statement; import rx.Subscription; +import rx.observers.TestObserver; import rx.schedulers.Schedulers; import rx.schedulers.TestScheduler; +import rx.util.functions.Action1; import rx.util.functions.Func0; public class OperationConditionalsTest { @@ -108,7 +111,7 @@ public T call() { <T> void observe(Observable<? extends T> source, T... values) { Observer<T> o = mock(Observer.class); - Subscription s = source.subscribe(o); + Subscription s = source.subscribe(new TestObserver<T>(o)); InOrder inOrder = inOrder(o); @@ -127,7 +130,7 @@ <T> void observe(Observable<? extends T> source, T... values) { <T> void observeSequence(Observable<? extends T> source, Iterable<? extends T> values) { Observer<T> o = mock(Observer.class); - Subscription s = source.subscribe(o); + Subscription s = source.subscribe(new TestObserver<T>(o)); InOrder inOrder = inOrder(o); @@ -146,7 +149,7 @@ <T> void observeSequence(Observable<? extends T> source, Iterable<? extends T> v <T> void observeError(Observable<? extends T> source, Class<? extends Throwable> error, T... valuesBeforeError) { Observer<T> o = mock(Observer.class); - Subscription s = source.subscribe(o); + Subscription s = source.subscribe(new TestObserver<T>(o)); InOrder inOrder = inOrder(o); @@ -165,7 +168,7 @@ <T> void observeError(Observable<? extends T> source, Class<? extends Throwable> <T> void observeSequenceError(Observable<? extends T> source, Class<? extends Throwable> error, Iterable<? extends T> valuesBeforeError) { Observer<T> o = mock(Observer.class); - Subscription s = source.subscribe(o); + Subscription s = source.subscribe(new TestObserver<T>(o)); InOrder inOrder = inOrder(o); @@ -400,6 +403,7 @@ public Boolean call() { @Test public void testDoWhileManyTimes() { + fail("deadlocking"); Observable<Integer> source1 = Observable.from(1, 2, 3).subscribeOn(Schedulers.currentThread()); List<Integer> expected = new ArrayList<Integer>(numRecursion * 3);
635b24fec892a394fba1eb9154a3c6888020f419
restlet-framework-java
- Updated Jetty to version 7.0 RC4.- Upgraded the Jetty extension: replaced "headerBufferSize" parameter- by "requestHeaderSize" and "responseHeaderSize" parameters. - Removed "lowThreads" parameter no longer available.--
p
https://github.com/restlet/restlet-framework-java
diff --git a/build/tmpl/text/changes.txt b/build/tmpl/text/changes.txt index f56805331c..2540f46b00 100644 --- a/build/tmpl/text/changes.txt +++ b/build/tmpl/text/changes.txt @@ -35,6 +35,10 @@ Changes log - Updated Velocity to version 1.6.2. - Updated JiBX to version 1.2.1. - Updated db4o to version 7.10.96. + - Updated Jetty to version 7.0 RC4. Upgraded the Jetty + extension: replaced "headerBufferSize" parameter by + "requestHeaderSize" and "responseHeaderSize" parameters. + Removed "lowThreads" parameter no longer available. - Updated the Javadocs of the API to indicate the mapping between properties/classes and HTTP headers. - Updated the "Server" HTTP header returned by default to diff --git a/libraries/org.eclipse.jetty_7.0/.classpath b/libraries/org.eclipse.jetty_7.0/.classpath index 50e4634365..5a7b154d16 100644 --- a/libraries/org.eclipse.jetty_7.0/.classpath +++ b/libraries/org.eclipse.jetty_7.0/.classpath @@ -1,5 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?> <classpath> + <classpathentry exported="true" kind="lib" path="org.eclipse.jetty.continuations.jar"/> <classpathentry exported="true" kind="lib" path="org.eclipse.jetty.io.jar"/> <classpathentry exported="true" kind="lib" path="org.eclipse.jetty.ajp.jar"/> <classpathentry exported="true" kind="lib" path="org.eclipse.jetty.http.jar"/> diff --git a/libraries/org.eclipse.jetty_7.0/META-INF/MANIFEST.MF b/libraries/org.eclipse.jetty_7.0/META-INF/MANIFEST.MF index 6e56bd48dc..6c08541f17 100644 --- a/libraries/org.eclipse.jetty_7.0/META-INF/MANIFEST.MF +++ b/libraries/org.eclipse.jetty_7.0/META-INF/MANIFEST.MF @@ -7,7 +7,8 @@ Bundle-ClassPath: org.eclipse.jetty.ajp.jar, org.eclipse.jetty.http.jar, org.eclipse.jetty.server.jar, org.eclipse.jetty.util.jar, - org.eclipse.jetty.io.jar + org.eclipse.jetty.io.jar, + org.eclipse.jetty.continuations.jar Bundle-Vendor: Eclipse Foundation Bundle-RequiredExecutionEnvironment: J2SE-1.5 Import-Package: javax.servlet, @@ -19,6 +20,7 @@ Export-Package: org.eclipse.jetty.ajp; org.eclipse.jetty.io, org.eclipse.jetty.http, org.eclipse.jetty.server.bio", + org.eclipse.jetty.continuation;uses:="javax.servlet,org.mortbay.util.ajax", org.eclipse.jetty.http; uses:="org.eclipse.jetty.io, org.eclipse.jetty.util.resource, diff --git a/libraries/org.eclipse.jetty_7.0/build.properties b/libraries/org.eclipse.jetty_7.0/build.properties index ccc3c69b2c..6d62fe8c00 100644 --- a/libraries/org.eclipse.jetty_7.0/build.properties +++ b/libraries/org.eclipse.jetty_7.0/build.properties @@ -3,5 +3,6 @@ bin.includes = META-INF/,\ org.eclipse.jetty.http.jar,\ org.eclipse.jetty.server.jar,\ org.eclipse.jetty.util.jar,\ - org.eclipse.jetty.io.jar + org.eclipse.jetty.io.jar,\ + org.eclipse.jetty.continuations.jar diff --git a/libraries/org.eclipse.jetty_7.0/org.eclipse.jetty.continuations.jar b/libraries/org.eclipse.jetty_7.0/org.eclipse.jetty.continuations.jar new file mode 100644 index 0000000000..e816cb7725 Binary files /dev/null and b/libraries/org.eclipse.jetty_7.0/org.eclipse.jetty.continuations.jar differ diff --git a/libraries/org.mortbay.jetty_6.1/.classpath b/libraries/org.mortbay.jetty_6.1/.classpath deleted file mode 100644 index a0bab312d0..0000000000 --- a/libraries/org.mortbay.jetty_6.1/.classpath +++ /dev/null @@ -1,10 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<classpath> - <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/> - <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry exported="true" kind="lib" path="org.mortbay.jetty.util.jar" sourcepath="org.mortbay.jetty_6.1src.zip"/> - <classpathentry exported="true" kind="lib" path="org.mortbay.jetty.jar" sourcepath="org.mortbay.jetty_6.1src.zip"/> - <classpathentry exported="true" kind="lib" path="org.mortbay.jetty.ajp.jar" sourcepath="org.mortbay.jetty_6.1src.zip"/> - <classpathentry exported="true" kind="lib" path="org.mortbay.jetty.https.jar" sourcepath="org.mortbay.jetty_6.1src.zip"/> - <classpathentry kind="output" path="bin"/> -</classpath> diff --git a/libraries/org.mortbay.jetty_6.1/.project b/libraries/org.mortbay.jetty_6.1/.project deleted file mode 100644 index b569941a8b..0000000000 --- a/libraries/org.mortbay.jetty_6.1/.project +++ /dev/null @@ -1,28 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.mortbay.jetty</name> - <comment></comment> - <projects> - </projects> - <buildSpec> - <buildCommand> - <name>org.eclipse.jdt.core.javabuilder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.pde.ManifestBuilder</name> - <arguments> - </arguments> - </buildCommand> - <buildCommand> - <name>org.eclipse.pde.SchemaBuilder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.pde.PluginNature</nature> - <nature>org.eclipse.jdt.core.javanature</nature> - </natures> -</projectDescription> diff --git a/libraries/org.mortbay.jetty_6.1/META-INF/MANIFEST.MF b/libraries/org.mortbay.jetty_6.1/META-INF/MANIFEST.MF deleted file mode 100644 index c1e1ab0ba8..0000000000 --- a/libraries/org.mortbay.jetty_6.1/META-INF/MANIFEST.MF +++ /dev/null @@ -1,94 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Jetty HTTP server 6.1 -Bundle-SymbolicName: org.mortbay.jetty -Bundle-Version: 6.1.18 -Bundle-ClassPath: org.mortbay.jetty.util.jar, - org.mortbay.jetty.jar, org.mortbay.jetty.ajp.jar, org.mortbay.jetty.https.jar -Bundle-Vendor: Mortbay Consulting -Export-Package: org.mortbay.component;uses:="new org.mortbay.component", - org.mortbay.io;uses:="org.mortbay.util", - org.mortbay.io.bio;uses:="org.mortbay.io", - org.mortbay.io.nio;uses:="org.mortbay.io,org.mortbay.thread,org.mortbay.component", - org.mortbay.jetty; - uses:="org.mortbay.io, - new org.mortbay.jetty, - org.mortbay.jetty.security, - org.mortbay.jetty.handler, - org.mortbay.resource, - javax.servlet, - org.mortbay.jetty.servlet, - org.mortbay.util.ajax, - org.mortbay.thread, - org.mortbay.component, - org.mortbay.util, - javax.servlet.http", - org.mortbay.jetty.ajp; - uses:="org.mortbay.jetty, - javax.servlet, - org.mortbay.jetty.bio, - org.mortbay.io", - org.mortbay.jetty.bio;uses:="org.mortbay.jetty,org.mortbay.io,org.mortbay.io.bio", - org.mortbay.jetty.deployer; - uses:="org.mortbay.jetty, - org.mortbay.resource, - org.mortbay.jetty.handler, - org.mortbay.component, - org.mortbay.util", - org.mortbay.jetty.handler; - uses:="org.mortbay.jetty, - org.mortbay.log, - org.mortbay.io, - org.mortbay.resource, - javax.servlet, - org.mortbay.jetty.servlet, - org.mortbay.component, - org.mortbay.util, - javax.servlet.http", - org.mortbay.jetty.nio; - uses:="org.mortbay.jetty, - org.mortbay.io.nio, - org.mortbay.util.ajax, - org.mortbay.io, - org.mortbay.thread", - org.mortbay.jetty.security; - uses:="org.mortbay.jetty, - org.mortbay.io.nio, - org.mortbay.io, - javax.net.ssl, - org.mortbay.jetty.nio", - org.mortbay.jetty.servlet; - uses:="org.mortbay.jetty, - org.mortbay.io, - org.mortbay.jetty.security, - new org.mortbay.jetty.servlet, - org.mortbay.jetty.handler, - org.mortbay.resource, - javax.servlet, - org.mortbay.util, - org.mortbay.component, - javax.servlet.http", - org.mortbay.jetty.webapp; - uses:="org.mortbay.jetty, - org.mortbay.jetty.security, - org.mortbay.xml, - org.mortbay.jetty.handler, - org.mortbay.resource, - org.mortbay.jetty.servlet, - javax.servlet.http", - org.mortbay.log, - org.mortbay.resource, - org.mortbay.servlet;uses:="javax.servlet,org.mortbay.util,javax.servlet.http", - org.mortbay.servlet.jetty;uses:="org.mortbay.servlet,javax.servlet.http", - org.mortbay.thread;uses:="org.mortbay.component", - org.mortbay.util;uses:="org.mortbay.thread", - org.mortbay.util.ajax; - uses:="javax.servlet, - org.mortbay.util, - new org.mortbay.util.ajax, - javax.servlet.http", - org.mortbay.xml;uses:="javax.xml.parsers,org.xml.sax" -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Import-Package: javax.servlet, - javax.servlet.http, - javax.servlet.resources diff --git a/libraries/org.mortbay.jetty_6.1/build.properties b/libraries/org.mortbay.jetty_6.1/build.properties deleted file mode 100644 index 3674e8ac5a..0000000000 --- a/libraries/org.mortbay.jetty_6.1/build.properties +++ /dev/null @@ -1,5 +0,0 @@ -bin.includes = META-INF/,\ - org.mortbay.jetty.util.jar,\ - org.mortbay.jetty.jar,\ - org.mortbay.jetty.ajp.jar,\ - org.mortbay.jetty.https.jar diff --git a/libraries/org.mortbay.jetty_6.1/library.xml b/libraries/org.mortbay.jetty_6.1/library.xml deleted file mode 100644 index 643033acc7..0000000000 --- a/libraries/org.mortbay.jetty_6.1/library.xml +++ /dev/null @@ -1,17 +0,0 @@ -<library id="jetty"> - <package name="org.mortbay.jetty" /> - <version>6.1</version> - <release>18</release> - <distributions> - <distribution id="classic" /> - </distributions> - <homeUri> - http://www.mortbay.org/jetty/ - </homeUri> - <downloadUri> - http://docs.codehaus.org/display/JETTY/Downloading+Jetty - </downloadUri> - <javadocs> - <link href="http://jetty.mortbay.org/apidocs/" /> - </javadocs> -</library> diff --git a/libraries/org.mortbay.jetty_6.1/license.txt b/libraries/org.mortbay.jetty_6.1/license.txt deleted file mode 100644 index d645695673..0000000000 --- a/libraries/org.mortbay.jetty_6.1/license.txt +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/libraries/org.mortbay.jetty_6.1/org.mortbay.jetty.ajp.jar b/libraries/org.mortbay.jetty_6.1/org.mortbay.jetty.ajp.jar deleted file mode 100644 index 5cb25ae526..0000000000 Binary files a/libraries/org.mortbay.jetty_6.1/org.mortbay.jetty.ajp.jar and /dev/null differ diff --git a/libraries/org.mortbay.jetty_6.1/org.mortbay.jetty.https.jar b/libraries/org.mortbay.jetty_6.1/org.mortbay.jetty.https.jar deleted file mode 100644 index 3f690c09f1..0000000000 Binary files a/libraries/org.mortbay.jetty_6.1/org.mortbay.jetty.https.jar and /dev/null differ diff --git a/libraries/org.mortbay.jetty_6.1/org.mortbay.jetty.jar b/libraries/org.mortbay.jetty_6.1/org.mortbay.jetty.jar deleted file mode 100644 index 0fea05246f..0000000000 Binary files a/libraries/org.mortbay.jetty_6.1/org.mortbay.jetty.jar and /dev/null differ diff --git a/libraries/org.mortbay.jetty_6.1/org.mortbay.jetty.util.jar b/libraries/org.mortbay.jetty_6.1/org.mortbay.jetty.util.jar deleted file mode 100644 index dbe3cf79c2..0000000000 Binary files a/libraries/org.mortbay.jetty_6.1/org.mortbay.jetty.util.jar and /dev/null differ diff --git a/libraries/org.mortbay.jetty_6.1/readme.txt b/libraries/org.mortbay.jetty_6.1/readme.txt deleted file mode 100644 index 6b3b5275c0..0000000000 --- a/libraries/org.mortbay.jetty_6.1/readme.txt +++ /dev/null @@ -1,13 +0,0 @@ -------------- -Mortbay Jetty -------------- - -"Jetty is an open-source, standards-based, full-featured web server implemented -entirely in java. It is released under the Apache 2.0 licence and is therefore -free for commercial use and distribution. First created in 1995, Jetty has -benefitted from input from a vast user community and consistent and focussed -development by a stable core of lead developers. Full commercial 24x7 support, -training and development services for Jetty are available from Webtide." - -For more information: -http://jetty.mortbay.org/ \ No newline at end of file diff --git a/modules/org.restlet.ext.jetty/META-INF/MANIFEST.MF b/modules/org.restlet.ext.jetty/META-INF/MANIFEST.MF index 219c9eb1ae..ca00a991a0 100644 --- a/modules/org.restlet.ext.jetty/META-INF/MANIFEST.MF +++ b/modules/org.restlet.ext.jetty/META-INF/MANIFEST.MF @@ -15,14 +15,23 @@ Export-Package: org.restlet.ext.jetty; Import-Package: javax.servlet, javax.servlet.http, javax.servlet.resources, - org.mortbay.component, - org.mortbay.jetty, - org.mortbay.jetty.ajp, - org.mortbay.jetty.bio, - org.mortbay.jetty.handler, - org.mortbay.jetty.nio, - org.mortbay.jetty.security, - org.mortbay.thread, + org.eclipse.jetty.ajp, + org.eclipse.jetty.http, + org.eclipse.jetty.http.security, + org.eclipse.jetty.http.ssl, + org.eclipse.jetty.io, + org.eclipse.jetty.server, + org.eclipse.jetty.server.bio, + org.eclipse.jetty.server.handler, + org.eclipse.jetty.server.nio, + org.eclipse.jetty.server.session, + org.eclipse.jetty.server.ssl, + org.eclipse.jetty.util, + org.eclipse.jetty.util.ajax, + org.eclipse.jetty.util.component, + org.eclipse.jetty.util.log, + org.eclipse.jetty.util.resource, + org.eclipse.jetty.util.thread, org.restlet, org.restlet.data, org.restlet.engine, diff --git a/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/AjpServerHelper.java b/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/AjpServerHelper.java index da68aae8fc..fc737bdbd1 100644 --- a/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/AjpServerHelper.java +++ b/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/AjpServerHelper.java @@ -30,8 +30,8 @@ package org.restlet.ext.jetty; -import org.mortbay.jetty.AbstractConnector; -import org.mortbay.jetty.ajp.Ajp13SocketConnector; +import org.eclipse.jetty.ajp.Ajp13SocketConnector; +import org.eclipse.jetty.server.AbstractConnector; import org.restlet.Server; import org.restlet.data.Protocol; diff --git a/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/HttpServerHelper.java b/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/HttpServerHelper.java index 788d728ca1..e3083d7aba 100644 --- a/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/HttpServerHelper.java +++ b/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/HttpServerHelper.java @@ -30,10 +30,10 @@ package org.restlet.ext.jetty; -import org.mortbay.jetty.AbstractConnector; -import org.mortbay.jetty.bio.SocketConnector; -import org.mortbay.jetty.nio.BlockingChannelConnector; -import org.mortbay.jetty.nio.SelectChannelConnector; +import org.eclipse.jetty.server.AbstractConnector; +import org.eclipse.jetty.server.bio.SocketConnector; +import org.eclipse.jetty.server.nio.BlockingChannelConnector; +import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.restlet.Server; import org.restlet.data.Protocol; diff --git a/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/HttpsServerHelper.java b/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/HttpsServerHelper.java index 54240656ba..3f8500dd22 100644 --- a/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/HttpsServerHelper.java +++ b/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/HttpsServerHelper.java @@ -35,15 +35,14 @@ import javax.net.ssl.SSLContext; import javax.net.ssl.SSLServerSocketFactory; -import org.mortbay.jetty.AbstractConnector; -import org.mortbay.jetty.security.SslSelectChannelConnector; -import org.mortbay.jetty.security.SslSocketConnector; +import org.eclipse.jetty.server.AbstractConnector; +import org.eclipse.jetty.server.ssl.SslSelectChannelConnector; +import org.eclipse.jetty.server.ssl.SslSocketConnector; import org.restlet.Server; import org.restlet.data.Protocol; import org.restlet.engine.http.HttpsUtils; import org.restlet.engine.security.SslContextFactory; - /** * Jetty HTTPS server connector. Here is the list of additional parameters that * are supported: @@ -140,7 +139,9 @@ * </tr> * </table> * - * @see <a href="http://docs.codehaus.org/display/JETTY/How+to+configure+SSL">How to configure SSL for Jetty</a> + * @see <a + * href="http://docs.codehaus.org/display/JETTY/How+to+configure+SSL">How + * to configure SSL for Jetty</a> * @author Jerome Louvel */ public class HttpsServerHelper extends JettyServerHelper { diff --git a/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/JettyCall.java b/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/JettyCall.java index e555c89f60..d113540add 100644 --- a/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/JettyCall.java +++ b/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/JettyCall.java @@ -42,8 +42,8 @@ import java.util.List; import java.util.logging.Level; -import org.mortbay.jetty.EofException; -import org.mortbay.jetty.HttpConnection; +import org.eclipse.jetty.io.EofException; +import org.eclipse.jetty.server.HttpConnection; import org.restlet.Response; import org.restlet.Server; import org.restlet.data.Parameter; @@ -153,7 +153,6 @@ public ReadableByteChannel getRequestHeadChannel() { * @return The list of request headers. */ @Override - @SuppressWarnings("unchecked") public Series<Parameter> getRequestHeaders() { final Series<Parameter> result = super.getRequestHeaders(); diff --git a/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/JettyHandler.java b/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/JettyHandler.java index 0f3241783f..dd68342063 100644 --- a/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/JettyHandler.java +++ b/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/JettyHandler.java @@ -36,9 +36,9 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.mortbay.jetty.HttpConnection; -import org.mortbay.jetty.Request; -import org.mortbay.jetty.handler.AbstractHandler; +import org.eclipse.jetty.server.HttpConnection; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.handler.AbstractHandler; import org.restlet.Server; /** @@ -100,15 +100,16 @@ protected void doStop() throws Exception { * The target of the request, either a URI or a name. * @param request * The Jetty request. - * @param response - * The Jetty response. - * @param dispatch - * The Jetty dispatch mode. + * @param servletRequest + * The Servlet request. + * @param servletResponse + * The Servlet response. */ - public void handle(String target, HttpServletRequest request, - HttpServletResponse response, int dispatch) throws IOException, + public void handle(String target, Request arg1, + HttpServletRequest servletRequest, + HttpServletResponse servletResponse) throws IOException, ServletException { - final Request baseRequest = (request instanceof Request) ? (Request) request + final Request baseRequest = (servletRequest instanceof Request) ? (Request) servletRequest : HttpConnection.getCurrentConnection().getRequest(); this.helper.handle(new JettyCall(this.helper.getHelped(), HttpConnection.getCurrentConnection())); diff --git a/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/JettyServerHelper.java b/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/JettyServerHelper.java index a1ebeca86e..e54124708e 100644 --- a/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/JettyServerHelper.java +++ b/modules/org.restlet.ext.jetty/src/org/restlet/ext/jetty/JettyServerHelper.java @@ -34,10 +34,10 @@ import javax.servlet.ServletException; -import org.mortbay.jetty.AbstractConnector; -import org.mortbay.jetty.HttpConnection; -import org.mortbay.jetty.Server; -import org.mortbay.thread.QueuedThreadPool; +import org.eclipse.jetty.server.AbstractConnector; +import org.eclipse.jetty.server.HttpConnection; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.util.thread.QueuedThreadPool; /** * Abstract Jetty Web server connector. Here is the list of parameters that are @@ -68,13 +68,6 @@ * <td>Time for an idle thread to wait for a request or read.</td> * </tr> * <tr> - * <td>lowThreads</td> - * <td>int</td> - * <td>25</td> - * <td>Threshold of remaining threads at which the server is considered as - * running low on resources.</td> - * </tr> - * <tr> * <td>lowResourceMaxIdleTimeMs</td> * <td>int</td> * <td>2500</td> @@ -94,10 +87,16 @@ * <td>Size of the accept queue.</td> * </tr> * <tr> - * <td>headerBufferSize</td> + * <td>requestHeaderSize</td> + * <td>int</td> + * <td>4*1024</td> + * <td>Size of the buffer to be used for request headers.</td> + * </tr> + * <tr> + * <td>responseHeaderSize</td> * <td>int</td> * <td>4*1024</td> - * <td>Size of the buffer to be used for request and response headers.</td> + * <td>Size of the buffer to be used for response headers.</td> * </tr> * <tr> * <td>requestBufferSize</td> @@ -159,7 +158,7 @@ public abstract class JettyServerHelper extends * * @author Jerome Louvel */ - private static class WrappedServer extends org.mortbay.jetty.Server { + private static class WrappedServer extends org.eclipse.jetty.server.Server { JettyServerHelper helper; /** @@ -218,7 +217,8 @@ protected void configure(AbstractConnector connector) { connector.setLowResourceMaxIdleTime(getLowResourceMaxIdleTimeMs()); connector.setAcceptors(getAcceptorThreads()); connector.setAcceptQueueSize(getAcceptQueueSize()); - connector.setHeaderBufferSize(getHeaderBufferSize()); + connector.setRequestHeaderSize(getRequestHeaderSize()); + connector.setResponseHeaderSize(getResponseHeaderSize()); connector.setRequestBufferSize(getRequestBufferSize()); connector.setResponseBufferSize(getResponseBufferSize()); connector.setMaxIdleTime(getIoMaxIdleTimeMs()); @@ -263,18 +263,6 @@ public int getGracefulShutdown() { "gracefulShutdown", "0")); } - /** - * Returns the size of the buffer to be used for request and response - * headers. - * - * @return The size of the buffer to be used for request and response - * headers. - */ - public int getHeaderBufferSize() { - return Integer.parseInt(getHelpedParameters().getFirstValue( - "headerBufferSize", Integer.toString(4 * 1024))); - } - /** * Returns the maximum time to wait on an idle IO operation. * @@ -297,18 +285,6 @@ public int getLowResourceMaxIdleTimeMs() { "lowResourceMaxIdleTimeMs", "2500")); } - /** - * Returns the threshold of remaining threads at which the server is - * considered as running low on resources. - * - * @return The threshold of remaining threads at which the server is - * considered as running low on resources. - */ - public int getLowThreads() { - return Integer.parseInt(getHelpedParameters().getFirstValue( - "lowThreads", "25")); - } - /** * Returns the maximum threads that will service requests. * @@ -339,6 +315,16 @@ public int getRequestBufferSize() { "requestBufferSize", Integer.toString(8 * 1024))); } + /** + * Returns the size of the buffer to be used for request headers. + * + * @return The size of the buffer to be used for request headers. + */ + public int getRequestHeaderSize() { + return Integer.parseInt(getHelpedParameters().getFirstValue( + "requestHeaderSize", Integer.toString(4 * 1024))); + } + /** * Returns the size of the content buffer for sending responses. * @@ -349,6 +335,16 @@ public int getResponseBufferSize() { "responseBufferSize", Integer.toString(32 * 1024))); } + /** + * Returns the size of the buffer to be used for response headers. + * + * @return The size of the buffer to be used for response headers. + */ + public int getResponseHeaderSize() { + return Integer.parseInt(getHelpedParameters().getFirstValue( + "responseHeaderSize", Integer.toString(4 * 1024))); + } + /** * Returns the SO linger time (see Jetty 6 documentation). * @@ -379,8 +375,7 @@ protected Server getWrappedServer() { this.wrappedServer = new WrappedServer(this); // Configuring the thread pool - final QueuedThreadPool btp = new QueuedThreadPool(); - btp.setLowThreads(getLowThreads()); + QueuedThreadPool btp = new QueuedThreadPool(); btp.setMaxIdleTimeMs(getThreadMaxIdleTimeMs()); btp.setMaxThreads(getMaxThreads()); btp.setMinThreads(getMinThreads());
d8fdf6abed4031adfa24a35ab23b78185cad6fc1
drools
[DROOLS-991] allow to configure maxEventsInMemory- in FileLogger--
a
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/KieLoggersTest.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/KieLoggersTest.java index 16a433a6708..be9896a32e3 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/KieLoggersTest.java +++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/KieLoggersTest.java @@ -15,12 +15,6 @@ package org.drools.compiler.integrationtests; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.File; - import org.drools.compiler.Message; import org.junit.Test; import org.kie.api.KieServices; @@ -31,12 +25,16 @@ import org.kie.api.builder.model.KieSessionModel; import org.kie.api.event.rule.AfterMatchFiredEvent; import org.kie.api.event.rule.AgendaEventListener; -import org.kie.api.runtime.KieContainer; -import org.kie.internal.io.ResourceFactory; import org.kie.api.io.Resource; import org.kie.api.logger.KieRuntimeLogger; +import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.StatelessKieSession; +import org.kie.internal.io.ResourceFactory; + +import java.io.File; + +import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class KieLoggersTest { @@ -186,6 +184,45 @@ public void testKieFileLogger() throws Exception { file = new File( fileName+".log" ); assertTrue( file.exists() ); + assertTrue( file.length() > 0 ); + file.delete(); + } + + @Test + public void testKieFileLoggerWithImmediateFlushing() throws Exception { + // DROOLS-991 + String drl = "package org.drools.integrationtests\n" + + "import org.drools.compiler.Message;\n" + + "rule \"Hello World\"\n" + + " when\n" + + " m : Message( myMessage : message )\n" + + " then\n" + + "end"; + // get the resource + Resource dt = ResourceFactory.newByteArrayResource(drl.getBytes()).setTargetPath( "org/drools/integrationtests/hello.drl" ); + + // create the builder + KieSession ksession = getKieSession(dt); + + String fileName = "testKieFileLogger"; + File file = new File(fileName+".log"); + if( file.exists() ) { + file.delete(); + } + + // Setting maxEventsInMemory to 0 makes all events to be immediately flushed to the file + KieRuntimeLogger logger = KieServices.Factory.get().getLoggers().newFileLogger( ksession, fileName, 0 ); + + ksession.insert(new Message("Hello World")); + int fired = ksession.fireAllRules(); + assertEquals( 1, fired ); + + // check that the file has been populated before closing it + file = new File( fileName+".log" ); + assertTrue( file.exists() ); + assertTrue( file.length() > 0 ); + + logger.close(); file.delete(); } diff --git a/drools-core/src/main/java/org/drools/core/audit/KnowledgeRuntimeLoggerProviderImpl.java b/drools-core/src/main/java/org/drools/core/audit/KnowledgeRuntimeLoggerProviderImpl.java index 99fc0618ba4..70b2b6036f8 100644 --- a/drools-core/src/main/java/org/drools/core/audit/KnowledgeRuntimeLoggerProviderImpl.java +++ b/drools-core/src/main/java/org/drools/core/audit/KnowledgeRuntimeLoggerProviderImpl.java @@ -31,7 +31,14 @@ public class KnowledgeRuntimeLoggerProviderImpl public KnowledgeRuntimeLogger newFileLogger(KieRuntimeEventManager session, String fileName) { + return newFileLogger(session, fileName, WorkingMemoryFileLogger.DEFAULT_MAX_EVENTS_IN_MEMORY); + } + + public KnowledgeRuntimeLogger newFileLogger(KieRuntimeEventManager session, + String fileName, + int maxEventsInMemory) { WorkingMemoryFileLogger logger = new WorkingMemoryFileLogger( (KnowledgeRuntimeEventManager) session ); + logger.setMaxEventsInMemory( maxEventsInMemory ); if ( fileName != null ) { logger.setFileName(fileName); } diff --git a/drools-core/src/main/java/org/drools/core/audit/WorkingMemoryFileLogger.java b/drools-core/src/main/java/org/drools/core/audit/WorkingMemoryFileLogger.java index 92a839e8d4d..493c090e2bf 100644 --- a/drools-core/src/main/java/org/drools/core/audit/WorkingMemoryFileLogger.java +++ b/drools-core/src/main/java/org/drools/core/audit/WorkingMemoryFileLogger.java @@ -16,9 +16,16 @@ package org.drools.core.audit; +import com.thoughtworks.xstream.XStream; +import org.drools.core.WorkingMemory; +import org.drools.core.audit.event.LogEvent; +import org.drools.core.util.IoUtils; +import org.kie.internal.event.KnowledgeRuntimeEventManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.FileNotFoundException; import java.io.FileOutputStream; -import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; @@ -27,19 +34,6 @@ import java.util.ArrayList; import java.util.List; -import org.drools.core.WorkingMemory; -import org.drools.core.audit.event.LogEvent; -import org.drools.core.util.IoUtils; -import org.kie.api.event.rule.AgendaGroupPoppedEvent; -import org.kie.api.event.rule.AgendaGroupPushedEvent; -import org.kie.api.event.rule.RuleFlowGroupActivatedEvent; -import org.kie.api.event.rule.RuleFlowGroupDeactivatedEvent; -import org.kie.internal.event.KnowledgeRuntimeEventManager; - -import com.thoughtworks.xstream.XStream; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * A logger of events generated by a working memory. It stores its information * in a file that can be specified. All the events logged are written to the @@ -55,9 +49,11 @@ public class WorkingMemoryFileLogger extends WorkingMemoryLogger { protected static final transient Logger logger = LoggerFactory.getLogger(WorkingMemoryFileLogger.class); + public static final int DEFAULT_MAX_EVENTS_IN_MEMORY = 1000; + private List<LogEvent> events = new ArrayList<LogEvent>(); private String fileName = "event"; - private int maxEventsInMemory = 1000; + private int maxEventsInMemory = DEFAULT_MAX_EVENTS_IN_MEMORY; private int nbOfFile = 0; private boolean split = true; private boolean initialized = false;
e9cba0d2cc00ce51932418aec929cbfb74dfd004
Vala
Add Signal to known attrs
a
https://github.com/GNOME/vala/
diff --git a/vala/valausedattr.vala b/vala/valausedattr.vala index 4a17562848..bb090fbc2b 100644 --- a/vala/valausedattr.vala +++ b/vala/valausedattr.vala @@ -56,6 +56,7 @@ public class Vala.UsedAttr : CodeVisitor { "HasEmitter", "", "ReturnsModifiedPointer", "", "Deprecated", "since", "replacement", "", + "Signal", "detailed", "run", "no_recurse", "action", "no_hooks", "", "IntegerType", "rank", "min", "max", "", "FloatingType", "rank", "",
6fd08d88f3724a73261ed91defe3c1881699fe9e
tapiji
Removes the unused completion proposal `ValueOfResourceBundleProposal`.
p
https://github.com/tapiji/tapiji
diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java index 2d6bdcac..ad0ad93f 100644 --- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java +++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java @@ -28,189 +28,204 @@ import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.contentassist.ICompletionProposal; - public class MessageCompletionProposalComputer implements - IJavaCompletionProposalComputer { - - private ResourceAuditVisitor csav; - private IJavaElement je; - private IJavaElement javaElement; - private CompilationUnit cu; - - public MessageCompletionProposalComputer() { - - } + IJavaCompletionProposalComputer { - - - @Override - public List<ICompletionProposal> computeCompletionProposals( - ContentAssistInvocationContext context, IProgressMonitor monitor) { - List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); - - if (!InternationalizationNature.hasNature(((JavaContentAssistInvocationContext) context) - .getCompilationUnit().getResource().getProject()) ) - return completions; - - try { - CompletionContext coreContext = ((JavaContentAssistInvocationContext) context) - .getCoreContext(); - int offset = coreContext.getOffset(); - - if (javaElement == null) - javaElement = ((JavaContentAssistInvocationContext) context) - .getCompilationUnit().getElementAt(offset); - - String stringLiteralStart = new String(coreContext.getToken()); - - // Check if the string literal is up to be written within the context - // of a resource-bundle accessor method - ResourceBundleManager manager = ResourceBundleManager.getManager(javaElement.getResource().getProject()); - - if (csav == null) { - csav = new ResourceAuditVisitor(null, - manager); - je = JavaCore.create(javaElement.getResource()); - } - - if (je instanceof ICompilationUnit) { - // get the type of the currently loaded resource - if (cu == null) { - ITypeRoot typeRoot = ((ICompilationUnit) je); - - if (typeRoot == null) - return null; - - cu = ASTutils.getCompilationUnit(typeRoot); - - cu.accept(csav); - } - - //StringLiteralAnalyzer sla = new StringLiteralAnalyzer(javaElement.getResource()); - if (csav.getKeyAt(new Long(offset)) != null) { - completions.addAll(getResourceBundleCompletionProposals(offset, stringLiteralStart, manager, csav, javaElement.getResource())); - } else if (csav.getRBReferenceAt(new Long(offset)) != null) { - completions.addAll(getRBReferenceCompletionProposals(offset, stringLiteralStart, manager, je.getResource())); - } else { - completions.addAll(getBasicJavaCompletionProposals(offset, stringLiteralStart, manager, csav, je.getResource())); - } - if (completions.size() == 1) - completions.add(new NoActionProposal()); - } else - return null; - } catch (Exception e) { - // e.printStackTrace(); - } - return completions; - } - - private Collection<ICompletionProposal> getRBReferenceCompletionProposals( - int offset, String stringLiteralStart, ResourceBundleManager manager, IResource resource) { - List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); - int posStart = offset - stringLiteralStart.length(); - boolean hit = false; - - // Show a list of available resource bundles - List<String> resourceBundles = manager.getResourceBundleIdentifiers(); - for (String rbName : resourceBundles) { - if (rbName.startsWith(stringLiteralStart)) { - if (rbName.equals(stringLiteralStart)) - hit = true; - else - completions.add (new MessageCompletionProposal (posStart, stringLiteralStart.length(), rbName, true)); - } - } - - if (!hit && stringLiteralStart.trim().length() > 0) - completions.add(new CreateResourceBundleProposal(stringLiteralStart, resource, posStart, posStart + stringLiteralStart.length())); - - return completions; - } + private ResourceAuditVisitor csav; + private IJavaElement je; + private IJavaElement javaElement; + private CompilationUnit cu; - protected List<ICompletionProposal> getBasicJavaCompletionProposals ( - int offset, String stringLiteralStart, - ResourceBundleManager manager, ResourceAuditVisitor csav, IResource resource) { - List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); - - if (stringLiteralStart.length() == 0) { - // If nothing has been entered - completions.add(new InsertResourceBundleReferenceProposal( - offset - stringLiteralStart.length(), - stringLiteralStart.length(), - manager, resource, csav.getDefinedResourceBundles(offset))); - completions.add(new NewResourceBundleEntryProposal(resource, offset - stringLiteralStart.length(), - false, manager, null/*, csav.getDefinedResourceBundles(offset)*/)); - } else { -// if (!"Hallo Welt".equals(stringLiteralStart)) { -// // If a part of a String has already been entered -// if ("Hallo Welt".startsWith(stringLiteralStart) ) { -// completions.add(new ValueOfResourceBundleProposal(offset - stringLiteralStart.length(), -// stringLiteralStart.length(), "hello.world", "Hallo Welt!")); -// } - completions.add(new NewResourceBundleEntryProposal(resource, offset - stringLiteralStart.length(), - false, manager, null/*, csav.getDefinedResourceBundles(offset)*/)); - -// } + public MessageCompletionProposalComputer() { + + } + + @Override + public List<ICompletionProposal> computeCompletionProposals( + ContentAssistInvocationContext context, IProgressMonitor monitor) { + List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); + + if (!InternationalizationNature + .hasNature(((JavaContentAssistInvocationContext) context) + .getCompilationUnit().getResource().getProject())) + return completions; + + try { + CompletionContext coreContext = ((JavaContentAssistInvocationContext) context) + .getCoreContext(); + int offset = coreContext.getOffset(); + + if (javaElement == null) + javaElement = ((JavaContentAssistInvocationContext) context) + .getCompilationUnit().getElementAt(offset); + + String stringLiteralStart = new String(coreContext.getToken()); + + // Check if the string literal is up to be written within the + // context + // of a resource-bundle accessor method + ResourceBundleManager manager = ResourceBundleManager + .getManager(javaElement.getResource().getProject()); + + if (csav == null) { + csav = new ResourceAuditVisitor(null, manager); + je = JavaCore.create(javaElement.getResource()); + } + + if (je instanceof ICompilationUnit) { + // get the type of the currently loaded resource + if (cu == null) { + ITypeRoot typeRoot = ((ICompilationUnit) je); + + if (typeRoot == null) + return null; + + cu = ASTutils.getCompilationUnit(typeRoot); + + cu.accept(csav); } - return completions; - } - - protected List<ICompletionProposal> getResourceBundleCompletionProposals ( - int offset, String stringLiteralStart, ResourceBundleManager manager, - ResourceAuditVisitor csav, IResource resource) { - List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); - IRegion region = csav.getKeyAt(new Long(offset)); - String bundleName = csav.getBundleReference(region); - int posStart = offset - stringLiteralStart.length(); - IMessagesBundleGroup bundleGroup = manager.getResourceBundle(bundleName); - - if (stringLiteralStart.length() > 0) { - boolean hit = false; - // If a part of a String has already been entered - for (String key : bundleGroup.getMessageKeys()) { - if (key.toLowerCase().startsWith(stringLiteralStart.toLowerCase())) { - if (!key.equals(stringLiteralStart)) - completions.add(new MessageCompletionProposal(posStart, - stringLiteralStart.length(), key, false)); - else - hit = true; - } - } - if (!hit) - completions.add(new NewResourceBundleEntryProposal(resource, offset - stringLiteralStart.length(), - true, manager, bundleName/*, csav.getDefinedResourceBundles(offset)*/)); + + // StringLiteralAnalyzer sla = new + // StringLiteralAnalyzer(javaElement.getResource()); + if (csav.getKeyAt(new Long(offset)) != null) { + completions.addAll(getResourceBundleCompletionProposals( + offset, stringLiteralStart, manager, csav, + javaElement.getResource())); + } else if (csav.getRBReferenceAt(new Long(offset)) != null) { + completions.addAll(getRBReferenceCompletionProposals( + offset, stringLiteralStart, manager, + je.getResource())); } else { - for (String key : bundleGroup.getMessageKeys()) { - completions.add (new MessageCompletionProposal (posStart, stringLiteralStart.length(), key, false)); - } - completions.add(new NewResourceBundleEntryProposal(resource, offset - stringLiteralStart.length(), - true, manager, bundleName/*, csav.getDefinedResourceBundles(offset)*/)); - + completions + .addAll(getBasicJavaCompletionProposals(offset, + stringLiteralStart, manager, csav, + je.getResource())); } - return completions; - } - - @Override - public List computeContextInformation( - ContentAssistInvocationContext context, IProgressMonitor monitor) { + if (completions.size() == 1) + completions.add(new NoActionProposal()); + } else return null; + } catch (Exception e) { + // e.printStackTrace(); } + return completions; + } + + private Collection<ICompletionProposal> getRBReferenceCompletionProposals( + int offset, String stringLiteralStart, + ResourceBundleManager manager, IResource resource) { + List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); + int posStart = offset - stringLiteralStart.length(); + boolean hit = false; - @Override - public String getErrorMessage() { - // TODO Auto-generated method stub - return ""; + // Show a list of available resource bundles + List<String> resourceBundles = manager.getResourceBundleIdentifiers(); + for (String rbName : resourceBundles) { + if (rbName.startsWith(stringLiteralStart)) { + if (rbName.equals(stringLiteralStart)) + hit = true; + else + completions.add(new MessageCompletionProposal(posStart, + stringLiteralStart.length(), rbName, true)); + } } - @Override - public void sessionEnded() { - csav = null; - javaElement = null; - cu = null; + if (!hit && stringLiteralStart.trim().length() > 0) + completions.add(new CreateResourceBundleProposal( + stringLiteralStart, resource, posStart, posStart + + stringLiteralStart.length())); + + return completions; + } + + protected List<ICompletionProposal> getBasicJavaCompletionProposals( + int offset, String stringLiteralStart, + ResourceBundleManager manager, ResourceAuditVisitor csav, + IResource resource) { + List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); + + if (stringLiteralStart.length() == 0) { + // If nothing has been entered + completions.add(new InsertResourceBundleReferenceProposal(offset + - stringLiteralStart.length(), stringLiteralStart.length(), + manager, resource, csav.getDefinedResourceBundles(offset))); + completions.add(new NewResourceBundleEntryProposal(resource, offset + - stringLiteralStart.length(), false, manager, null)); + } else { + completions.add(new NewResourceBundleEntryProposal(resource, offset + - stringLiteralStart.length(), false, manager, null)); } + return completions; + } + + protected List<ICompletionProposal> getResourceBundleCompletionProposals( + int offset, String stringLiteralStart, + ResourceBundleManager manager, ResourceAuditVisitor csav, + IResource resource) { + List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); + IRegion region = csav.getKeyAt(new Long(offset)); + String bundleName = csav.getBundleReference(region); + int posStart = offset - stringLiteralStart.length(); + IMessagesBundleGroup bundleGroup = manager + .getResourceBundle(bundleName); + + if (stringLiteralStart.length() > 0) { + boolean hit = false; + // If a part of a String has already been entered + for (String key : bundleGroup.getMessageKeys()) { + if (key.toLowerCase().startsWith( + stringLiteralStart.toLowerCase())) { + if (!key.equals(stringLiteralStart)) + completions.add(new MessageCompletionProposal(posStart, + stringLiteralStart.length(), key, false)); + else + hit = true; + } + } + if (!hit) + completions.add(new NewResourceBundleEntryProposal(resource, + offset - stringLiteralStart.length(), true, manager, + bundleName/* + * , csav.getDefinedResourceBundles (offset) + */)); + } else { + for (String key : bundleGroup.getMessageKeys()) { + completions.add(new MessageCompletionProposal(posStart, + stringLiteralStart.length(), key, false)); + } + completions + .add(new NewResourceBundleEntryProposal(resource, offset + - stringLiteralStart.length(), true, manager, + bundleName/* + * , + * csav.getDefinedResourceBundles(offset) + */)); - @Override - public void sessionStarted() { } + return completions; + } + + @Override + public List computeContextInformation( + ContentAssistInvocationContext context, IProgressMonitor monitor) { + return null; + } + + @Override + public String getErrorMessage() { + // TODO Auto-generated method stub + return ""; + } + + @Override + public void sessionEnded() { + csav = null; + javaElement = null; + cu = null; + } + + @Override + public void sessionStarted() { + } } diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java index 7c5ab0ec..77a2f4a0 100644 --- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java +++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java @@ -6,36 +6,35 @@ public class Sorter extends AbstractProposalSorter { - private boolean loaded = false; - - public Sorter () { - // i18n - loaded = true; - } - - @Override - public void beginSorting(ContentAssistInvocationContext context) { - // TODO Auto-generated method stub - super.beginSorting(context); - } - - @Override - public int compare(ICompletionProposal prop1, ICompletionProposal prop2) { - return getIndex (prop1) - getIndex (prop2); - } - - protected int getIndex (ICompletionProposal prop) { - if (prop instanceof NoActionProposal) - return 1; - else if (prop instanceof MessageCompletionProposal) - return 2; - else if (prop instanceof ValueOfResourceBundleProposal) - return 3; - else if (prop instanceof InsertResourceBundleReferenceProposal) - return 4; - else if (prop instanceof NewResourceBundleEntryProposal) - return 5; - else return 0; - } - + private boolean loaded = false; + + public Sorter() { + // i18n + loaded = true; + } + + @Override + public void beginSorting(ContentAssistInvocationContext context) { + // TODO Auto-generated method stub + super.beginSorting(context); + } + + @Override + public int compare(ICompletionProposal prop1, ICompletionProposal prop2) { + return getIndex(prop1) - getIndex(prop2); + } + + protected int getIndex(ICompletionProposal prop) { + if (prop instanceof NoActionProposal) + return 1; + else if (prop instanceof MessageCompletionProposal) + return 2; + else if (prop instanceof InsertResourceBundleReferenceProposal) + return 3; + else if (prop instanceof NewResourceBundleEntryProposal) + return 4; + else + return 0; + } + } diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/ValueOfResourceBundleProposal.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/ValueOfResourceBundleProposal.java deleted file mode 100644 index 8ce210d0..00000000 --- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/ValueOfResourceBundleProposal.java +++ /dev/null @@ -1,71 +0,0 @@ -package org.eclipse.babel.tapiji.tools.java.ui.autocompletion; - -import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.contentassist.IContextInformation; -import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; - -public class ValueOfResourceBundleProposal implements IJavaCompletionProposal { - - private int offset = 0; - private int length = 0; - private String content = ""; - private String matchingString = ""; - - public ValueOfResourceBundleProposal (int offset, int length, String content, String matchingString) { - this.offset = offset; - this.length = length; - this.content = content; - this.matchingString = matchingString; - } - - @Override - public void apply(IDocument document) { - try { - String inplaceContent = "myResources.getString(\"" + content + "\")"; - // TODO prüfe öffnende und schließende klammern - document.replace(offset-1, length+2, inplaceContent); - } catch (Exception e) { - e.printStackTrace(); - } - } - - - @Override - public String getAdditionalProposalInfo() { - // TODO Auto-generated method stub - return null; - } - - @Override - public IContextInformation getContextInformation() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getDisplayString() { - // TODO Auto-generated method stub - return "Insert localized reference to '" + matchingString + "'"; - } - - @Override - public Image getImage() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Point getSelection(IDocument document) { - // TODO Auto-generated method stub - return null; - } - - @Override - public int getRelevance() { - // TODO Auto-generated method stub - return 98; - } - -}
ced5a6c917416088d9def359edacf548509677f3
kotlin
Introduce RenderingContext and add as parameter- to DiagnosticParameterRenderer-render--RenderingContext holds data about the whole diagnostics allowing to adjust rendering of its parameters-
a
https://github.com/JetBrains/kotlin
diff --git a/compiler/frontend.java/src/org/jetbrains/kotlin/resolve/jvm/diagnostics/DefaultErrorMessagesJvm.java b/compiler/frontend.java/src/org/jetbrains/kotlin/resolve/jvm/diagnostics/DefaultErrorMessagesJvm.java index 8b059e3b5a9d7..50cd881fa597a 100644 --- a/compiler/frontend.java/src/org/jetbrains/kotlin/resolve/jvm/diagnostics/DefaultErrorMessagesJvm.java +++ b/compiler/frontend.java/src/org/jetbrains/kotlin/resolve/jvm/diagnostics/DefaultErrorMessagesJvm.java @@ -18,10 +18,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.kotlin.descriptors.DeclarationDescriptor; -import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages; -import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticFactoryToRendererMap; -import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticParameterRenderer; -import org.jetbrains.kotlin.diagnostics.rendering.Renderers; +import org.jetbrains.kotlin.diagnostics.rendering.*; import org.jetbrains.kotlin.renderer.DescriptorRenderer; import java.util.ArrayList; @@ -33,7 +30,7 @@ public class DefaultErrorMessagesJvm implements DefaultErrorMessages.Extension { private static final DiagnosticParameterRenderer<ConflictingJvmDeclarationsData> CONFLICTING_JVM_DECLARATIONS_DATA = new DiagnosticParameterRenderer<ConflictingJvmDeclarationsData>() { @NotNull @Override - public String render(@NotNull ConflictingJvmDeclarationsData data) { + public String render(@NotNull ConflictingJvmDeclarationsData data, @NotNull RenderingContext context) { List<String> renderedDescriptors = new ArrayList<String>(); for (JvmDeclarationOrigin origin : data.getSignatureOrigins()) { DeclarationDescriptor descriptor = origin.getDescriptor(); diff --git a/compiler/frontend/src/org/jetbrains/kotlin/checkers/CheckerTestUtil.java b/compiler/frontend/src/org/jetbrains/kotlin/checkers/CheckerTestUtil.java index 19d39f1d56d68..81df046e67e25 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/checkers/CheckerTestUtil.java +++ b/compiler/frontend/src/org/jetbrains/kotlin/checkers/CheckerTestUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. + * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java index 32f27ead4afa9..6482a9375f565 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java +++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. + * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,6 +41,7 @@ import static org.jetbrains.kotlin.diagnostics.Errors.*; import static org.jetbrains.kotlin.diagnostics.rendering.Renderers.*; +import static org.jetbrains.kotlin.diagnostics.rendering.RenderingContext.*; public class DefaultErrorMessages { @@ -118,11 +119,13 @@ public static DiagnosticRenderer getRendererForDiagnostic(@NotNull Diagnostic di @NotNull @Override public String[] render(@NotNull TypeMismatchDueToTypeProjectionsData object) { + RenderingContext context = + of(object.getExpectedType(), object.getExpressionType(), object.getReceiverType(), object.getCallableDescriptor()); return new String[] { - RENDER_TYPE.render(object.getExpectedType()), - RENDER_TYPE.render(object.getExpressionType()), - RENDER_TYPE.render(object.getReceiverType()), - DescriptorRenderer.FQ_NAMES_IN_TYPES.render(object.getCallableDescriptor()) + RENDER_TYPE.render(object.getExpectedType(), context), + RENDER_TYPE.render(object.getExpressionType(), context), + RENDER_TYPE.render(object.getReceiverType(), context), + FQ_NAMES_IN_TYPES.render(object.getCallableDescriptor(), context) }; } }); @@ -175,7 +178,7 @@ public String[] render(@NotNull TypeMismatchDueToTypeProjectionsData object) { MAP.put(NAMED_ARGUMENTS_NOT_ALLOWED, "Named arguments are not allowed for {0}", new DiagnosticParameterRenderer<BadNamedArgumentsTarget>() { @NotNull @Override - public String render(@NotNull BadNamedArgumentsTarget target) { + public String render(@NotNull BadNamedArgumentsTarget target, @NotNull RenderingContext context) { switch (target) { case NON_KOTLIN_FUNCTION: return "non-Kotlin functions"; @@ -391,7 +394,7 @@ public String render(@NotNull BadNamedArgumentsTarget target) { MAP.put(EXPRESSION_EXPECTED, "{0} is not an expression, and only expressions are allowed here", new DiagnosticParameterRenderer<KtExpression>() { @NotNull @Override - public String render(@NotNull KtExpression expression) { + public String render(@NotNull KtExpression expression, @NotNull RenderingContext context) { String expressionType = expression.toString(); return expressionType.substring(0, 1) + expressionType.substring(1).toLowerCase(); @@ -487,7 +490,7 @@ public String render(@NotNull KtExpression expression) { MAP.put(NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER, "{0} does not refer to a type parameter of {1}", new DiagnosticParameterRenderer<KtTypeConstraint>() { @NotNull @Override - public String render(@NotNull KtTypeConstraint typeConstraint) { + public String render(@NotNull KtTypeConstraint typeConstraint, @NotNull RenderingContext context) { //noinspection ConstantConditions return typeConstraint.getSubjectTypeParameterName().getReferencedName(); } @@ -509,11 +512,13 @@ public String render(@NotNull KtTypeConstraint typeConstraint) { @NotNull @Override public String[] render(@NotNull VarianceConflictDiagnosticData data) { + RenderingContext context = + of(data.getTypeParameter(), data.getTypeParameter().getVariance(), data.getOccurrencePosition(), data.getContainingType()); return new String[] { - NAME.render(data.getTypeParameter()), - RENDER_POSITION_VARIANCE.render(data.getTypeParameter().getVariance()), - RENDER_POSITION_VARIANCE.render(data.getOccurrencePosition()), - RENDER_TYPE.render(data.getContainingType()) + NAME.render(data.getTypeParameter(), context), + RENDER_POSITION_VARIANCE.render(data.getTypeParameter().getVariance(), context), + RENDER_POSITION_VARIANCE.render(data.getOccurrencePosition(), context), + RENDER_TYPE.render(data.getContainingType(), context) }; } }); @@ -548,7 +553,7 @@ public String[] render(@NotNull VarianceConflictDiagnosticData data) { MAP.put(EQUALITY_NOT_APPLICABLE, "Operator ''{0}'' cannot be applied to ''{1}'' and ''{2}''", new DiagnosticParameterRenderer<KtSimpleNameExpression>() { @NotNull @Override - public String render(@NotNull KtSimpleNameExpression nameExpression) { + public String render(@NotNull KtSimpleNameExpression nameExpression, @NotNull RenderingContext context) { //noinspection ConstantConditions return nameExpression.getReferencedName(); } @@ -603,15 +608,15 @@ public String render(@NotNull KtSimpleNameExpression nameExpression) { ELEMENT_TEXT, new DiagnosticParameterRenderer<KotlinType>() { @NotNull @Override - public String render(@NotNull KotlinType type) { + public String render(@NotNull KotlinType type, @NotNull RenderingContext context) { if (type.isError()) return ""; - return " of type '" + RENDER_TYPE.render(type) + "'"; + return " of type '" + RENDER_TYPE.render(type, context) + "'"; } }); MAP.put(FUNCTION_CALL_EXPECTED, "Function invocation ''{0}({1})'' expected", ELEMENT_TEXT, new DiagnosticParameterRenderer<Boolean>() { @NotNull @Override - public String render(@NotNull Boolean hasValueParameters) { + public String render(@NotNull Boolean hasValueParameters, @NotNull RenderingContext context) { return hasValueParameters ? "..." : ""; } }); diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DiagnosticParameterRenderer.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DiagnosticParameterRenderer.kt index 5efb23fcc284b..1d445f643ca9e 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DiagnosticParameterRenderer.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DiagnosticParameterRenderer.kt @@ -17,9 +17,13 @@ package org.jetbrains.kotlin.diagnostics.rendering interface DiagnosticParameterRenderer<in O> { - fun render(obj: O): String + fun render(obj: O, renderingContext: RenderingContext): String } fun <O> Renderer(block: (O) -> String) = object : DiagnosticParameterRenderer<O> { - override fun render(obj: O) = block(obj) + override fun render(obj: O, renderingContext: RenderingContext): String = block(obj) +} + +fun <O> ContextDependentRenderer(block: (O, RenderingContext) -> String) = object : DiagnosticParameterRenderer<O> { + override fun render(obj: O, renderingContext: RenderingContext): String = block(obj, renderingContext) } \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DiagnosticRendererUtil.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DiagnosticRendererUtil.kt index 644df659948e5..34a20f8d8ebc0 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DiagnosticRendererUtil.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DiagnosticRendererUtil.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. + * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,8 @@ package org.jetbrains.kotlin.diagnostics.rendering import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.renderer.DescriptorRenderer -fun <P : Any> renderParameter(parameter: P, renderer: DiagnosticParameterRenderer<P>?): Any = renderer?.render(parameter) ?: parameter +fun <P : Any> renderParameter(parameter: P, renderer: DiagnosticParameterRenderer<P>?, context: RenderingContext): Any + = renderer?.render(parameter, context) ?: parameter fun ClassDescriptor.renderKindWithName(): String = DescriptorRenderer.getClassKindPrefix(this) + " '" + name + "'" diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/Renderers.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/Renderers.kt index 1703a62e53737..8bfd10ad4e0a1 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/Renderers.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/Renderers.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. + * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -122,19 +122,20 @@ object Renderers { @JvmField val AMBIGUOUS_CALLS = Renderer { calls: Collection<ResolvedCall<*>> -> - calls - .map { it.resultingDescriptor } + val descriptors = calls.map { it.resultingDescriptor } + val context = RenderingContext.Impl(descriptors) + descriptors .sortedWith(MemberComparator.INSTANCE) - .joinToString(separator = "\n", prefix = "\n") { DescriptorRenderer.FQ_NAMES_IN_TYPES.render(it) } + .joinToString(separator = "\n", prefix = "\n") { FQ_NAMES_IN_TYPES.render(it, context) } } - @JvmStatic fun <T> commaSeparated(itemRenderer: DiagnosticParameterRenderer<T>) = Renderer<Collection<T>> { - collection -> + @JvmStatic fun <T> commaSeparated(itemRenderer: DiagnosticParameterRenderer<T>) = ContextDependentRenderer<Collection<T>> { + collection, context -> buildString { val iterator = collection.iterator() while (iterator.hasNext()) { val next = iterator.next() - append(itemRenderer.render(next)) + append(itemRenderer.render(next, context)) if (iterator.hasNext()) { append(", ") } @@ -166,7 +167,7 @@ object Renderers { inferenceErrorData: InferenceErrorData, result: TabledDescriptorRenderer ): TabledDescriptorRenderer { LOG.assertTrue(inferenceErrorData.constraintSystem.status.hasConflictingConstraints(), - renderDebugMessage("Conflicting substitutions inference error renderer is applied for incorrect status", inferenceErrorData)) + debugMessage("Conflicting substitutions inference error renderer is applied for incorrect status", inferenceErrorData)) val substitutedDescriptors = Lists.newArrayList<CallableDescriptor>() val substitutors = ConstraintsUtil.getSubstitutorsForConflictingParameters(inferenceErrorData.constraintSystem) @@ -177,7 +178,7 @@ object Renderers { val firstConflictingVariable = ConstraintsUtil.getFirstConflictingVariable(inferenceErrorData.constraintSystem) if (firstConflictingVariable == null) { - LOG.error(renderDebugMessage("There is no conflicting parameter for 'conflicting constraints' error.", inferenceErrorData)) + LOG.error(debugMessage("There is no conflicting parameter for 'conflicting constraints' error.", inferenceErrorData)) return result } @@ -238,7 +239,7 @@ object Renderers { val firstUnknownVariable = inferenceErrorData.constraintSystem.typeVariables.firstOrNull { variable -> inferenceErrorData.constraintSystem.getTypeBounds(variable).values.isEmpty() } ?: return result.apply { - LOG.error(renderDebugMessage("There is no unknown parameter for 'no information for parameter error'.", inferenceErrorData)) + LOG.error(debugMessage("There is no unknown parameter for 'no information for parameter error'.", inferenceErrorData)) } return result @@ -256,7 +257,7 @@ object Renderers { val constraintSystem = inferenceErrorData.constraintSystem val status = constraintSystem.status LOG.assertTrue(status.hasViolatedUpperBound(), - renderDebugMessage("Upper bound violated renderer is applied for incorrect status", inferenceErrorData)) + debugMessage("Upper bound violated renderer is applied for incorrect status", inferenceErrorData)) val systemWithoutWeakConstraints = constraintSystem.filterConstraintsOut(ConstraintPositionKind.TYPE_BOUND_POSITION) val typeParameterDescriptor = inferenceErrorData.descriptor.typeParameters.firstOrNull { @@ -266,15 +267,15 @@ object Renderers { return renderConflictingSubstitutionsInferenceError(inferenceErrorData, result) } if (typeParameterDescriptor == null) { - LOG.error(renderDebugMessage("There is no type parameter with violated upper bound for 'upper bound violated' error", inferenceErrorData)) + LOG.error(debugMessage("There is no type parameter with violated upper bound for 'upper bound violated' error", inferenceErrorData)) return result } val typeVariable = systemWithoutWeakConstraints.descriptorToVariable(inferenceErrorData.call.toHandle(), typeParameterDescriptor) val inferredValueForTypeParameter = systemWithoutWeakConstraints.getTypeBounds(typeVariable).value if (inferredValueForTypeParameter == null) { - LOG.error(renderDebugMessage("System without weak constraints is not successful, there is no value for type parameter " + - typeParameterDescriptor.name + "\n: " + systemWithoutWeakConstraints, inferenceErrorData)) + LOG.error(debugMessage("System without weak constraints is not successful, there is no value for type parameter " + + typeParameterDescriptor.name + "\n: " + systemWithoutWeakConstraints, inferenceErrorData)) return result } @@ -295,17 +296,19 @@ object Renderers { } } if (violatedUpperBound == null) { - LOG.error(renderDebugMessage("Type parameter (chosen as violating its upper bound)" + - typeParameterDescriptor.name + " violates no bounds after substitution", inferenceErrorData)) + LOG.error(debugMessage("Type parameter (chosen as violating its upper bound)" + + typeParameterDescriptor.name + " violates no bounds after substitution", inferenceErrorData)) return result } + // TODO: context should be in fact shared for the table and these two types + val context = RenderingContext.of(inferredValueForTypeParameter, violatedUpperBound) val typeRenderer = result.typeRenderer result.text(newText() .normal(" is not satisfied: inferred type ") - .error(typeRenderer.render(inferredValueForTypeParameter)) + .error(typeRenderer.render(inferredValueForTypeParameter, context)) .normal(" is not a subtype of ") - .strong(typeRenderer.render(violatedUpperBound))) + .strong(typeRenderer.render(violatedUpperBound, context))) return result } @@ -316,7 +319,7 @@ object Renderers { val errors = system.status.constraintErrors val typeVariableWithCapturedConstraint = errors.firstIsInstanceOrNull<CannotCapture>()?.typeVariable if (typeVariableWithCapturedConstraint == null) { - LOG.error(renderDebugMessage("An error 'cannot capture type parameter' is not found in errors", inferenceErrorData)) + LOG.error(debugMessage("An error 'cannot capture type parameter' is not found in errors", inferenceErrorData)) return result } @@ -324,7 +327,7 @@ object Renderers { val boundWithCapturedType = typeBounds.bounds.firstOrNull { it.constrainingType.isCaptured() } val capturedTypeConstructor = boundWithCapturedType?.constrainingType?.constructor as? CapturedTypeConstructor if (capturedTypeConstructor == null) { - LOG.error(renderDebugMessage("There is no captured type in bounds, but there is an error 'cannot capture type parameter'", inferenceErrorData)) + LOG.error(debugMessage("There is no captured type in bounds, but there is an error 'cannot capture type parameter'", inferenceErrorData)) return result } @@ -333,7 +336,7 @@ object Renderers { val explanation: String val upperBound = TypeIntersector.getUpperBoundsAsType(typeParameter) if (!KotlinBuiltIns.isNullableAny(upperBound) && capturedTypeConstructor.typeProjection.projectionKind == Variance.IN_VARIANCE) { - explanation = "Type parameter has an upper bound '" + result.typeRenderer.render(upperBound) + "'" + + explanation = "Type parameter has an upper bound '" + result.typeRenderer.render(upperBound, RenderingContext.of(upperBound)) + "'" + " that cannot be satisfied capturing 'in' projection" } else { @@ -365,24 +368,20 @@ object Renderers { } } - private fun renderTypes(types: Collection<KotlinType>) = StringUtil.join(types, { RENDER_TYPE.render(it) }, ", ") + private fun renderTypes(types: Collection<KotlinType>, context: RenderingContext) = StringUtil.join(types, { RENDER_TYPE.render(it, context) }, ", ") - @JvmField val RENDER_COLLECTION_OF_TYPES = Renderer<Collection<KotlinType>> { renderTypes(it) } + @JvmField val RENDER_COLLECTION_OF_TYPES = ContextDependentRenderer<Collection<KotlinType>> { types, context -> renderTypes(types, context) } - private fun renderConstraintSystem(constraintSystem: ConstraintSystem, renderTypeBounds: DiagnosticParameterRenderer<TypeBounds>): String { + fun renderConstraintSystem(constraintSystem: ConstraintSystem, shortTypeBounds: Boolean): String { val typeBounds = linkedSetOf<TypeBounds>() for (variable in constraintSystem.typeVariables) { typeBounds.add(constraintSystem.getTypeBounds(variable)) } return "type parameter bounds:\n" + - StringUtil.join(typeBounds, { renderTypeBounds.render(it) }, "\n") + "\n\n" + "status:\n" + + StringUtil.join(typeBounds, { renderTypeBounds(it, short = shortTypeBounds) }, "\n") + "\n\n" + "status:\n" + ConstraintsUtil.getDebugMessageForStatus(constraintSystem.status) } - @JvmField val RENDER_CONSTRAINT_SYSTEM = Renderer<ConstraintSystem> { renderConstraintSystem(it, RENDER_TYPE_BOUNDS) } - - @JvmField val RENDER_CONSTRAINT_SYSTEM_SHORT = Renderer<ConstraintSystem> { renderConstraintSystem(it, RENDER_TYPE_BOUNDS_SHORT) } - private fun renderTypeBounds(typeBounds: TypeBounds, short: Boolean): String { val renderBound = { bound: Bound -> val arrow = if (bound.kind == LOWER_BOUND) ">: " else if (bound.kind == UPPER_BOUND) "<: " else ":= " @@ -398,28 +397,25 @@ object Renderers { "$typeVariableName ${StringUtil.join(typeBounds.bounds, renderBound, ", ")}" } - @JvmField val RENDER_TYPE_BOUNDS = Renderer<TypeBounds> { renderTypeBounds(it, short = false) } - - @JvmField val RENDER_TYPE_BOUNDS_SHORT = Renderer<TypeBounds> { renderTypeBounds(it, short = true) } - - private fun renderDebugMessage(message: String, inferenceErrorData: InferenceErrorData) = buildString { + private fun debugMessage(message: String, inferenceErrorData: InferenceErrorData) = buildString { append(message) append("\nConstraint system: \n") - append(RENDER_CONSTRAINT_SYSTEM.render(inferenceErrorData.constraintSystem)) + append(renderConstraintSystem(inferenceErrorData.constraintSystem, false)) append("\nDescriptor:\n") append(inferenceErrorData.descriptor) append("\nExpected type:\n") + val context = RenderingContext.Empty if (TypeUtils.noExpectedType(inferenceErrorData.expectedType)) { append(inferenceErrorData.expectedType) } else { - append(RENDER_TYPE.render(inferenceErrorData.expectedType)) + append(RENDER_TYPE.render(inferenceErrorData.expectedType, context)) } append("\nArgument types:\n") if (inferenceErrorData.receiverArgumentType != null) { - append(RENDER_TYPE.render(inferenceErrorData.receiverArgumentType)).append(".") + append(RENDER_TYPE.render(inferenceErrorData.receiverArgumentType, context)).append(".") } - append("(").append(renderTypes(inferenceErrorData.valueArgumentsTypes)).append(")") + append("(").append(renderTypes(inferenceErrorData.valueArgumentsTypes, context)).append(")") } private val WHEN_MISSING_LIMIT = 7 @@ -448,4 +444,4 @@ object Renderers { fun DescriptorRenderer.asRenderer() = Renderer<DeclarationDescriptor> { render(it) -} \ No newline at end of file +} diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/RenderingContext.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/RenderingContext.kt new file mode 100644 index 0000000000000..0c2c56b5e2587 --- /dev/null +++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/RenderingContext.kt @@ -0,0 +1,68 @@ +/* + * Copyright 2010-2016 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.kotlin.diagnostics.rendering + +import org.jetbrains.kotlin.diagnostics.* + +// holds data about the parameters of the diagnostic we're about to render +sealed class RenderingContext { + abstract operator fun <T> get(key: Key<T>): T + + abstract class Key<T>(val name: String) { + abstract fun compute(objectsToRender: Collection<Any?>): T + } + + class Impl(private val objectsToRender: Collection<Any?>) : RenderingContext() { + private val data = linkedMapOf<Key<*>, Any?>() + + override fun <T> get(key: Key<T>): T { + if (!data.containsKey(key)) { + val result = key.compute(objectsToRender) + data[key] = result + return result + } + return data[key] as T + } + } + + + object Empty : RenderingContext() { + override fun <T> get(key: Key<T>): T { + return key.compute(emptyList()) + } + } + + companion object { + @JvmStatic + fun of(vararg objectsToRender: Any?): RenderingContext { + return Impl(objectsToRender.toList()) + } + + @JvmStatic + fun fromDiagnostic(d: Diagnostic): RenderingContext { + val parameters = when (d) { + is SimpleDiagnostic<*> -> listOf() + is DiagnosticWithParameters1<*, *> -> listOf(d.a) + is DiagnosticWithParameters2<*, *, *> -> listOf(d.a, d.b) + is DiagnosticWithParameters3<*, *, *, *> -> listOf(d.a, d.b, d.c) + is ParametrizedDiagnostic<*> -> error("Unexpected diagnostic: ${d.javaClass}") + else -> listOf() + } + return Impl(parameters) + } + } +} \ No newline at end of file diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/TabledDescriptorRenderer.java b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/TabledDescriptorRenderer.java index f9677583991b4..05e5c1eb89639 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/TabledDescriptorRenderer.java +++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/TabledDescriptorRenderer.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. + * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,10 +26,10 @@ import org.jetbrains.kotlin.diagnostics.rendering.TabledDescriptorRenderer.TableRenderer.FunctionArgumentsRow; import org.jetbrains.kotlin.diagnostics.rendering.TabledDescriptorRenderer.TableRenderer.TableRow; import org.jetbrains.kotlin.diagnostics.rendering.TabledDescriptorRenderer.TextRenderer.TextElement; -import org.jetbrains.kotlin.renderer.DescriptorRenderer; import org.jetbrains.kotlin.resolve.calls.inference.constraintPosition.ConstraintPosition; import org.jetbrains.kotlin.types.KotlinType; +import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -167,26 +167,33 @@ protected void renderText(TextRenderer textRenderer, StringBuilder result) { protected void renderTable(TableRenderer table, StringBuilder result) { if (table.rows.isEmpty()) return; + + RenderingContext context = computeRenderingContext(table); for (TableRow row : table.rows) { if (row instanceof TextRenderer) { renderText((TextRenderer) row, result); } if (row instanceof DescriptorRow) { - result.append(DescriptorRenderer.COMPACT.render(((DescriptorRow) row).descriptor)); + result.append(Renderers.COMPACT.render(((DescriptorRow) row).descriptor, context)); } if (row instanceof FunctionArgumentsRow) { FunctionArgumentsRow functionArgumentsRow = (FunctionArgumentsRow) row; - renderFunctionArguments(functionArgumentsRow.receiverType, functionArgumentsRow.argumentTypes, result); + renderFunctionArguments(functionArgumentsRow.receiverType, functionArgumentsRow.argumentTypes, result, context); } result.append("\n"); } } - private void renderFunctionArguments(@Nullable KotlinType receiverType, @NotNull List<KotlinType> argumentTypes, StringBuilder result) { + private void renderFunctionArguments( + @Nullable KotlinType receiverType, + @NotNull List<KotlinType> argumentTypes, + StringBuilder result, + @NotNull RenderingContext context + ) { boolean hasReceiver = receiverType != null; if (hasReceiver) { result.append("receiver: "); - result.append(getTypeRenderer().render(receiverType)); + result.append(getTypeRenderer().render(receiverType, context)); result.append(" arguments: "); } if (argumentTypes.isEmpty()) { @@ -197,7 +204,7 @@ private void renderFunctionArguments(@Nullable KotlinType receiverType, @NotNull result.append("("); for (Iterator<KotlinType> iterator = argumentTypes.iterator(); iterator.hasNext(); ) { KotlinType argumentType = iterator.next(); - String renderedArgument = getTypeRenderer().render(argumentType); + String renderedArgument = getTypeRenderer().render(argumentType, context); result.append(renderedArgument); if (iterator.hasNext()) { @@ -212,4 +219,25 @@ public static TabledDescriptorRenderer create() { } public static enum TextElementType { STRONG, ERROR, DEFAULT } + + @NotNull + protected static RenderingContext computeRenderingContext(@NotNull TableRenderer table) { + ArrayList<Object> toRender = new ArrayList<Object>(); + for (TableRow row : table.rows) { + if (row instanceof DescriptorRow) { + toRender.add(((DescriptorRow) row).descriptor); + } + else if (row instanceof FunctionArgumentsRow) { + toRender.add(((FunctionArgumentsRow) row).receiverType); + toRender.addAll(((FunctionArgumentsRow) row).argumentTypes); + } + else if (row instanceof TextRenderer) { + + } + else { + throw new AssertionError("Unknown row of type " + row.getClass()); + } + } + return new RenderingContext.Impl(toRender); + } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/diagnosticsWithParameterRenderers.kt b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/diagnosticsWithParameterRenderers.kt index 42b567ed62c05..7aeccb372812d 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/diagnosticsWithParameterRenderers.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/diagnosticsWithParameterRenderers.kt @@ -42,10 +42,9 @@ class DiagnosticWithParameters1Renderer<A : Any>( ) : AbstractDiagnosticWithParametersRenderer<DiagnosticWithParameters1<*, A>>(message) { override fun renderParameters(diagnostic: DiagnosticWithParameters1<*, A>): Array<out Any> { - return arrayOf(renderParameter(diagnostic.a, rendererForA)) + val context = RenderingContext.of(diagnostic.a) + return arrayOf(renderParameter(diagnostic.a, rendererForA, context)) } - - } class DiagnosticWithParameters2Renderer<A : Any, B : Any>( @@ -55,9 +54,10 @@ class DiagnosticWithParameters2Renderer<A : Any, B : Any>( ) : AbstractDiagnosticWithParametersRenderer<DiagnosticWithParameters2<*, A, B>>(message) { override fun renderParameters(diagnostic: DiagnosticWithParameters2<*, A, B>): Array<out Any> { + val context = RenderingContext.of(diagnostic.a, diagnostic.b) return arrayOf( - renderParameter(diagnostic.a, rendererForA), - renderParameter(diagnostic.b, rendererForB) + renderParameter(diagnostic.a, rendererForA, context), + renderParameter(diagnostic.b, rendererForB, context) ) } } @@ -70,10 +70,11 @@ class DiagnosticWithParameters3Renderer<A : Any, B : Any, C : Any>( ) : AbstractDiagnosticWithParametersRenderer<DiagnosticWithParameters3<*, A, B, C>>(message) { override fun renderParameters(diagnostic: DiagnosticWithParameters3<*, A, B, C>): Array<out Any> { + val context = RenderingContext.of(diagnostic.a, diagnostic.b, diagnostic.c) return arrayOf( - renderParameter(diagnostic.a, rendererForA), - renderParameter(diagnostic.b, rendererForB), - renderParameter(diagnostic.c, rendererForC) + renderParameter(diagnostic.a, rendererForA, context), + renderParameter(diagnostic.b, rendererForB, context), + renderParameter(diagnostic.c, rendererForC, context) ) } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatedPropertyResolver.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatedPropertyResolver.java index b297cd15d34a0..5e8c2620c996c 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatedPropertyResolver.java +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/DelegatedPropertyResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. + * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,15 +17,17 @@ package org.jetbrains.kotlin.resolve; import com.google.common.collect.Lists; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; +import com.intellij.util.Function; import kotlin.Pair; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.kotlin.builtins.KotlinBuiltIns; import org.jetbrains.kotlin.descriptors.*; -import org.jetbrains.kotlin.diagnostics.rendering.Renderers; import org.jetbrains.kotlin.name.Name; import org.jetbrains.kotlin.psi.*; +import org.jetbrains.kotlin.renderer.DescriptorRenderer; import org.jetbrains.kotlin.resolve.calls.callUtil.CallUtilKt; import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystem; import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystemCompleter; @@ -34,8 +36,8 @@ import org.jetbrains.kotlin.resolve.calls.results.OverloadResolutionResults; import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo; import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfoFactory; -import org.jetbrains.kotlin.resolve.scopes.ScopeUtils; import org.jetbrains.kotlin.resolve.scopes.LexicalScope; +import org.jetbrains.kotlin.resolve.scopes.ScopeUtils; import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver; import org.jetbrains.kotlin.resolve.validation.OperatorValidator; import org.jetbrains.kotlin.resolve.validation.SymbolUsageValidator; @@ -308,7 +310,13 @@ private static String renderCall(@NotNull Call call, @NotNull BindingContext con argumentTypes.add(context.getType(argument.getArgumentExpression())); } - builder.append(Renderers.RENDER_COLLECTION_OF_TYPES.render(argumentTypes)); + String arguments = StringUtil.join(argumentTypes, new Function<KotlinType, String>() { + @Override + public String fun(KotlinType type) { + return DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(type); + } + }, ", "); + builder.append(arguments); builder.append(")"); return builder.toString(); } diff --git a/compiler/tests/org/jetbrains/kotlin/resolve/constraintSystem/AbstractConstraintSystemTest.kt b/compiler/tests/org/jetbrains/kotlin/resolve/constraintSystem/AbstractConstraintSystemTest.kt index 53f7dcdac837a..245a6245b83d0 100644 --- a/compiler/tests/org/jetbrains/kotlin/resolve/constraintSystem/AbstractConstraintSystemTest.kt +++ b/compiler/tests/org/jetbrains/kotlin/resolve/constraintSystem/AbstractConstraintSystemTest.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. + * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -110,7 +110,7 @@ abstract class AbstractConstraintSystemTest() : KotlinLiteFixture() { val system = builder.build() - val resultingStatus = Renderers.RENDER_CONSTRAINT_SYSTEM_SHORT.render(system) + val resultingStatus = Renderers.renderConstraintSystem(system, shortTypeBounds = true) val resultingSubstitutor = system.resultingSubstitutor val result = typeParameterDescriptors.map { diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/HtmlTabledDescriptorRenderer.java b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/HtmlTabledDescriptorRenderer.java index 1681670d7e11c..737fb172390ec 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/HtmlTabledDescriptorRenderer.java +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/HtmlTabledDescriptorRenderer.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. + * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import org.jetbrains.annotations.Nullable; import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor; import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticParameterRenderer; +import org.jetbrains.kotlin.diagnostics.rendering.RenderingContext; import org.jetbrains.kotlin.diagnostics.rendering.TabledDescriptorRenderer; import org.jetbrains.kotlin.diagnostics.rendering.TabledDescriptorRenderer.TableRenderer.DescriptorRow; import org.jetbrains.kotlin.diagnostics.rendering.TabledDescriptorRenderer.TableRenderer.FunctionArgumentsRow; @@ -94,9 +95,10 @@ else if (row instanceof FunctionArgumentsRow) { @Override protected void renderTable(TableRenderer table, StringBuilder result) { if (table.rows.isEmpty()) return; - int rowsNumber = countColumnNumber(table); + RenderingContext context = computeRenderingContext(table); + int rowsNumber = countColumnNumber(table); result.append("<table>"); for (TableRow row : table.rows) { result.append("<tr>"); @@ -111,7 +113,7 @@ protected void renderTable(TableRenderer table, StringBuilder result) { } if (row instanceof FunctionArgumentsRow) { FunctionArgumentsRow functionArgumentsRow = (FunctionArgumentsRow) row; - renderFunctionArguments(functionArgumentsRow.receiverType, functionArgumentsRow.argumentTypes, functionArgumentsRow.isErrorPosition, result); + renderFunctionArguments(functionArgumentsRow.receiverType, functionArgumentsRow.argumentTypes, functionArgumentsRow.isErrorPosition, result, context); } result.append("</tr>"); } @@ -124,7 +126,8 @@ private void renderFunctionArguments( @Nullable KotlinType receiverType, @NotNull List<KotlinType> argumentTypes, Predicate<ConstraintPosition> isErrorPosition, - StringBuilder result + StringBuilder result, + @NotNull RenderingContext context ) { boolean hasReceiver = receiverType != null; tdSpace(result); @@ -134,7 +137,7 @@ private void renderFunctionArguments( if (isErrorPosition.apply(RECEIVER_POSITION.position())) { error = true; } - receiver = "receiver: " + RenderersUtilKt.renderStrong(getTypeRenderer().render(receiverType), error); + receiver = "receiver: " + RenderersUtilKt.renderStrong(getTypeRenderer().render(receiverType, context), error); } td(result, receiver); td(result, hasReceiver ? "arguments: " : ""); @@ -151,7 +154,7 @@ private void renderFunctionArguments( if (isErrorPosition.apply(VALUE_PARAMETER_POSITION.position(i))) { error = true; } - String renderedArgument = getTypeRenderer().render(argumentType); + String renderedArgument = getTypeRenderer().render(argumentType, context); tdRight(result, RenderersUtilKt.renderStrong(renderedArgument, error) + (iterator.hasNext() ? RenderersUtilKt.renderStrong(",") : "")); i++; diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeErrorMessages.java b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeErrorMessages.java index 941e062eba6c5..dc856c556b7c7 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeErrorMessages.java +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeErrorMessages.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. + * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,11 +71,13 @@ public static boolean hasIdeSpecificMessage(@NotNull Diagnostic diagnostic) { @NotNull @Override public String[] render(@NotNull TypeMismatchDueToTypeProjectionsData object) { + RenderingContext context = RenderingContext + .of(object.getExpectedType(), object.getExpressionType(), object.getReceiverType(), object.getCallableDescriptor()); return new String[] { - HTML_RENDER_TYPE.render(object.getExpectedType()), - HTML_RENDER_TYPE.render(object.getExpressionType()), - HTML_RENDER_TYPE.render(object.getReceiverType()), - HTML.render(object.getCallableDescriptor()) + HTML_RENDER_TYPE.render(object.getExpectedType(), context), + HTML_RENDER_TYPE.render(object.getExpressionType(), context), + HTML_RENDER_TYPE.render(object.getReceiverType(), context), + HTML.render(object.getCallableDescriptor(), context) }; } }); diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeRenderers.kt b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeRenderers.kt index b21f0747335d3..38d14e749071c 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeRenderers.kt +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/IdeRenderers.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. + * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.jetbrains.kotlin.idea.highlighter import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor +import org.jetbrains.kotlin.diagnostics.rendering.ContextDependentRenderer import org.jetbrains.kotlin.diagnostics.rendering.Renderer import org.jetbrains.kotlin.diagnostics.rendering.Renderers import org.jetbrains.kotlin.diagnostics.rendering.asRenderer @@ -67,28 +68,29 @@ object IdeRenderers { Renderers.renderUpperBoundViolatedInferenceError(it, HtmlTabledDescriptorRenderer.create()).toString() } - @JvmField val HTML_RENDER_RETURN_TYPE = Renderer<CallableMemberDescriptor> { - val returnType = it.returnType!! - DescriptorRenderer.HTML.renderType(returnType) + @JvmField val HTML_RENDER_RETURN_TYPE = ContextDependentRenderer<CallableMemberDescriptor> { + member, context -> + HTML_RENDER_TYPE.render(member.returnType!!, context) } @JvmField val HTML_COMPACT_WITH_MODIFIERS = DescriptorRenderer.HTML.withOptions { withDefinedIn = false }.asRenderer() - @JvmField val HTML_CONFLICTING_JVM_DECLARATIONS_DATA = Renderer { - data: ConflictingJvmDeclarationsData -> + @JvmField val HTML_CONFLICTING_JVM_DECLARATIONS_DATA = ContextDependentRenderer { + data: ConflictingJvmDeclarationsData, renderingContext -> val conflicts = data.signatureOrigins - .mapNotNull { it.descriptor } - .sortedWith(MemberComparator.INSTANCE) - .joinToString("") { "<li>" + HTML_COMPACT_WITH_MODIFIERS.render(it) + "</li>\n" } + .mapNotNull { it.descriptor } + .sortedWith(MemberComparator.INSTANCE) + .joinToString("") { "<li>" + HTML_COMPACT_WITH_MODIFIERS.render(it, renderingContext) + "</li>\n" } "The following declarations have the same JVM signature (<code>${data.signature.name}${data.signature.desc}</code>):<br/>\n<ul>\n$conflicts</ul>" } - @JvmField val HTML_THROWABLE = Renderer<Throwable> { - Renderers.THROWABLE.render(it).replace("\n", "<br/>") + @JvmField val HTML_THROWABLE = ContextDependentRenderer<Throwable> { + throwable, context -> + Renderers.THROWABLE.render(throwable, context).replace("\n", "<br/>") } @JvmField val HTML = DescriptorRenderer.HTML.asRenderer() diff --git a/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/diagnostics/jsRenderers.kt b/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/diagnostics/jsRenderers.kt index 66a5984a21b68..edf40981acc28 100644 --- a/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/diagnostics/jsRenderers.kt +++ b/js/js.frontend/src/org/jetbrains/kotlin/js/resolve/diagnostics/jsRenderers.kt @@ -1,5 +1,5 @@ /* - * Copyright 2010-2015 JetBrains s.r.o. + * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,10 @@ package org.jetbrains.kotlin.js.resolve.diagnostics import com.google.gwt.dev.js.rhino.Utils.isEndOfLine import com.intellij.psi.PsiElement import org.jetbrains.kotlin.diagnostics.rendering.DiagnosticParameterRenderer +import org.jetbrains.kotlin.diagnostics.rendering.RenderingContext object RenderFirstLineOfElementText : DiagnosticParameterRenderer<PsiElement> { - override fun render(element: PsiElement): String { + override fun render(element: PsiElement, context: RenderingContext): String { val text = element.text val index = text.indexOf('\n') return if (index == -1) text else text.substring(0, index) + "..." @@ -31,7 +32,7 @@ object RenderFirstLineOfElementText : DiagnosticParameterRenderer<PsiElement> { abstract class JsCallDataRenderer : DiagnosticParameterRenderer<JsCallData> { protected abstract fun format(data: JsCallDataWithCode): String - override fun render(data: JsCallData): String = + override fun render(data: JsCallData, context: RenderingContext): String = when (data) { is JsCallDataWithCode -> format(data) is JsCallData -> data.message
2eeb4ebd8c3af6f5838efe510da4c92ceb0ceb35
elasticsearch
improve memcached test--
p
https://github.com/elastic/elasticsearch
diff --git a/plugins/transport/memcached/src/test/java/org/elasticsearch/memcached/test/AbstractMemcachedActionsTests.java b/plugins/transport/memcached/src/test/java/org/elasticsearch/memcached/test/AbstractMemcachedActionsTests.java index 71c01e745a039..2a5bcbd2c7c72 100644 --- a/plugins/transport/memcached/src/test/java/org/elasticsearch/memcached/test/AbstractMemcachedActionsTests.java +++ b/plugins/transport/memcached/src/test/java/org/elasticsearch/memcached/test/AbstractMemcachedActionsTests.java @@ -21,6 +21,7 @@ import net.spy.memcached.MemcachedClient; import org.elasticsearch.node.Node; +import org.hamcrest.Matchers; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -31,6 +32,8 @@ import static org.elasticsearch.common.xcontent.XContentFactory.*; import static org.elasticsearch.node.NodeBuilder.*; +import static org.hamcrest.MatcherAssert.*; +import static org.hamcrest.Matchers.*; /** * @author kimchy (shay.banon) @@ -56,20 +59,29 @@ public void tearDown() { } @Test public void testSimpleOperations() throws Exception { - Future setResult = memcachedClient.set("/test/person/1", 0, jsonBuilder().startObject().field("test", "value").endObject().copiedBytes()); - setResult.get(10, TimeUnit.SECONDS); + Future<Boolean> setResult = memcachedClient.set("/test/person/1", 0, jsonBuilder().startObject().field("test", "value").endObject().copiedBytes()); + assertThat(setResult.get(10, TimeUnit.SECONDS), equalTo(true)); String getResult = (String) memcachedClient.get("/_refresh"); System.out.println("REFRESH " + getResult); + assertThat(getResult, Matchers.containsString("\"total\":10")); + assertThat(getResult, Matchers.containsString("\"successful\":5")); + assertThat(getResult, Matchers.containsString("\"failed\":0")); getResult = (String) memcachedClient.get("/test/person/1"); System.out.println("GET " + getResult); + assertThat(getResult, Matchers.containsString("\"_index\":\"test\"")); + assertThat(getResult, Matchers.containsString("\"_type\":\"person\"")); + assertThat(getResult, Matchers.containsString("\"_id\":\"1\"")); - Future deleteResult = memcachedClient.delete("/test/person/1"); - deleteResult.get(10, TimeUnit.SECONDS); + Future<Boolean> deleteResult = memcachedClient.delete("/test/person/1"); + assertThat(deleteResult.get(10, TimeUnit.SECONDS), equalTo(true)); getResult = (String) memcachedClient.get("/_refresh"); System.out.println("REFRESH " + getResult); + assertThat(getResult, Matchers.containsString("\"total\":10")); + assertThat(getResult, Matchers.containsString("\"successful\":5")); + assertThat(getResult, Matchers.containsString("\"failed\":0")); getResult = (String) memcachedClient.get("/test/person/1"); System.out.println("GET " + getResult);
c9aea8c9a95b0903411afb9ef033b002e7da6648
eclipse$vert.x
Message Forward -Added capability for forwarding messages -Added forward with header/body optimizations -Added isForwarded status flag on Message -Unit Tests -Cleanup, method renaming for consistency -Written against latest vert.x EB API
p
https://github.com/eclipse-vertx/vert.x
diff --git a/.gitignore b/.gitignore index 11528caab61..1a7fe61f9ad 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,4 @@ test-results test-tmp *.class ScratchPad.java +*.swp diff --git a/vertx-core/src/main/java/io/vertx/core/eventbus/Message.java b/vertx-core/src/main/java/io/vertx/core/eventbus/Message.java index fe316cd3b23..33d298b9399 100644 --- a/vertx-core/src/main/java/io/vertx/core/eventbus/Message.java +++ b/vertx-core/src/main/java/io/vertx/core/eventbus/Message.java @@ -78,4 +78,13 @@ public interface Message<T> { void forward(String address); void forward(String address, DeliveryOptions options); + + /** + * Indicates whether or not this message has been received as a result of a forward operation + * versus a send or publish. + * + * @return whether or not the message has been fowarded + */ + boolean isForward(); + } diff --git a/vertx-core/src/main/java/io/vertx/core/eventbus/impl/EventBusImpl.java b/vertx-core/src/main/java/io/vertx/core/eventbus/impl/EventBusImpl.java index 32073caecbf..24170b11c16 100644 --- a/vertx-core/src/main/java/io/vertx/core/eventbus/impl/EventBusImpl.java +++ b/vertx-core/src/main/java/io/vertx/core/eventbus/impl/EventBusImpl.java @@ -209,6 +209,14 @@ public EventBus publish(String address, Object message, DeliveryOptions options) return this; } + EventBus forward(String address, Object message) { + return forward(address, message, null); + } + + EventBus forward(String address, Object message, DeliveryOptions options) { + sendOrPub(null, (MessageImpl)message, options, null); + return this; + } @Override public <T> MessageConsumer<T> consumer(String address) { return new HandlerRegistration<>(address, false, false, -1); @@ -709,7 +717,7 @@ private void schedulePing(ConnectionHolder holder) { cleanupConnection(holder.theServerID, holder, true); }); MessageImpl pingMessage = new MessageImpl<>(serverID, PING_ADDRESS, null, null, null, new NullMessageCodec(), true); - holder.socket.write(pingMessage.encodeToWire()); + holder.socket.write(pingMessage.writeToWire()); }); } @@ -846,11 +854,11 @@ private ConnectionHolder(NetClient client) { void writeMessage(MessageImpl message) { if (connected) { - socket.write(message.encodeToWire()); + socket.write(message.writeToWire()); } else { synchronized (this) { if (connected) { - socket.write(message.encodeToWire()); + socket.write(message.writeToWire()); } else { pending.add(message); } @@ -872,7 +880,7 @@ synchronized void connected(ServerID theServerID, NetSocket socket) { // Start a pinger schedulePing(ConnectionHolder.this); for (MessageImpl message : pending) { - socket.write(message.encodeToWire()); + socket.write(message.writeToWire()); } pending.clear(); } diff --git a/vertx-core/src/main/java/io/vertx/core/eventbus/impl/MessageImpl.java b/vertx-core/src/main/java/io/vertx/core/eventbus/impl/MessageImpl.java index 1501a0735aa..25d207b0aac 100644 --- a/vertx-core/src/main/java/io/vertx/core/eventbus/impl/MessageImpl.java +++ b/vertx-core/src/main/java/io/vertx/core/eventbus/impl/MessageImpl.java @@ -55,6 +55,9 @@ public class MessageImpl<U, V> implements Message<V> { private Buffer wireBuffer; private int bodyPos; private int headersPos; + private int absoluteBodyPos; + private int absoluteHeaderPos; + private boolean isForwarded; public MessageImpl() { } @@ -91,8 +94,12 @@ private MessageImpl(MessageImpl<U, V> other) { this.wireBuffer = other.wireBuffer; this.bodyPos = other.bodyPos; this.headersPos = other.headersPos; + this.headersPos = other.headersPos; + this.absoluteBodyPos = other.absoluteBodyPos; + this.absoluteHeaderPos = other.absoluteHeaderPos; } this.send = other.send; + this.isForwarded = other.isForwarded; } public MessageImpl<U, V> copyBeforeReceive() { @@ -110,7 +117,7 @@ public MultiMap headers() { if (headers == null) { // The message has been read from the wire if (headersPos != 0) { - decodeHeaders(); + readHeaders(); } if (headers == null) { headers = new CaseInsensitiveHeaders(); @@ -124,7 +131,7 @@ public V body() { // Lazily decode the body if (receivedBody == null && bodyPos != 0) { // The message has been read from the wire - decodeBody(); + readBody(); } return receivedBody; } @@ -134,8 +141,8 @@ public String replyAddress() { return replyAddress; } - public Buffer encodeToWire() { - int length = 1024; // TODO make this configurable + public Buffer writeToWire() { + int length = 1024; Buffer buffer = Buffer.buffer(length); buffer.appendInt(0); buffer.appendByte(WIRE_PROTOCOL_VERSION); @@ -154,12 +161,10 @@ public Buffer encodeToWire() { } buffer.appendInt(sender.port); writeString(buffer, sender.host); - encodeHeaders(buffer); + buffer.appendByte(isForwarded ? (byte)0 : (byte)1); + writeHeaders(buffer); writeBody(buffer); buffer.setInt(0, buffer.length() - 4); -// if (buffer.length()> length) { -// log.warn("Overshot length " + length + " actual " + buffer.length()); -// } return buffer; } @@ -210,20 +215,25 @@ public void readFromWire(Buffer buffer, Map<String, MessageCodec> codecMap, Mess bytes = buffer.getBytes(pos, pos + length); String senderHost = new String(bytes, CharsetUtil.UTF_8); pos += length; - headersPos = pos; + + isForwarded = (buffer.getByte(pos) == 0); + pos++; + + headersPos = absoluteHeaderPos = pos; int headersLength = buffer.getInt(pos); pos += headersLength; - bodyPos = pos; + bodyPos = absoluteBodyPos = pos; sender = new ServerID(senderPort, senderHost); wireBuffer = buffer; } - private void decodeBody() { + private void readBody() { receivedBody = messageCodec.decodeFromWire(bodyPos, wireBuffer); bodyPos = 0; } - private void encodeHeaders(Buffer buffer) { + private void writeHeaders(Buffer buffer) { + //Headers exist, have been decoded from the wire, and need to be reencoded if (headers != null && !headers.isEmpty()) { int headersLengthPos = buffer.getByteBuf().writerIndex(); buffer.appendInt(0); @@ -235,12 +245,20 @@ private void encodeHeaders(Buffer buffer) { } int headersEndPos = buffer.getByteBuf().writerIndex(); buffer.setInt(headersLengthPos, headersEndPos - headersLengthPos); - } else { + }else if((headers == null && headersPos != 0) || (headers != null && headersPos == 0)){ + //headers could exist, just have never been read + int length = wireBuffer.getInt(headersPos); + buffer.appendInt(length); + int numHeaders = wireBuffer.getInt(headersPos + 4); + buffer.appendInt(numHeaders); + byte[] rawHeaders = wireBuffer.getBytes(headersPos + 8, (headersPos) + length); + buffer.appendBytes(rawHeaders); + }else { buffer.appendInt(4); } } - private void decodeHeaders() { + private void readHeaders() { int length = wireBuffer.getInt(headersPos); if (length != 0) { headersPos += 4; @@ -265,7 +283,14 @@ private void decodeHeaders() { } private void writeBody(Buffer buff) { - messageCodec.encodeToWire(buff, sentBody); + if(sentBody != null){ + messageCodec.encodeToWire(buff, sentBody); + }else if((receivedBody == null && bodyPos != 0) || (receivedBody != null && bodyPos == 0)){ + int length = wireBuffer.getInt(absoluteBodyPos); + byte[] bytes = wireBuffer.getBytes(absoluteBodyPos + 4, absoluteBodyPos + 4 + length); + buff.appendInt(bytes.length); + buff.appendBytes(bytes); + } } private void writeString(Buffer buff, String str) { @@ -282,12 +307,14 @@ public void fail(int failureCode, String message) { @Override public void forward(String address) { - + forward(address, null); } @Override public void forward(String address, DeliveryOptions options) { - + this.address = address; + this.isForwarded = true; + bus.forward(address, this, options); } @Override @@ -332,5 +359,10 @@ private <R> void sendReply(MessageImpl msg, DeliveryOptions options, Handler<Asy } } + @Override + public boolean isForward() { + return this.isForwarded; + } + } diff --git a/vertx-core/src/test/java/io/vertx/test/core/ClusteredEventBusTest.java b/vertx-core/src/test/java/io/vertx/test/core/ClusteredEventBusTest.java index 81b06ef0813..0ef419f2475 100644 --- a/vertx-core/src/test/java/io/vertx/test/core/ClusteredEventBusTest.java +++ b/vertx-core/src/test/java/io/vertx/test/core/ClusteredEventBusTest.java @@ -155,6 +155,60 @@ public void handle(AsyncResult<Void> ar) { vertices[0].eventBus().publish(ADDRESS1, val); await(); } + + @Override + protected <T> void testForward(T val) { + startNodes(2); + + vertices[0].eventBus().<T>consumer(ADDRESS1).handler((Message<T> msg) -> { + assertEquals(val, msg.body()); + msg.forward(ADDRESS2); + }); + + vertices[1].eventBus().<T>consumer(ADDRESS2).handler((Message<T> msg) -> { + assertEquals(val, msg.body()); + assertTrue(msg.isForward()); + testComplete(); + }); + + vertices[0].eventBus().send(ADDRESS1, val); + await(); + + } + + @Override + protected <T> void testForward(T val, DeliveryOptions options) { + + startNodes(2); + int expectedHeaders = options.getHeaders().size(); + final String FIRST_KEY = "first"; + final String SEC_KEY = "second"; + + vertices[0].eventBus().<T>consumer(ADDRESS1).handler((Message<T> msg) -> { + assertEquals(val, msg.body()); + if(!msg.isForward()){ + msg.forward(ADDRESS2); + }else{ + assertTrue(msg.isForward()); + assertTrue(msg.headers().size() == expectedHeaders); + assertEquals(msg.headers().get(FIRST_KEY), "first"); + assertEquals(msg.headers().get(SEC_KEY), "second"); + testComplete(); + } + + }); + + vertices[1].eventBus().<T>consumer(ADDRESS2).handler((Message<T> msg) -> { + assertEquals(val, msg.body()); + assertTrue(msg.isForward()); + msg.forward(ADDRESS1); + }); + + vertices[0].eventBus().send(ADDRESS1, val, options); + await(); + + } + @Test public void testLocalHandlerNotReceive() throws Exception { diff --git a/vertx-core/src/test/java/io/vertx/test/core/EventBusTestBase.java b/vertx-core/src/test/java/io/vertx/test/core/EventBusTestBase.java index b47233ea0c8..b22e9e0b391 100644 --- a/vertx-core/src/test/java/io/vertx/test/core/EventBusTestBase.java +++ b/vertx-core/src/test/java/io/vertx/test/core/EventBusTestBase.java @@ -326,6 +326,23 @@ public void testReplyWithHeaders() { testReply("foo", "foo", null, new DeliveryOptions().addHeader("uhqwduh", "qijwdqiuwd").addHeader("iojdijef", "iqjwddh")); } + @Test + public void testForward(){ + testForward(TestUtils.randomUnicodeString(100)); + } + + @Test + public void testForwardWithHeaders(){ + DeliveryOptions options = new DeliveryOptions(); + options.addHeader("first", "first"); + options.addHeader("second", "second"); + testForward("Test body", options); + } + + protected abstract <T> void testForward(T val); + + protected abstract <T> void testForward(T val, DeliveryOptions options); + protected <T> void testSend(T val) { testSend(val, null); } diff --git a/vertx-core/src/test/java/io/vertx/test/core/LocalEventBusTest.java b/vertx-core/src/test/java/io/vertx/test/core/LocalEventBusTest.java index ae341857fb5..4a5cbed994c 100644 --- a/vertx-core/src/test/java/io/vertx/test/core/LocalEventBusTest.java +++ b/vertx-core/src/test/java/io/vertx/test/core/LocalEventBusTest.java @@ -1201,5 +1201,42 @@ public void testPump() { Pump.pump(consumer, producer); producer.write(str); } -} + @Override + protected <T> void testForward(T val) { + + eb.<T>consumer(ADDRESS1).handler((Message<T> msg) -> { + assertEquals(val, msg.body()); + msg.forward(ADDRESS2); + + }); + + eb.<T>consumer(ADDRESS2).handler((Message<T> msg) -> { + + assertEquals(val, msg.body()); + testComplete(); + }); + + eb.send(ADDRESS1, val); + await(); + } + + @Override + protected <T> void testForward(T val, DeliveryOptions options) { + + eb.<T>consumer(ADDRESS1).handler((Message<T> msg) -> { + assertEquals(val, msg.body()); + msg.forward(ADDRESS2); + }); + + eb.<T>consumer(ADDRESS2).handler((Message<T> msg) -> { + + assertEquals(val, msg.body()); + testComplete(); + }); + + eb.send(ADDRESS1, val, options); + await(); + + } +}
aded57f8faa5c23934839ac6b44e1376ea99c07b
Delta Spike
DELTASPIKE-289 windowId detection code with JavaScript and intermediate page partly ported over from MyFaces CODI, partly rewritten. Passing the windowId via hidden input field
a
https://github.com/apache/deltaspike
diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdHolderComponent.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/component/window/WindowIdHolderComponent.java similarity index 91% rename from deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdHolderComponent.java rename to deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/component/window/WindowIdHolderComponent.java index e4f73268b..4ec76c50b 100644 --- a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdHolderComponent.java +++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/component/window/WindowIdHolderComponent.java @@ -16,8 +16,9 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.deltaspike.jsf.impl.scope.window; +package org.apache.deltaspike.jsf.impl.component.window; +import javax.faces.component.FacesComponent; import javax.faces.component.UIComponent; import javax.faces.component.UIOutput; import javax.faces.component.UIViewRoot; @@ -32,8 +33,11 @@ * We store this component as direct child in the ViewRoot * and evaluate it's value on postbacks. */ +@FacesComponent(WindowIdHolderComponent.COMPONENT_TYPE) public class WindowIdHolderComponent extends UIOutput { + public static final String COMPONENT_TYPE = "org.apache.deltaspike.WindowIdHolder"; + private static final Logger logger = Logger.getLogger(WindowIdHolderComponent.class.getName()); private String windowId; diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitWrapper.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/component/window/WindowIdHolderComponentHtmlRenderer.java similarity index 53% rename from deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitWrapper.java rename to deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/component/window/WindowIdHolderComponentHtmlRenderer.java index bb939d516..ff3193303 100644 --- a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitWrapper.java +++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/component/window/WindowIdHolderComponentHtmlRenderer.java @@ -16,64 +16,57 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.deltaspike.jsf.impl.scope.window; +package org.apache.deltaspike.jsf.impl.component.window; +import javax.faces.application.ResourceDependencies; +import javax.faces.application.ResourceDependency; +import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; -import javax.faces.render.RenderKit; -import javax.faces.render.RenderKitWrapper; -import java.io.Writer; +import javax.faces.render.FacesRenderer; +import javax.faces.render.Renderer; +import java.io.IOException; import org.apache.deltaspike.core.api.provider.BeanProvider; import org.apache.deltaspike.core.spi.scope.window.WindowContext; + /** - * Wraps the RenderKit and adds the - * {@link WindowIdHolderComponent} to the view tree + * HtmlRenderer for our dsWindowId hidden field. + * This gets used for post requests. */ -public class WindowIdRenderKitWrapper extends RenderKitWrapper +@FacesRenderer(componentFamily = WindowIdHolderComponent.COMPONENT_FAMILY, + rendererType = WindowIdHolderComponent.COMPONENT_TYPE) +@ResourceDependencies( { + @ResourceDependency(library = "js", name = "windowhandler.js", target = "head"), + @ResourceDependency(library = "javax.faces", name = "jsf.js", target = "head") } ) +public class WindowIdHolderComponentHtmlRenderer extends Renderer { - private final RenderKit wrapped; - - /** - * This will get initialized lazily to prevent boot order issues - * with the JSF and CDI containers. - */ private volatile WindowContext windowContext; - //needed if the renderkit gets proxied - see EXTCDI-215 - protected WindowIdRenderKitWrapper() - { - this.wrapped = null; - } - - public WindowIdRenderKitWrapper(RenderKit wrapped) - { - this.wrapped = wrapped; - } - - @Override - public RenderKit getWrapped() - { - return wrapped; - } - /** - * Adds a {@link WindowIdHolderComponent} with the - * current windowId to the component tree. + * Write a simple hidden field into the form. + * This might change in the future... + * @param context + * @param component + * @throws IOException */ - public ResponseWriter createResponseWriter(Writer writer, String s, String s1) + @Override + public void encodeBegin(FacesContext context, UIComponent component) throws IOException { - FacesContext facesContext = FacesContext.getCurrentInstance(); + super.encodeBegin(context, component); + String windowId = getWindowContext().getCurrentWindowId(); - WindowIdHolderComponent.addWindowIdHolderComponent(facesContext, windowId); + ResponseWriter writer = context.getResponseWriter(); + writer.startElement("script", component); + writer.writeAttribute("type", "text/javascript", null); + writer.write("window.deltaspikeJsWindowId=" + windowId + ";"); - return wrapped.createResponseWriter(writer, s, s1); + writer.endElement("script"); } - private WindowContext getWindowContext() { if (windowContext == null) diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/DefaultClientWindow.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/DefaultClientWindow.java index 3ea94788a..31185029f 100644 --- a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/DefaultClientWindow.java +++ b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/DefaultClientWindow.java @@ -20,7 +20,6 @@ import javax.enterprise.context.ApplicationScoped; import javax.faces.FacesException; -import javax.faces.component.UIViewRoot; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.inject.Inject; @@ -29,6 +28,8 @@ import java.io.IOException; import java.io.OutputStream; +import java.util.Map; +import java.util.Random; import java.util.logging.Logger; import org.apache.deltaspike.core.spi.scope.window.WindowContext; @@ -51,8 +52,26 @@ @ApplicationScoped public class DefaultClientWindow implements ClientWindow { + + /** + * Value which can be used as "window-id" by external clients which aren't aware of windows. + * It deactivates e.g. the redirect for the initial request. + */ + public static final String AUTOMATED_ENTRY_POINT_PARAMETER_KEY = "automatedEntryPoint"; + + /** + * The parameter for the windowId for GET requests + */ + public static final String DELTASPIKE_WINDOW_ID_PARAM = "windowId"; + + /** + * The parameter for the windowId for POST requests + */ + public static final String DELTASPIKE_WINDOW_ID_POST_PARAM = "dsPostWindowId"; + private static final Logger logger = Logger.getLogger(DefaultClientWindow.class.getName()); + private static final String WINDOW_ID_COOKIE_PREFIX = "dsWindowId-"; private static final String DELTASPIKE_REQUEST_TOKEN = "dsRid"; @@ -60,6 +79,7 @@ public class DefaultClientWindow implements ClientWindow private static final String WINDOW_ID_REPLACE_PATTERN = "$$windowIdValue$$"; private static final String NOSCRIPT_URL_REPLACE_PATTERN = "$$noscriptUrl$$"; + /** * Use this parameter to force a 'direct' request from the clients without any windowId detection * We keep this name for backward compat with CODI. @@ -106,10 +126,19 @@ public String getWindowId(FacesContext facesContext) } String windowId = getVerifiedWindowIdFromCookie(externalContext); - if (windowId == null) + + boolean newWindowIdRequested = false; + if (AUTOMATED_ENTRY_POINT_PARAMETER_KEY.equals(windowId)) + { + // this is a marker for generating a new windowId + windowId = generateNewWindowId(); + newWindowIdRequested = true; + } + + if (windowId == null || newWindowIdRequested) { // GET request without windowId - send windowhandlerfilter.html to get the windowId - sendWindowHandlerHtml(externalContext, null); + sendWindowHandlerHtml(externalContext, windowId); facesContext.responseComplete(); } @@ -117,24 +146,24 @@ public String getWindowId(FacesContext facesContext) return windowId; } + /** + * Create a unique windowId + * @return + */ + private String generateNewWindowId() + { + //X TODO proper mechanism + return "" + (new Random()).nextInt() % 10000; + } + /** * Extract the windowId for http POST */ private String getPostBackWindowId(FacesContext facesContext) { - UIViewRoot uiViewRoot = facesContext.getViewRoot(); - - if (uiViewRoot != null) - { - WindowIdHolderComponent existingWindowIdHolder - = WindowIdHolderComponent.getWindowIdHolderComponent(uiViewRoot); - if (existingWindowIdHolder != null) - { - return existingWindowIdHolder.getWindowId(); - } - } - - return null; + Map<String, String> requestParams = facesContext.getExternalContext().getRequestParameterMap(); + String windowId = requestParams.get(DELTASPIKE_WINDOW_ID_POST_PARAM); + return windowId; } diff --git a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitFactory.java b/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitFactory.java deleted file mode 100644 index 883ddb022..000000000 --- a/deltaspike/modules/jsf/impl/src/main/java/org/apache/deltaspike/jsf/impl/scope/window/WindowIdRenderKitFactory.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.deltaspike.jsf.impl.scope.window; - -import javax.faces.context.FacesContext; -import javax.faces.render.RenderKit; -import javax.faces.render.RenderKitFactory; -import java.util.Iterator; - -import org.apache.deltaspike.core.spi.activation.Deactivatable; -import org.apache.deltaspike.core.util.ClassDeactivationUtils; - - -/** - * Registers the @{link WindowIdRenderKit} - */ -public class WindowIdRenderKitFactory extends RenderKitFactory implements Deactivatable -{ - private final RenderKitFactory wrapped; - - private final boolean deactivated; - - /** - * Constructor for wrapping the given {@link javax.faces.render.RenderKitFactory} - * @param wrapped render-kit-factory which will be wrapped - */ - public WindowIdRenderKitFactory(RenderKitFactory wrapped) - { - this.wrapped = wrapped; - this.deactivated = !isActivated(); - } - - /** - * {@inheritDoc} - */ - @Override - public void addRenderKit(String s, RenderKit renderKit) - { - wrapped.addRenderKit(s, renderKit); - } - - /** - * {@inheritDoc} - */ - @Override - public RenderKit getRenderKit(FacesContext facesContext, String s) - { - RenderKit renderKit = wrapped.getRenderKit(facesContext, s); - - if (renderKit == null) - { - return null; - } - - if (deactivated) - { - return renderKit; - } - - return new WindowIdRenderKitWrapper(renderKit); - } - - /** - * {@inheritDoc} - */ - @Override - public Iterator<String> getRenderKitIds() - { - return wrapped.getRenderKitIds(); - } - - /** - * {@inheritDoc} - */ - @Override - public RenderKitFactory getWrapped() - { - return wrapped; - } - - public boolean isActivated() - { - return ClassDeactivationUtils.isActivated(getClass()); - } -} diff --git a/deltaspike/modules/jsf/impl/src/main/resources/META-INF/deltaspike.taglib.xml b/deltaspike/modules/jsf/impl/src/main/resources/META-INF/deltaspike.taglib.xml new file mode 100644 index 000000000..947063f16 --- /dev/null +++ b/deltaspike/modules/jsf/impl/src/main/resources/META-INF/deltaspike.taglib.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<facelet-taglib xmlns="http://java.sun.com/xml/ns/javaee" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd" + version="2.0"> + <namespace>http://deltaspike.apache.org/jsf</namespace> + + <tag> + <tag-name>windowId</tag-name> + <component> + <component-type>org.apache.deltaspike.WindowIdHolder</component-type> + <renderer-type>org.apache.deltaspike.WindowIdHolder</renderer-type> + </component> + </tag> +</facelet-taglib> diff --git a/deltaspike/modules/jsf/impl/src/main/resources/META-INF/faces-config.xml b/deltaspike/modules/jsf/impl/src/main/resources/META-INF/faces-config.xml index 8b7b43a7e..de8ef13d4 100644 --- a/deltaspike/modules/jsf/impl/src/main/resources/META-INF/faces-config.xml +++ b/deltaspike/modules/jsf/impl/src/main/resources/META-INF/faces-config.xml @@ -37,6 +37,6 @@ <factory> <lifecycle-factory>org.apache.deltaspike.jsf.impl.listener.request.DeltaSpikeLifecycleFactoryWrapper</lifecycle-factory> <faces-context-factory>org.apache.deltaspike.jsf.impl.listener.request.DeltaSpikeFacesContextFactory</faces-context-factory> - <render-kit-factory>org.apache.deltaspike.jsf.impl.scope.window.WindowIdRenderKitFactory</render-kit-factory> </factory> + </faces-config> diff --git a/deltaspike/modules/jsf/impl/src/main/resources/META-INF/resources/js/windowhandler.js b/deltaspike/modules/jsf/impl/src/main/resources/META-INF/resources/js/windowhandler.js index b563b3120..c7f6bca2a 100644 --- a/deltaspike/modules/jsf/impl/src/main/resources/META-INF/resources/js/windowhandler.js +++ b/deltaspike/modules/jsf/impl/src/main/resources/META-INF/resources/js/windowhandler.js @@ -73,28 +73,43 @@ function equalsIgnoreCase(source, destination) { } /** This method will be called onWindowLoad and after AJAX success */ -function applyOnClick() { - var links = document.getElementsByTagName("a"); - for (var i = 0; i < links.length; i++) { - if (!links[i].onclick) { - links[i].onclick = function() {storeWindowTree(); return true;}; - } else { - // prevent double decoration - if (!("" + links[i].onclick).match(".*storeWindowTree().*")) { - //the function wrapper is important otherwise the - //last onclick handler would be assigned to oldonclick - (function storeEvent() { - var oldonclick = links[i].onclick; - links[i].onclick = function(evt) { - //ie handling added - evt = evt || window.event; +function applyWindowId() { + if (isHtml5()) { // onClick handling + var links = document.getElementsByTagName("a"); + for (var i = 0; i < links.length; i++) { + if (!links[i].onclick) { + links[i].onclick = function() {storeWindowTree(); return true;}; + } else { + // prevent double decoration + if (!("" + links[i].onclick).match(".*storeWindowTree().*")) { + //the function wrapper is important otherwise the + //last onclick handler would be assigned to oldonclick + (function storeEvent() { + var oldonclick = links[i].onclick; + links[i].onclick = function(evt) { + //ie handling added + evt = evt || window.event; - return storeWindowTree() && oldonclick(evt); - }; - })(); + return storeWindowTree() && oldonclick(evt); + }; + })(); + } } } } + var forms = document.getElementsByTagName("form"); + for (var i = 0; i < forms.length; i++) { + var form = forms[i]; + var windowIdHolder = form.elements["dsPostWindowId"]; + if (!windowIdHolder) { + windowIdHolder = document.createElement("INPUT"); + windowIdHolder.name = "dsPostWindowId"; + windowIdHolder.type = "hidden"; + form.appendChild(windowIdHolder); + } + + windowIdHolder.value = window.deltaspikeJsWindowId; + } } function getUrlParameter(name) { @@ -159,7 +174,7 @@ function eraseRequestCookie() { var ajaxOnClick = function ajaxDecorateClick(event) { if (event.status=="success") { - applyOnClick(); + applyWindowId(); } } @@ -171,10 +186,8 @@ window.onload = function(evt) { } finally { eraseRequestCookie(); // manually erase the old dsRid cookie because Firefox doesn't do it properly assertWindowId(); - if (isHtml5()) { - applyOnClick(); - jsf.ajax.addOnEvent(ajaxOnClick); - } + applyWindowId(); + jsf.ajax.addOnEvent(ajaxOnClick); } } })(); diff --git a/deltaspike/modules/jsf/impl/src/main/resources/static/windowhandler.html b/deltaspike/modules/jsf/impl/src/main/resources/static/windowhandler.html index c0967228f..30e622ad3 100644 --- a/deltaspike/modules/jsf/impl/src/main/resources/static/windowhandler.html +++ b/deltaspike/modules/jsf/impl/src/main/resources/static/windowhandler.html @@ -135,29 +135,35 @@ replaceContent(); window.onload = function() { + // uncomment the following line to debug the intermediate page + // if (!confirm('reload?')) { return true; } + loadCss(true); // this will be replaced in the phase listener - var windowId = '$$windowIdValue$$'; - if (windowId == 'uninitializedWindowId') { - windowId = window.name - } + var windowId = window.name; + var urlId = windowId; if (!windowId || windowId.length < 1) { - // request a new windowId - windowId = 'automatedEntryPoint'; + var newWindowId = '$$windowIdValue$$'; + if (newWindowId != 'uninitializedWindowId') { + window.name = newWindowId; // set the window.name with our windowId + windowId = newWindowId; + urlId = windowId; + } + else { + windowId = 'automatedEntryPoint'; + urlId = null; + } } - window.name = windowId; - - // uncomment the following line to debug the intermediate page - // if (!confirm('reload?')) { return true; } - // 3 seconds expiry time var expdt = new Date(); expdt.setTime(expdt.getTime()+(3*1000)); var expires = "; expires="+expdt.toGMTString(); - var requestToken = Math.floor(Math.random()*1001); + var requestToken = Math.floor(Math.random()*999); var newUrl = setUrlParam(window.location.href, "dsRid", requestToken); + + // we still add hte windowId page param to support lazy windowId dropping for some clients newUrl = setUrlParam(newUrl, "windowId", windowId); document.cookie = 'dsWindowId-' + requestToken + '=' + windowId + expires+"; path=/"; diff --git a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/WindowScopedContextTest.java b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/WindowScopedContextTest.java new file mode 100644 index 000000000..6f84fe88e --- /dev/null +++ b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/WindowScopedContextTest.java @@ -0,0 +1,99 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.deltaspike.test.jsf.impl.scope.window; + + +import java.net.URL; + +import org.apache.deltaspike.test.category.WebProfileCategory; +import org.apache.deltaspike.test.jsf.impl.scope.window.beans.WindowScopedBackingBean; +import org.apache.deltaspike.test.jsf.impl.util.ArchiveUtils; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.container.test.api.RunAsClient; +import org.jboss.arquillian.drone.api.annotation.Drone; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.arquillian.test.api.ArquillianResource; +import org.jboss.arquillian.warp.WarpTest; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.EmptyAsset; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Assert; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; + + +/** + * Test for the DeltaSpike JsfMessage Producer + */ +@WarpTest +@RunWith(Arquillian.class) +@Category(WebProfileCategory.class) +public class WindowScopedContextTest +{ + @Drone + private WebDriver driver; + + @ArquillianResource + private URL contextPath; + + @Deployment + public static WebArchive deploy() + { + return ShrinkWrap + .create(WebArchive.class, "windowScopedContextTest.war") + .addPackage(WindowScopedBackingBean.class.getPackage()) + .addAsLibraries(ArchiveUtils.getDeltaSpikeCoreAndJsfArchive()) + .addAsLibraries(ArchiveUtils.getDeltaSpikeSecurityArchive()) + .addAsWebInfResource("default/WEB-INF/web.xml", "web.xml") + .addAsWebResource("META-INF/resources/js/windowhandler.js", "resources/js/windowhandler.js") + .addAsWebResource("windowScopedContextTest/page.xhtml", "page.xhtml") + .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml"); + } + + + @Test + @RunAsClient + public void testWindowId() throws Exception + { + System.out.println("contextpath= " + contextPath); + //X Thread.sleep(600000L); + + driver.get(new URL(contextPath, "page.xhtml").toString()); + + //X comment this in if you like to debug the server + //X I've already reported ARQGRA-213 for it + //X + + WebElement inputField = driver.findElement(By.id("test:valueInput")); + inputField.sendKeys("23"); + + WebElement button = driver.findElement(By.id("test:saveButton")); + button.click(); + + Assert.assertTrue(ExpectedConditions.textToBePresentInElement(By.id("test:valueOutput"), "23").apply(driver)); + + } + + +} diff --git a/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/beans/WindowScopedBackingBean.java b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/beans/WindowScopedBackingBean.java new file mode 100644 index 000000000..8a58d483f --- /dev/null +++ b/deltaspike/modules/jsf/impl/src/test/java/org/apache/deltaspike/test/jsf/impl/scope/window/beans/WindowScopedBackingBean.java @@ -0,0 +1,50 @@ +/* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.apache.deltaspike.test.jsf.impl.scope.window.beans; + +import javax.inject.Named; +import java.io.Serializable; + +import org.apache.deltaspike.core.api.scope.WindowScoped; + +/** + * WindowScoped sample backing bean. + */ +@WindowScoped +@Named("windowScopedBean") +public class WindowScopedBackingBean implements Serializable +{ + private int i = 0; + + public int getI() + { + return i; + } + + public void setI(int i) + { + this.i = i; + } + + public String someAction() + { + // stay on the page. + return null; + } +} diff --git a/deltaspike/modules/jsf/impl/src/test/resources/windowScopedContextTest/page.xhtml b/deltaspike/modules/jsf/impl/src/test/resources/windowScopedContextTest/page.xhtml new file mode 100644 index 000000000..c0a64c4c6 --- /dev/null +++ b/deltaspike/modules/jsf/impl/src/test/resources/windowScopedContextTest/page.xhtml @@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +--> + +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" + xmlns:h="http://java.sun.com/jsf/html" + xmlns:f="http://java.sun.com/jsf/core" + xmlns:ui="http://java.sun.com/jsf/facelets" + xmlns:c="http://java.sun.com/jsp/jstl/core" + xmlns:ds="http://deltaspike.apache.org/jsf"> + +<h:head> + +</h:head> + +<h:body> +<ds:windowId/> +<div> + <h:form id="test"> + <h:outputLabel for="valueInput" value="WindowScoped value:"/> + <h:inputText id="valueInput" value="#{windowScopedBean.i}"/> + <br/> + <h:outputLabel for="valueOutput" value="backing bean value:"/> + <h:outputText id="valueOutput" value="#{windowScopedBean.i}"/> + <br/> + <h:commandButton id="saveButton" action="#{windowScopedBean.someAction}" value="save"/> + </h:form> +</div> +</h:body> +</html>
59f1ae7b2b15776314059123e26dc1563ca064c8
Vala
tracker-indexer-module-1.0: regenerate
a
https://github.com/GNOME/vala/
diff --git a/vapi/tracker-indexer-module-1.0.vapi b/vapi/tracker-indexer-module-1.0.vapi index b6b6d68974..fed3d41010 100644 --- a/vapi/tracker-indexer-module-1.0.vapi +++ b/vapi/tracker-indexer-module-1.0.vapi @@ -2,40 +2,118 @@ [CCode (cprefix = "Tracker", lower_case_cprefix = "tracker_")] namespace Tracker { + [CCode (cprefix = "TrackerModule", lower_case_cprefix = "tracker_module_")] + namespace Module { + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] + public delegate void FileFreeDataFunc (); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h", has_target = false)] + public delegate void* FileGetDataFunc (string path); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h", has_target = false)] + public delegate unowned Tracker.Metadata FileGetMetadataFunc (Tracker.File file); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h", has_target = false)] + public delegate unowned string FileGetServiceTypeFunc (Tracker.File file); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h", has_target = false)] + public delegate unowned string FileGetText (Tracker.File path); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h", has_target = false)] + public delegate void FileGetUriFunc (Tracker.File file, string dirname, string basename); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h", has_target = false)] + public delegate bool FileIterContents (Tracker.File path); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h", has_target = false)] + public delegate unowned string GetDirectoriesFunc (); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h", has_target = false)] + public delegate unowned string GetNameFunc (); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h", has_target = false)] + public delegate void Init (); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h", has_target = false)] + public delegate void Shutdown (); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] + public static void file_free_data (void* file_data); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] + public static void* file_get_data (string path); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] + public static unowned Tracker.Metadata file_get_metadata (Tracker.File file); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] + public static unowned string file_get_service_type (Tracker.File file); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] + public static unowned string file_get_text (Tracker.File file); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] + public static void file_get_uri (Tracker.File file, string dirname, string basename); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] + public static bool file_iter_contents (Tracker.File file); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] + public static unowned string get_name (); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] + public static void init (); + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] + public static void shutdown (); + } + [CCode (cprefix = "TrackerModuleConfig", lower_case_cprefix = "tracker_module_config_")] + namespace ModuleConfig { + [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] + public static unowned string get_description (string name); + [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] + public static bool get_enabled (string name); + [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] + public static unowned GLib.List get_ignored_directories (string name); + [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] + public static unowned GLib.List get_ignored_directory_patterns (string name); + [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] + public static unowned GLib.List get_ignored_file_patterns (string name); + [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] + public static unowned GLib.List get_ignored_files (string name); + [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] + public static unowned GLib.List get_index_file_patterns (string name); + [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] + public static unowned GLib.List get_index_files (string name); + [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] + public static unowned GLib.List get_index_mime_types (string name); + [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] + public static unowned string get_index_service (string name); + [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] + public static unowned GLib.List get_modules (); + [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] + public static unowned GLib.List get_monitor_directories (string name); + [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] + public static unowned GLib.List get_monitor_recurse_directories (string name); + [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] + public static bool init (); + [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] + public static void shutdown (); + } [CCode (cprefix = "TrackerOntology", lower_case_cprefix = "tracker_ontology_")] namespace Ontology { [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] public static void field_add (Tracker.Field field); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] - public static weak string field_get_display_name (Tracker.Field field); + public static unowned string field_get_display_name (Tracker.Field field); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] - public static weak string field_get_id (string name); + public static unowned string field_get_id (string name); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] public static bool field_is_child_of (string child, string parent); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] - public static weak Tracker.Field get_field_by_id (int id); + public static unowned Tracker.Field get_field_by_id (int id); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] - public static weak Tracker.Field get_field_by_name (string name); + public static unowned Tracker.Field get_field_by_name (string name); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] - public static weak string get_field_name_by_service_name (Tracker.Field field, string service_str); + public static unowned string get_field_name_by_service_name (Tracker.Field field, string service_str); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] - public static weak GLib.SList get_field_names_registered (string service_str); + public static unowned GLib.SList get_field_names_registered (string service_str); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] - public static weak string get_service_by_id (int id); + public static unowned string get_service_by_id (int id); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] - public static weak string get_service_by_mime (string mime); + public static unowned string get_service_by_mime (string mime); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] - public static weak Tracker.Service get_service_by_name (string service_str); + public static unowned Tracker.Service get_service_by_name (string service_str); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] public static Tracker.DBType get_service_db_by_name (string service_str); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] public static int get_service_id_by_name (string service_str); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] - public static weak GLib.SList get_service_names_registered (); + public static unowned GLib.SList get_service_names_registered (); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] - public static weak string get_service_parent (string service_str); + public static unowned string get_service_parent (string service_str); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] - public static weak string get_service_parent_by_id (int id); + public static unowned string get_service_parent_by_id (int id); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] public static int get_service_parent_id_by_id (int id); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] @@ -61,162 +139,18 @@ namespace Tracker { [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-ontology.h")] public static void shutdown (); } - [CCode (cprefix = "TrackerModuleConfig", lower_case_cprefix = "tracker_module_config_")] - namespace ModuleConfig { - [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] - public static weak string get_description (string name); - [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] - public static bool get_enabled (string name); - [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] - public static weak GLib.List get_ignored_directories (string name); - [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] - public static weak GLib.List get_ignored_directory_patterns (string name); - [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] - public static weak GLib.List get_ignored_file_patterns (string name); - [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] - public static weak GLib.List get_ignored_files (string name); - [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] - public static weak GLib.List get_index_file_patterns (string name); - [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] - public static weak GLib.List get_index_files (string name); - [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] - public static weak GLib.List get_index_mime_types (string name); - [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] - public static weak string get_index_service (string name); - [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] - public static weak GLib.List get_modules (); - [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] - public static weak GLib.List get_monitor_directories (string name); - [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] - public static weak GLib.List get_monitor_recurse_directories (string name); - [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] - public static bool init (); - [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-module-config.h")] - public static void shutdown (); - } - [CCode (cprefix = "TrackerModule", lower_case_cprefix = "tracker_module_")] - namespace Module { - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public delegate void FileFreeDataFunc (); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static delegate void* FileGetDataFunc (string path); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static delegate weak Tracker.Metadata FileGetMetadataFunc (Tracker.File file); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static delegate weak string FileGetServiceTypeFunc (Tracker.File file); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static delegate weak string FileGetText (Tracker.File path); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static delegate void FileGetUriFunc (Tracker.File file, string dirname, string basename); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static delegate bool FileIterContents (Tracker.File path); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static delegate weak string GetDirectoriesFunc (); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static delegate weak string GetNameFunc (); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static delegate void Init (); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static delegate void Shutdown (); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static void file_free_data (void* file_data); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static void* file_get_data (string path); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static weak Tracker.Metadata file_get_metadata (Tracker.File file); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static weak string file_get_service_type (Tracker.File file); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static weak string file_get_text (Tracker.File file); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static void file_get_uri (Tracker.File file, string dirname, string basename); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static bool file_iter_contents (Tracker.File file); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static weak string get_name (); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static void init (); - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-module.h")] - public static void shutdown (); - } - [CCode (cprefix = "TRACKER_DB_TYPE_", cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public enum DBType { - UNKNOWN, - DATA, - INDEX, - COMMON, - CONTENT, - EMAIL, - FILES, - XESAM, - CACHE, - USER - } - [CCode (cprefix = "TRACKER_FIELD_TYPE_", cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public enum FieldType { - KEYWORD, - INDEX, - FULLTEXT, - STRING, - INTEGER, - DOUBLE, - DATE, - BLOB, - STRUCT, - LINK - } - [Compact] - [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public class File { - public weak string path; - public void* data; - public static void close (int fd, bool no_longer_needed); - public static weak string get_mime_type (string uri); - public static int get_mtime (string uri); - public static void get_path_and_name (string uri, string path, string name); - public static uint get_size (string uri); - public static bool is_directory (string uri); - public static bool is_indexable (string uri); - public static bool is_valid (string uri); - public static int open (string uri, bool readahead); - public static bool unlink (string uri); - } - [Compact] - [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-metadata.h")] - public class Metadata { - public void @foreach (Tracker.MetadataForeach func); - public void insert (string field_name, string value); - public void insert_multiple_values (string field_name, GLib.List list); - public weak string lookup (string field_name); - public weak GLib.List lookup_multiple_values (string field_name); - public Metadata (); - public static weak Tracker.Metadata utils_get_data (string path); - public static weak string utils_get_text (string path); - } - [Compact] - [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public class Parser { - public bool is_stop_word (string word); - public Parser (Tracker.Language language, int max_word_length, int min_word_length); - public weak string next (int position, int byte_offset_start, int byte_offset_end, bool new_paragraph, bool stop_word, int word_length); - public weak string process_word (string word, int length, bool do_strip); - public void reset (string txt, int txt_size, bool delimit_words, bool enable_stemmer, bool enable_stop_words, bool parse_reserved_words); - public void set_posititon (int position); - public static weak GLib.HashTable text (GLib.HashTable word_table, string txt, int weight, Tracker.Language language, int max_words_to_index, int max_word_length, int min_word_length, bool filter_words, bool delimit_words); - public static weak GLib.HashTable text_fast (GLib.HashTable word_table, string txt, int weight); - public static weak string text_into_array (string text, Tracker.Language language, int max_word_length, int min_word_length); - public static weak string text_to_string (string txt, Tracker.Language language, int max_word_length, int min_word_length, bool filter_words, bool filter_numbers, bool delimit); - } [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] public class Config : GLib.Object { + [CCode (has_construct_function = false)] + public Config (); public void add_crawl_directory_roots (string roots); public void add_disabled_modules (string modules); public void add_no_watch_directory_roots (string roots); public void add_watch_directory_roots (string roots); - public weak GLib.SList get_crawl_directory_roots (); + public unowned GLib.SList get_crawl_directory_roots (); public bool get_disable_indexing_on_battery (); public bool get_disable_indexing_on_battery_init (); - public weak GLib.SList get_disabled_modules (); + public unowned GLib.SList get_disabled_modules (); public bool get_enable_content_indexing (); public bool get_enable_indexing (); public bool get_enable_stemmer (); @@ -227,7 +161,7 @@ namespace Tracker { public bool get_index_mounted_directories (); public bool get_index_removable_devices (); public int get_initial_sleep (); - public weak string get_language (); + public unowned string get_language (); public int get_low_disk_space_limit (); public bool get_low_memory_mode (); public int get_max_bucket_count (); @@ -237,12 +171,11 @@ namespace Tracker { public int get_min_bucket_count (); public int get_min_word_length (); public bool get_nfs_locking (); - public weak GLib.SList get_no_index_file_types (); - public weak GLib.SList get_no_watch_directory_roots (); + public unowned GLib.SList get_no_index_file_types (); + public unowned GLib.SList get_no_watch_directory_roots (); public int get_throttle (); public int get_verbosity (); - public weak GLib.SList get_watch_directory_roots (); - public Config (); + public unowned GLib.SList get_watch_directory_roots (); public void remove_disabled_modules (string module); public void set_disable_indexing_on_battery (bool value); public void set_disable_indexing_on_battery_init (bool value); @@ -300,19 +233,20 @@ namespace Tracker { } [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] public class Field : GLib.Object { + [CCode (has_construct_function = false)] + public Field (); public void append_child_id (string id); - public weak GLib.SList get_child_ids (); + public unowned GLib.SList get_child_ids (); public Tracker.FieldType get_data_type (); public bool get_delimited (); public bool get_embedded (); - public weak string get_field_name (); + public unowned string get_field_name (); public bool get_filtered (); - public weak string get_id (); + public unowned string get_id (); public bool get_multiple_values (); - public weak string get_name (); + public unowned string get_name (); public bool get_store_metadata (); public int get_weight (); - public Field (); public void set_child_ids (GLib.SList value); public void set_data_type (Tracker.FieldType value); public void set_delimited (bool value); @@ -324,7 +258,7 @@ namespace Tracker { public void set_name (string value); public void set_store_metadata (bool value); public void set_weight (int value); - public static weak string type_to_string (Tracker.FieldType fieldtype); + public static unowned string type_to_string (Tracker.FieldType fieldtype); public void* child_ids { get; set; } public Tracker.FieldType data_type { get; set; } public bool delimited { get; set; } @@ -337,21 +271,68 @@ namespace Tracker { public bool store_metadata { get; set; } public int weight { get; set; } } + [Compact] + [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] + public class File { + public void* data; + public weak string path; + public static void close (int fd, bool no_longer_needed); + public static unowned string get_mime_type (string uri); + public static int32 get_mtime (string uri); + public static void get_path_and_name (string uri, string path, string name); + public static uint32 get_size (string uri); + public static bool is_directory (string uri); + public static bool is_indexable (string uri); + public static bool is_valid (string uri); + public static int open (string uri, bool readahead); + public static bool unlink (string uri); + } [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] public class Language : GLib.Object { - public static bool check_exists (string language_code); - public weak Tracker.Config get_config (); - public static weak string get_default_code (); - public weak GLib.HashTable get_stop_words (); + [CCode (has_construct_function = false)] public Language (Tracker.Config language); + public static bool check_exists (string language_code); + public unowned Tracker.Config get_config (); + public static unowned string get_default_code (); + public unowned GLib.HashTable get_stop_words (); public void set_config (Tracker.Config config); - public weak string stem_word (string word, int word_length); + public unowned string stem_word (string word, int word_length); public Tracker.Config config { get; set; } public GLib.HashTable stop_words { get; } } + [Compact] + [CCode (cheader_filename = "tracker-1.0/libtracker-indexer/tracker-metadata.h")] + public class Metadata { + [CCode (has_construct_function = false)] + public Metadata (); + public void @foreach (Tracker.MetadataForeach func); + public void insert (string field_name, string value); + public void insert_multiple_values (string field_name, GLib.List list); + public unowned string lookup (string field_name); + public unowned GLib.List lookup_multiple_values (string field_name); + public static unowned Tracker.Metadata utils_get_data (string path); + public static unowned string utils_get_text (string path); + } + [Compact] + [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] + public class Parser { + [CCode (has_construct_function = false)] + public Parser (Tracker.Language language, int max_word_length, int min_word_length); + public bool is_stop_word (string word); + public unowned string next (int position, int byte_offset_start, int byte_offset_end, bool new_paragraph, bool stop_word, int word_length); + public unowned string process_word (string word, int length, bool do_strip); + public void reset (string txt, int txt_size, bool delimit_words, bool enable_stemmer, bool enable_stop_words, bool parse_reserved_words); + public void set_posititon (int position); + public static unowned GLib.HashTable text (GLib.HashTable word_table, string txt, int weight, Tracker.Language language, int max_words_to_index, int max_word_length, int min_word_length, bool filter_words, bool delimit_words); + public static unowned GLib.HashTable text_fast (GLib.HashTable word_table, string txt, int weight); + public static unowned string text_into_array (string text, Tracker.Language language, int max_word_length, int min_word_length); + public static unowned string text_to_string (string txt, Tracker.Language language, int max_word_length, int min_word_length, bool filter_words, bool filter_numbers, bool delimit); + } [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] public class Service : GLib.Object { - public weak string get_content_metadata (); + [CCode (has_construct_function = false)] + public Service (); + public unowned string get_content_metadata (); public Tracker.DBType get_db_type (); public bool get_embedded (); public bool get_enabled (); @@ -359,13 +340,12 @@ namespace Tracker { public bool get_has_metadata (); public bool get_has_thumbs (); public int get_id (); - public weak GLib.SList get_key_metadata (); - public weak string get_name (); - public weak string get_parent (); - public weak string get_property_prefix (); + public unowned GLib.SList get_key_metadata (); + public unowned string get_name (); + public unowned string get_parent (); + public unowned string get_property_prefix (); public bool get_show_service_directories (); public bool get_show_service_files (); - public Service (); public void set_content_metadata (string value); public void set_db_type (Tracker.DBType value); public void set_embedded (bool value); @@ -395,64 +375,90 @@ namespace Tracker { public bool show_service_directories { get; set; } public bool show_service_files { get; set; } } + [CCode (cprefix = "TRACKER_DB_TYPE_", cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] + public enum DBType { + UNKNOWN, + DATA, + INDEX, + COMMON, + CONTENT, + EMAIL, + FILES, + XESAM, + CACHE, + USER + } + [CCode (cprefix = "TRACKER_FIELD_TYPE_", cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] + public enum FieldType { + KEYWORD, + INDEX, + FULLTEXT, + STRING, + INTEGER, + DOUBLE, + DATE, + BLOB, + STRUCT, + LINK + } [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] public delegate void MetadataForeach (Tracker.Field field, void* value); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak string date_format (string time_string); + public static unowned string date_format (string time_string); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak string date_to_string (ulong date_time); + public static unowned string date_to_string (ulong date_time); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak string date_to_time_string (string date_string); + public static unowned string date_to_time_string (string date_string); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] public static bool env_check_xdg_dirs (); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak string escape_string (string @in); + public static unowned string escape_string (string @in); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak string gint32_to_string (int i); + public static unowned string gint32_to_string (int32 i); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak string gint_to_string (int i); + public static unowned string gint_to_string (int i); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak string glong_to_string (long i); + public static unowned string glong_to_string (long i); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak GLib.SList gslist_copy_with_string_data (GLib.SList list); + public static unowned GLib.SList gslist_copy_with_string_data (GLib.SList list); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak string gslist_to_string_list (GLib.SList list); + public static unowned string gslist_to_string_list (GLib.SList list); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak string guint32_to_string (uint i); + public static unowned string guint32_to_string (uint32 i); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak string guint_to_string (uint i); + public static unowned string guint_to_string (uint i); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] public static bool is_empty_string (string str); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak string path_evaluate_name (string uri); + public static unowned string path_evaluate_name (string uri); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] public static void path_hash_table_filter_duplicates (GLib.HashTable roots); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] public static bool path_is_in_path (string path, string in_path); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak GLib.SList path_list_filter_duplicates (GLib.SList roots); + public static unowned GLib.SList path_list_filter_duplicates (GLib.SList roots); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] public static void path_remove (string uri); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak string seconds_estimate_to_string (double seconds_elapsed, bool short_string, uint items_done, uint items_remaining); + public static unowned string seconds_estimate_to_string (double seconds_elapsed, bool short_string, uint items_done, uint items_remaining); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak string seconds_to_string (double seconds_elapsed, bool short_string); + public static unowned string seconds_to_string (double seconds_elapsed, bool short_string); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak string string_boolean_to_string_gint (string value); + public static unowned string string_boolean_to_string_gint (string value); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] public static int string_in_string_list (string str, string strv); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak GLib.SList string_list_to_gslist (string strv, ulong length); + public static unowned GLib.SList string_list_to_gslist (string strv, size_t length); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak string string_list_to_string (string strv, ulong length, char sep); + public static unowned string string_list_to_string (string strv, size_t length, char sep); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak string string_remove (string haystack, string needle); + public static unowned string string_remove (string haystack, string needle); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak string string_replace (string haystack, string needle, string replacement); + public static unowned string string_replace (string haystack, string needle, string replacement); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] public static ulong string_to_date (string time_string); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] - public static weak string string_to_string_list (string str); + public static unowned string string_to_string_list (string str); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")] public static bool string_to_uint (string s, uint ret); [CCode (cheader_filename = "tracker-1.0/libtracker-common/tracker-common.h")]
11cafee76142ef632d20bb71633bae5b980181bd
Vala
goocanvas: Correct cname of Goo.CanvasImage.create Fixes bug 612221.
c
https://github.com/GNOME/vala/
diff --git a/vapi/goocanvas.vapi b/vapi/goocanvas.vapi index bb2d49039c..8c8b051d91 100644 --- a/vapi/goocanvas.vapi +++ b/vapi/goocanvas.vapi @@ -285,7 +285,7 @@ namespace Goo { } [CCode (cheader_filename = "goocanvas.h")] public class CanvasImage : Goo.CanvasItemSimple, Goo.CanvasItem { - [CCode (cname = "goo_image_group_new")] + [CCode (cname = "goo_canvas_image_new")] public static unowned Goo.CanvasImage create (Goo.CanvasItem? parent, Gdk.Pixbuf pixbuf, double x, double y, ...); [NoAccessorMethod] public double height { get; set; } diff --git a/vapi/packages/goocanvas/goocanvas-custom.vala b/vapi/packages/goocanvas/goocanvas-custom.vala index d5f7e2c5a6..f2ee89bc1a 100644 --- a/vapi/packages/goocanvas/goocanvas-custom.vala +++ b/vapi/packages/goocanvas/goocanvas-custom.vala @@ -85,7 +85,7 @@ namespace Goo public class CanvasImage { - [CCode (cname="goo_image_group_new", type="GooCanvasItem*")] + [CCode (cname="goo_canvas_image_new", type="GooCanvasItem*")] public static weak CanvasImage create (Goo.CanvasItem? parent, Gdk.Pixbuf pixbuf, double x, double y, ...); }
bead0e770467e56136d115c64bf9ea2404813627
camel
CAMEL-1078. Fix potential NPE.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@788149 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/camel
diff --git a/components/camel-irc/src/main/java/org/apache/camel/component/irc/IrcMessage.java b/components/camel-irc/src/main/java/org/apache/camel/component/irc/IrcMessage.java index 649a91589fe8a..f8943a0df76ae 100644 --- a/components/camel-irc/src/main/java/org/apache/camel/component/irc/IrcMessage.java +++ b/components/camel-irc/src/main/java/org/apache/camel/component/irc/IrcMessage.java @@ -103,8 +103,8 @@ public void setMessage(String message) { @Override protected Object createBody() { Exchange exchange = getExchange(); - IrcBinding binding = (IrcBinding)exchange.getProperty(Exchange.BINDING); - return binding.extractBodyFromIrc(exchange, this); + IrcBinding binding = exchange != null ? (IrcBinding)exchange.getProperty(Exchange.BINDING) : null; + return binding != null ? binding.extractBodyFromIrc(exchange, this) : null; } @Override
68f61f3b3c2efaa263190519be6ebf4a02e021ad
spring-framework
Fix nested @Component annotation instantiation- bug--3.1 M2 introduced a regression that causes false positives during-@Configuration class candidate checks. Now performing a call to-AnnotationMetadata-isInterface in addition to checks for @Component and-@Bean annotations when determining whether a candidate is a 'lite'-configuration class. Annotations are in the end interfaces
c
https://github.com/spring-projects/spring-framework
diff --git a/org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassUtils.java b/org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassUtils.java index 2d192a809c94..5a909771056b 100644 --- a/org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassUtils.java +++ b/org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassUtils.java @@ -100,8 +100,9 @@ public static boolean isFullConfigurationCandidate(AnnotationMetadata metadata) } public static boolean isLiteConfigurationCandidate(AnnotationMetadata metadata) { - return metadata.isAnnotated(Component.class.getName()) || - metadata.hasAnnotatedMethods(Bean.class.getName()); + return !metadata.isInterface() && // not an interface or an annotation + (metadata.isAnnotated(Component.class.getName()) || + metadata.hasAnnotatedMethods(Bean.class.getName())); } diff --git a/org.springframework.context/src/test/java/org/springframework/context/annotation/spr8761/Spr8761Tests.java b/org.springframework.context/src/test/java/org/springframework/context/annotation/spr8761/Spr8761Tests.java new file mode 100644 index 000000000000..c37c22106cda --- /dev/null +++ b/org.springframework.context/src/test/java/org/springframework/context/annotation/spr8761/Spr8761Tests.java @@ -0,0 +1,57 @@ +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.annotation.spr8761; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +import org.junit.Test; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.stereotype.Component; + +/** + * Tests cornering the regression reported in SPR-8761. + * + * @author Chris Beams + */ +public class Spr8761Tests { + + /** + * Prior to the fix for SPR-8761, this test threw because the nested MyComponent + * annotation was being falsely considered as a 'lite' Configuration class candidate. + */ + @Test + public void repro() { + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); + ctx.scan(getClass().getPackage().getName()); + ctx.refresh(); + assertThat(ctx.containsBean("withNestedAnnotation"), is(true)); + } + +} + +@Component +class WithNestedAnnotation { + + @Retention(RetentionPolicy.RUNTIME) + @Component + public static @interface MyComponent { + } +}
18f85bef4bf10e47cc314f71c302dd3b19f6797a
Mylyn Reviews
322734: File table spans whole width
a
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java index 8c035606..52621e3e 100644 --- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java +++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java @@ -22,6 +22,7 @@ import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.resource.CompositeImageDescriptor; import org.eclipse.jface.viewers.ArrayContentProvider; +import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; @@ -32,6 +33,7 @@ import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.viewers.Viewer; @@ -97,16 +99,16 @@ public void createControl(Composite parent, FormToolkit toolkit) { new GridData(SWT.FILL, SWT.FILL, true, true)); TableViewerColumn column = new TableViewerColumn(fileList, SWT.LEFT); - column.getColumn().setText(""); - column.getColumn().setWidth(25); - column.getColumn().setResizable(false); - column = new TableViewerColumn(fileList, SWT.LEFT); column.getColumn().setText("Filename"); column.getColumn().setWidth(100); column.getColumn().setResizable(true); + + TableLayout tableLayout = new TableLayout(); + tableLayout.addColumnData(new ColumnWeightData(100, true)); + fileList.getTable().setLayout(tableLayout); + fileList.setLabelProvider(new TableLabelProvider() { - private final int COLUMN_ICON = 0; - private final int COLUMN_FILE = 1; + private final int COLUMN_FILE = 0; @Override public String getColumnText(Object element, int columnIndex) { @@ -122,7 +124,7 @@ public String getColumnText(Object element, int columnIndex) { @Override public Image getColumnImage(Object element, int columnIndex) { - if (columnIndex == COLUMN_ICON) { + if (columnIndex == COLUMN_FILE) { ISharedImages sharedImages = PlatformUI.getWorkbench() .getSharedImages(); if (element instanceof ReviewDiffModel) {
26d12f78c550e45f32e2c0fd4cf625e3fbf3b295
restlet-framework-java
Add support for template route matching mode--
a
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet.ext.osgi/src/org/restlet/ext/osgi/IResourceProvider.java b/modules/org.restlet.ext.osgi/src/org/restlet/ext/osgi/IResourceProvider.java index d901769620..605b8ee885 100644 --- a/modules/org.restlet.ext.osgi/src/org/restlet/ext/osgi/IResourceProvider.java +++ b/modules/org.restlet.ext.osgi/src/org/restlet/ext/osgi/IResourceProvider.java @@ -55,4 +55,10 @@ public interface IResourceProvider extends IRestletProvider { * paths must start with '/'. */ String[] getPaths(); + + /** + * + * @return the matching mode to be used for template routes. Defaults to Template.MODE_EQUALS. + */ + int getMatchingMode(); } diff --git a/modules/org.restlet.ext.osgi/src/org/restlet/ext/osgi/ResourceProvider.java b/modules/org.restlet.ext.osgi/src/org/restlet/ext/osgi/ResourceProvider.java index 0a264bdbf8..3161fc65f9 100644 --- a/modules/org.restlet.ext.osgi/src/org/restlet/ext/osgi/ResourceProvider.java +++ b/modules/org.restlet.ext.osgi/src/org/restlet/ext/osgi/ResourceProvider.java @@ -39,6 +39,7 @@ import org.restlet.Context; import org.restlet.Restlet; import org.restlet.resource.Finder; +import org.restlet.routing.Template; /** * @author Bryan Hunt @@ -49,11 +50,17 @@ public abstract class ResourceProvider extends RestletProvider implements private Finder finder; private String[] paths; - + + private Integer matchingMode; + protected void activate(ComponentContext context) { @SuppressWarnings("unchecked") Dictionary<String, Object> properties = context.getProperties(); paths = (String[]) properties.get("paths"); + matchingMode = (Integer) properties.get("matchingMode"); + + if (matchingMode == null) + matchingMode = Template.MODE_EQUALS; } protected abstract Finder createFinder(Context context); @@ -76,4 +83,9 @@ public Restlet getInboundRoot(Context context) { public String[] getPaths() { return paths.clone(); } + + @Override + public int getMatchingMode() { + return matchingMode; + } } diff --git a/modules/org.restlet.ext.osgi/src/org/restlet/ext/osgi/RouterProvider.java b/modules/org.restlet.ext.osgi/src/org/restlet/ext/osgi/RouterProvider.java index 0f5c5241ca..0e710ab8de 100644 --- a/modules/org.restlet.ext.osgi/src/org/restlet/ext/osgi/RouterProvider.java +++ b/modules/org.restlet.ext.osgi/src/org/restlet/ext/osgi/RouterProvider.java @@ -38,6 +38,7 @@ import org.restlet.Context; import org.restlet.Restlet; import org.restlet.routing.Router; +import org.restlet.routing.TemplateRoute; /** * @author Bryan Hunt @@ -58,9 +59,10 @@ private void attachDirectory(IDirectoryProvider directoryProvider) { } private void attachResource(IResourceProvider resourceProvider) { - for (String path : resourceProvider.getPaths()) - router.attach(path, - resourceProvider.getInboundRoot(router.getContext())); + for (String path : resourceProvider.getPaths()) { + TemplateRoute templateRoute = router.attach(path, resourceProvider.getInboundRoot(router.getContext())); + templateRoute.setMatchingMode(resourceProvider.getMatchingMode()); + } } public void bindDefaultResourceProvider(IResourceProvider resourceProvider) {
42a5292e18eb62545b7186f95963d6bc9b330d38
Vala
clutter-1.0: fix Stage.read_pixels binding Fixes bug 616448.
c
https://github.com/GNOME/vala/
diff --git a/vapi/clutter-1.0.vapi b/vapi/clutter-1.0.vapi index d7aa954b92..b093aac5bd 100644 --- a/vapi/clutter-1.0.vapi +++ b/vapi/clutter-1.0.vapi @@ -984,7 +984,8 @@ namespace Clutter { public void hide_cursor (); public bool is_default (); public void queue_redraw (); - public unowned uchar[] read_pixels (int x, int y, int width, int height); + [CCode (array_length = false)] + public uchar[] read_pixels (int x, int y, int width = -1, int height = -1); [CCode (cname = "clutter_redraw")] public void redraw (); public void set_fullscreen (bool fullscreen); diff --git a/vapi/packages/clutter-1.0/clutter-1.0.metadata b/vapi/packages/clutter-1.0/clutter-1.0.metadata index 24ea92af00..b3df426058 100644 --- a/vapi/packages/clutter-1.0/clutter-1.0.metadata +++ b/vapi/packages/clutter-1.0/clutter-1.0.metadata @@ -338,6 +338,9 @@ clutter_stage_manager_get_default_stage hidden="1" clutter_stage_manager_list_stages type_arguments="Stage" clutter_stage_manager_peek_stages type_arguments="Stage" clutter_stage_manager_set_default_stage hidden="1" +clutter_stage_read_pixels transfer_ownership="1" no_array_length="1" +clutter_stage_read_pixels.width default_value="-1" +clutter_stage_read_pixels.height default_value="-1" clutter_stage_set_key_focus.actor nullable="1" ClutterStageStateEvent is_value_type="1"
cec891510bb4cdb379d11691eaf004289a50d044
ReactiveX-RxJava
Fix the initialization of Completable.complete()- (-4146)--
c
https://github.com/ReactiveX/RxJava
diff --git a/src/main/java/rx/Completable.java b/src/main/java/rx/Completable.java index c32a0a2ea8..2f6f3cce50 100644 --- a/src/main/java/rx/Completable.java +++ b/src/main/java/rx/Completable.java @@ -93,7 +93,7 @@ public void call(CompletableSubscriber s) { s.onSubscribe(Subscriptions.unsubscribed()); s.onCompleted(); } - }, true); // hook is handled in complete() + }, false); // hook is handled in complete() /** Single instance of a never Completable. */ static final Completable NEVER = new Completable(new CompletableOnSubscribe() { @@ -101,7 +101,7 @@ public void call(CompletableSubscriber s) { public void call(CompletableSubscriber s) { s.onSubscribe(Subscriptions.unsubscribed()); } - }, true); // hook is handled in never() + }, false); // hook is handled in never() /** * Returns a Completable which terminates as soon as one of the source Completables @@ -315,7 +315,7 @@ public static Completable complete() { if (cos == COMPLETE.onSubscribe) { return COMPLETE; } - return new Completable(cos, true); + return new Completable(cos, false); } /** @@ -742,7 +742,7 @@ public static Completable never() { if (cos == NEVER.onSubscribe) { return NEVER; } - return new Completable(cos, true); + return new Completable(cos, false); } /**
135ec78d7d5854af7e5a764d4c3bb50ccf188eeb
kotlin
Fixed EA-70945--
c
https://github.com/JetBrains/kotlin
diff --git a/idea/idea-completion/testData/smart/EA70945.kt b/idea/idea-completion/testData/smart/EA70945.kt new file mode 100644 index 0000000000000..1673544f07d95 --- /dev/null +++ b/idea/idea-completion/testData/smart/EA70945.kt @@ -0,0 +1,9 @@ +class A { + val foo: Int = 0 +} + +fun f() { + A().foo(<caret>) +} + +// NUMBER: 0 diff --git a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/JvmSmartCompletionTestGenerated.java b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/JvmSmartCompletionTestGenerated.java index 0ebb61cdc50b5..c73e6aba16076 100644 --- a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/JvmSmartCompletionTestGenerated.java +++ b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/JvmSmartCompletionTestGenerated.java @@ -113,6 +113,12 @@ public void testClassObjectMembersWithPrefix() throws Exception { doTest(fileName); } + @TestMetadata("EA70945.kt") + public void testEA70945() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("idea/idea-completion/testData/smart/EA70945.kt"); + doTest(fileName); + } + @TestMetadata("EmptyPrefix.kt") public void testEmptyPrefix() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("idea/idea-completion/testData/smart/EmptyPrefix.kt"); diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ExpectedInfos.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ExpectedInfos.kt index bf4d0c2db3499..53c7991390502 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ExpectedInfos.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/ExpectedInfos.kt @@ -188,6 +188,8 @@ class ExpectedInfos( private fun calculateForArgument(callElement: KtCallElement, argument: ValueArgument): Collection<ExpectedInfo>? { val call = callElement.getCall(bindingContext) ?: return null + // sometimes we get wrong call (see testEA70945) TODO: refactor resolve so that it does not happen + if (call.callElement != callElement) return null return calculateForArgument(call, argument) }
e4e85d3facf1633ea6a058d186dfbcf75f3e3a07
Delta Spike
DELTASPIKE-315 provide common EntityManagerFactoryProducer
a
https://github.com/apache/deltaspike
diff --git a/deltaspike/modules/jpa/api/src/main/java/org/apache/deltaspike/test/jpa/api/entitymanager/PersistenceConfigurationProvider.java b/deltaspike/modules/jpa/api/src/main/java/org/apache/deltaspike/test/jpa/api/entitymanager/PersistenceConfigurationProvider.java new file mode 100644 index 000000000..ca59d9bc0 --- /dev/null +++ b/deltaspike/modules/jpa/api/src/main/java/org/apache/deltaspike/test/jpa/api/entitymanager/PersistenceConfigurationProvider.java @@ -0,0 +1,39 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.deltaspike.test.jpa.api.entitymanager; + +import java.util.Properties; + +/** + * Provide the configuration for the EntityManagerFactory + * which gets produced with a given {@link PersistenceUnitName}. + * + * By default we provide a configuration which con be configured + * differently depending on the <i>-DdatabaseVendor</i> and the + * {@link org.apache.deltaspike.core.api.projectstage.ProjectStage} + */ +public interface PersistenceConfigurationProvider +{ + + /** + * @param persistenceUnitName the name of the persistence unit in persistence.xml + * @return the additional Properties from the configuration. + */ + Properties getEntityManagerFactoryConfiguration(String persistenceUnitName); +} diff --git a/deltaspike/modules/jpa/api/src/main/java/org/apache/deltaspike/test/jpa/api/entitymanager/PersistenceUnitName.java b/deltaspike/modules/jpa/api/src/main/java/org/apache/deltaspike/test/jpa/api/entitymanager/PersistenceUnitName.java new file mode 100644 index 000000000..45e94581f --- /dev/null +++ b/deltaspike/modules/jpa/api/src/main/java/org/apache/deltaspike/test/jpa/api/entitymanager/PersistenceUnitName.java @@ -0,0 +1,48 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.deltaspike.test.jpa.api.entitymanager; + +import javax.enterprise.util.Nonbinding; +import javax.inject.Qualifier; +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.ElementType.TYPE; + +/** + * The name of the PersistenceUnit to get picked up by the + * EntityManagerFactoryProducer. + */ +@Target( { TYPE, METHOD, PARAMETER, FIELD }) +@Retention(value= RetentionPolicy.RUNTIME) +@Documented +@Qualifier +public @interface PersistenceUnitName +{ + /** + * @return the name of the persistence unit. + */ + @Nonbinding + String value(); +} diff --git a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/entitymanager/EntityManagerFactoryProducer.java b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/entitymanager/EntityManagerFactoryProducer.java new file mode 100644 index 000000000..05129f3a5 --- /dev/null +++ b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/entitymanager/EntityManagerFactoryProducer.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.deltaspike.jpa.impl.entitymanager; + +import javax.enterprise.context.Dependent; +import javax.enterprise.inject.Produces; +import javax.enterprise.inject.spi.InjectionPoint; +import javax.inject.Inject; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import java.util.Properties; +import java.util.logging.Logger; + +import org.apache.deltaspike.test.jpa.api.entitymanager.PersistenceConfigurationProvider; +import org.apache.deltaspike.test.jpa.api.entitymanager.PersistenceUnitName; + + +/** + * TODO + */ +public class EntityManagerFactoryProducer +{ + private static final Logger LOG = Logger.getLogger(EntityManagerFactoryProducer.class.getName()); + + + private @Inject PersistenceConfigurationProvider persistenceConfigurationProvider; + + + @Produces + @Dependent + @PersistenceUnitName("any") // the value is nonbinding, thus this is just a dummy parameter here + public EntityManagerFactory createEntityManagerFactoryForUnit(InjectionPoint injectionPoint) + { + PersistenceUnitName unitNameAnnotation = injectionPoint.getAnnotated().getAnnotation(PersistenceUnitName.class); + + if (unitNameAnnotation == null) + { + LOG.warning("@PersisteneUnitName annotation could not be found at EntityManagerFactory injection point!"); + + return null; + } + + String unitName = unitNameAnnotation.value(); + + Properties properties = persistenceConfigurationProvider.getEntityManagerFactoryConfiguration(unitName); + + EntityManagerFactory emf = Persistence.createEntityManagerFactory(unitName, properties); + + return emf; + } +} diff --git a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/entitymanager/PersistenceConfigurationProviderImpl.java b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/entitymanager/PersistenceConfigurationProviderImpl.java new file mode 100644 index 000000000..1271a12b8 --- /dev/null +++ b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/entitymanager/PersistenceConfigurationProviderImpl.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.deltaspike.jpa.impl.entitymanager; + +import javax.enterprise.context.ApplicationScoped; + + +import java.util.Properties; + +import org.apache.deltaspike.test.jpa.api.entitymanager.PersistenceConfigurationProvider; + +/** + * Default implementation of the PersistenceConfigurationProvider + */ +@ApplicationScoped +public class PersistenceConfigurationProviderImpl implements PersistenceConfigurationProvider +{ + @Override + public Properties getEntityManagerFactoryConfiguration(String persistenceUnitName) + { + Properties unitProperties = new Properties(); + + //X TODO fill properties + + return unitProperties; + } +} diff --git a/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/EntityManagerFactoryProducerTest.java b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/EntityManagerFactoryProducerTest.java new file mode 100644 index 000000000..62b8d032c --- /dev/null +++ b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/EntityManagerFactoryProducerTest.java @@ -0,0 +1,80 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.deltaspike.test.jpa.api.entitymanager; + +import javax.inject.Inject; +import javax.persistence.EntityManager; +import javax.persistence.spi.PersistenceProviderResolverHolder; + +import org.apache.deltaspike.test.category.SeCategory; +import org.apache.deltaspike.test.jpa.api.shared.TestEntityManager; +import org.apache.deltaspike.test.util.ArchiveUtils; +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.asset.EmptyAsset; +import org.jboss.shrinkwrap.api.asset.StringAsset; +import org.jboss.shrinkwrap.api.spec.JavaArchive; +import org.jboss.shrinkwrap.api.spec.WebArchive; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.runner.RunWith; + +@RunWith(Arquillian.class) +@Category(SeCategory.class) +public class EntityManagerFactoryProducerTest +{ + + @Deployment + public static WebArchive deploy() + { + // set the dummy PersistenceProviderResolver which creates our DummyEntityManagerFactory + PersistenceProviderResolverHolder.setPersistenceProviderResolver(new TestPersistenceProviderResolver()); + + JavaArchive testJar = ShrinkWrap.create(JavaArchive.class, "unitDefinitionTest.jar") + .addPackage(ArchiveUtils.SHARED_PACKAGE) + .addPackage(EntityManagerFactoryProducerTest.class.getPackage().getName()) + .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") + .addAsResource(new StringAsset(TestPersistenceProviderResolver.class.getName()), + "META-INF/services/javax.persistence.spi.PersistenceProviderResolver"); + + return ShrinkWrap.create(WebArchive.class) + .addAsLibraries(ArchiveUtils.getDeltaSpikeCoreAndJpaArchive()) + .addAsLibraries(testJar) + .addAsWebInfResource(ArchiveUtils.getBeansXml(), "beans.xml"); + } + + + @Inject + @SampleDb + private EntityManager entityManager; + + @Test + public void testUnitDefinitionQualifier() throws Exception + { + Assert.assertNotNull(entityManager); + Assert.assertNotNull(entityManager.getDelegate()); + + Assert.assertTrue(entityManager.getDelegate() instanceof TestEntityManager); + TestEntityManager tem = (TestEntityManager) entityManager.getDelegate(); + Assert.assertEquals("testPersistenceUnit", tem.getUnitName()); + } +} diff --git a/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/SampleDb.java b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/SampleDb.java new file mode 100644 index 000000000..6c57195e3 --- /dev/null +++ b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/SampleDb.java @@ -0,0 +1,40 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.deltaspike.test.jpa.api.entitymanager; + +import javax.inject.Qualifier; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + + +/** + * Sample Database Qualifier + */ +@Target( { TYPE, METHOD, PARAMETER, FIELD }) +@Retention(value= RUNTIME) +@Qualifier +public @interface SampleDb +{ +} diff --git a/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/SampleEntityManagerProducer.java b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/SampleEntityManagerProducer.java new file mode 100644 index 000000000..238c049a4 --- /dev/null +++ b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/SampleEntityManagerProducer.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.deltaspike.test.jpa.api.entitymanager; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.context.RequestScoped; +import javax.enterprise.inject.Disposes; +import javax.enterprise.inject.Produces; +import javax.inject.Inject; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; + +/** + * Sample producer for a &#064;SampleDb EntityManager. + */ +@ApplicationScoped +@SuppressWarnings("unused") +public class SampleEntityManagerProducer +{ + @Inject + @PersistenceUnitName("testPersistenceUnit") + private EntityManagerFactory emf; + + @Produces + @RequestScoped + @SampleDb + public EntityManager createEntityManager() + { + return emf.createEntityManager(); + } + + public void closeEm(@Disposes @SampleDb EntityManager em) + { + em.close(); + } +} diff --git a/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/TestPersistenceProviderResolver.java b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/TestPersistenceProviderResolver.java new file mode 100644 index 000000000..acd6a651f --- /dev/null +++ b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/TestPersistenceProviderResolver.java @@ -0,0 +1,159 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.deltaspike.test.jpa.api.entitymanager; + +import javax.enterprise.inject.Typed; +import javax.persistence.Cache; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceUnitUtil; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.metamodel.Metamodel; +import javax.persistence.spi.PersistenceProvider; +import javax.persistence.spi.PersistenceProviderResolver; +import javax.persistence.spi.PersistenceUnitInfo; +import javax.persistence.spi.ProviderUtil; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.deltaspike.test.jpa.api.shared.TestEntityManager; + +/** + * PersistenceProviderResolver for dummy PersistenceProviders. + */ +@Typed() +public class TestPersistenceProviderResolver implements PersistenceProviderResolver +{ + private List<PersistenceProvider> persistenceProviders; + + public TestPersistenceProviderResolver() + { + this.persistenceProviders = new ArrayList<PersistenceProvider>(); + this.persistenceProviders.add(new DummyPersistenceProvider()); + } + + @Override + public void clearCachedProviders() + { + } + + @Override + public List<PersistenceProvider> getPersistenceProviders() + { + return persistenceProviders; + } + + + @Typed() + public static class DummyPersistenceProvider implements PersistenceProvider + { + @Override + public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) + { + return new DummyEntityManagerFactory(); + } + + @Override + public EntityManagerFactory createEntityManagerFactory(String emName, Map map) + { + return new DummyEntityManagerFactory(emName, map); + } + + @Override + public ProviderUtil getProviderUtil() + { + return null; + } + } + + @Typed() + public static class DummyEntityManagerFactory implements EntityManagerFactory + { + private final String emName; + private final Map map; + + public DummyEntityManagerFactory() + { + this.emName = null; + this.map = null; + + } + + public DummyEntityManagerFactory(String emName, Map map) + { + this.emName = emName; + this.map = map; + } + + + @Override + public void close() + { + } + + @Override + public EntityManager createEntityManager() + { + return new TestEntityManager(emName); + } + + @Override + public EntityManager createEntityManager(Map map) + { + return new TestEntityManager(emName); + } + + @Override + public CriteriaBuilder getCriteriaBuilder() + { + return null; + } + + @Override + public Metamodel getMetamodel() + { + return null; + } + + @Override + public boolean isOpen() + { + return false; + } + + @Override + public Map<String, Object> getProperties() + { + return map; + } + + @Override + public Cache getCache() + { + return null; + } + + @Override + public PersistenceUnitUtil getPersistenceUnitUtil() + { + return null; + } + } +} diff --git a/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/shared/TestEntityManager.java b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/shared/TestEntityManager.java index face0a853..44654f592 100644 --- a/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/shared/TestEntityManager.java +++ b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/shared/TestEntityManager.java @@ -38,6 +38,21 @@ public class TestEntityManager implements EntityManager private boolean open = true; private boolean flushed = false; + private String unitName = null; + + public TestEntityManager() + { + } + + public TestEntityManager(String name) + { + this.unitName = name; + } + + public String getUnitName() + { + return unitName; + } @Override public void persist(Object entity) @@ -240,7 +255,7 @@ public <T> T unwrap(Class<T> cls) @Override public Object getDelegate() { - throw new IllegalStateException("not implemented"); + return this; } @Override
b0caefee80a42d6737b3a255316487b668fab104
Delta Spike
DELTASPIKE-278 add category to Message API
a
https://github.com/apache/deltaspike
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/message/Message.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/message/Message.java index 04785736a..0cf3cb64e 100644 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/message/Message.java +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/message/Message.java @@ -63,4 +63,30 @@ public interface Message extends Serializable */ String toString(MessageContext messageContext); + /** + * Renders the Message to a String, using the {@link MessageContext} + * which created the Message. + * While resolving the message we will + * first search for a messageTemplate with the given category by + * just adding a dot '.' and the category String to the + * {@link #getTemplate()}. + * If no such a template exists we will fallback to the version + * without the category String + */ + String toString(String category); + + /** + * Renders the Message to a String, using an + * arbitrary {@link MessageContext}. + * While resolving the message we will + * first search for a messageTemplate with the given category by + * just adding a dot '.' and the category String to the + * {@link #getTemplate()}. + * If no such a template exists we will fallback to the version + * without the category String + */ + String toString(MessageContext messageContext, String category); + + + } diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessage.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessage.java index 10bb4d1ec..cae0f48ee 100644 --- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessage.java +++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessage.java @@ -84,8 +84,15 @@ public Serializable[] getArguments() } + @Override public String toString() + { + return toString((String) null); + } + + @Override + public String toString(String category) { // the string construction happens in 3 phases @@ -141,11 +148,17 @@ private String markAsUnresolved(String template) @Override public String toString(MessageContext messageContext) + { + return toString(messageContext, null); + } + + @Override + public String toString(MessageContext messageContext, String category) { return messageContext.message() .template(getTemplate()) .argument(getArguments()) - .toString(); + .toString(category); }
caf2af077a3a6454cef39678564391c4abaf8eeb
spring-framework
Polish MockHttpServletRequestBuilder--
p
https://github.com/spring-projects/spring-framework
diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/TestDispatcherServlet.java b/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/TestDispatcherServlet.java index 606b3ee74d0d..5e4b18db7feb 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/TestDispatcherServlet.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/TestDispatcherServlet.java @@ -73,6 +73,8 @@ protected void service(HttpServletRequest request, HttpServletResponse response) super.service(request, response); + // TODO: add CountDownLatch to DeferredResultInterceptor and wait in request().asyncResult(..) + Object handler = getMvcResult(request).getHandler(); if (asyncManager.isConcurrentHandlingStarted() && !deferredResultInterceptor.wasInvoked) { if (!callableInterceptor.await()) { diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/request/MockHttpServletRequestBuilder.java b/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/request/MockHttpServletRequestBuilder.java index 8d31b4df85fe..c1f8521e1e5d 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/request/MockHttpServletRequestBuilder.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/request/MockHttpServletRequestBuilder.java @@ -202,6 +202,21 @@ public MockHttpServletRequestBuilder content(byte[] content) { return this; } + /** + * Set the request body as a UTF-8 String. + * + * @param content the body content + */ + public MockHttpServletRequestBuilder content(String content) { + try { + this.content = content.getBytes("UTF-8"); + } + catch (UnsupportedEncodingException e) { + // should never happen + } + return this; + } + /** * Add the given cookies to the request. Cookies are always added. * diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/result/RequestResultMatchers.java b/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/result/RequestResultMatchers.java index e9a68a350bf9..5bc401583fb1 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/result/RequestResultMatchers.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/result/RequestResultMatchers.java @@ -84,9 +84,6 @@ public void match(MvcResult result) { /** * Assert the result from asynchronous processing with the given matcher. - * This method can be used when a controller method returns {@link Callable} - * or {@link AsyncTask}. The value matched is the value returned from the - * {@code Callable} or the exception raised. */ public <T> ResultMatcher asyncResult(final Matcher<T> matcher) { return new ResultMatcher() { @@ -95,7 +92,7 @@ public void match(MvcResult result) { HttpServletRequest request = result.getRequest(); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); MatcherAssert.assertThat("Async started", request.isAsyncStarted(), equalTo(true)); - MatcherAssert.assertThat("Callable result", (T) asyncManager.getConcurrentResult(), matcher); + MatcherAssert.assertThat("Async result", (T) asyncManager.getConcurrentResult(), matcher); } }; }
ad310d60e3e1d1c6ad6495af087dc19dc8ea02f2
Mylyn Reviews
Allow multiple attachments for review
a
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/CreateReviewActionFromAttachment.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/CreateReviewActionFromAttachment.java index 1ec9d850..0b5a77ff 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/CreateReviewActionFromAttachment.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/CreateReviewActionFromAttachment.java @@ -10,6 +10,10 @@ *******************************************************************************/ package org.eclipse.mylyn.reviews.tasks.ui; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.action.Action; @@ -27,7 +31,6 @@ import org.eclipse.mylyn.reviews.tasks.core.internal.ReviewsUtil; import org.eclipse.mylyn.reviews.tasks.core.internal.TaskProperties; import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector; -import org.eclipse.mylyn.tasks.core.ITask; import org.eclipse.mylyn.tasks.core.ITaskAttachment; import org.eclipse.mylyn.tasks.core.TaskRepository; import org.eclipse.mylyn.tasks.core.data.ITaskDataManager; @@ -39,81 +42,88 @@ public class CreateReviewActionFromAttachment extends Action implements IActionDelegate { - private Attachment attachment; - private ITaskAttachment taskAttachment; + private List<ITaskAttachment> selection2; public void run(IAction action) { - if (attachment != null) { - try { - // FIXME move common creation to a subclass - TaskRepository taskRepository = taskAttachment - .getTaskRepository(); - ITaskDataManager manager = TasksUi.getTaskDataManager(); - ITask parentTask = taskAttachment.getTask(); - TaskData parentTaskData = manager.getTaskData(taskAttachment - .getTask()); - - TaskMapper initializationData = new TaskMapper(parentTaskData); - IReviewMapper taskMapper = ReviewsUiPlugin.getMapper(); - - TaskData taskData = TasksUiInternal.createTaskData( - taskRepository, initializationData, null, - new NullProgressMonitor()); - AbstractRepositoryConnector connector = TasksUiPlugin - .getConnector(taskRepository.getConnectorKind()); - - connector.getTaskDataHandler().initializeSubTaskData( - taskRepository, taskData, parentTaskData, - new NullProgressMonitor()); - - ITaskProperties taskProperties = TaskProperties.fromTaskData( - manager, taskData); - taskProperties - .setSummary("[review] " + parentTask.getSummary()); - - String reviewer = taskRepository.getUserName(); - taskProperties.setAssignedTo(reviewer); - - initTaskProperties(taskMapper, taskProperties); - - TasksUiInternal.createAndOpenNewTask(taskData); - } catch (CoreException e) { - throw new RuntimeException(e); - } + try { + // FIXME move common creation to a subclass + ITaskAttachment taskAttachment = selection2.get(0); + + TaskRepository taskRepository = taskAttachment.getTaskRepository(); + ITaskDataManager manager = TasksUi.getTaskDataManager(); + TaskData parentTaskData = manager.getTaskData(taskAttachment + .getTask()); + ITaskProperties parentTask= TaskProperties.fromTaskData(manager, parentTaskData); + + TaskMapper initializationData = new TaskMapper(parentTaskData); + IReviewMapper taskMapper = ReviewsUiPlugin.getMapper(); + + TaskData taskData = TasksUiInternal.createTaskData(taskRepository, + initializationData, null, new NullProgressMonitor()); + AbstractRepositoryConnector connector = TasksUiPlugin + .getConnector(taskRepository.getConnectorKind()); + + connector.getTaskDataHandler().initializeSubTaskData( + taskRepository, taskData, parentTaskData, + new NullProgressMonitor()); + + ITaskProperties taskProperties = TaskProperties.fromTaskData( + manager, taskData); + taskProperties.setSummary("[review] " + parentTask.getDescription()); + + String reviewer = taskRepository.getUserName(); + taskProperties.setAssignedTo(reviewer); + + initTaskProperties(taskMapper, taskProperties,parentTask); + + TasksUiInternal.createAndOpenNewTask(taskData); + } catch (CoreException e) { + throw new RuntimeException(e); } } private void initTaskProperties(IReviewMapper taskMapper, - ITaskProperties taskProperties) { + ITaskProperties taskProperties,ITaskProperties parentTask) { ReviewScope scope = new ReviewScope(); - if (attachment.isPatch()) { - scope.addScope(new PatchScopeItem(attachment)); - } else { - scope.addScope(new ResourceScopeItem(attachment)); + for (ITaskAttachment taskAttachment : selection2) { + // FIXME date from task attachment + Attachment attachment = ReviewsUtil + .findAttachment(taskAttachment.getFileName(), + taskAttachment.getAuthor().getPersonId(), + taskAttachment.getCreationDate().toString(), + parentTask); + if (attachment.isPatch()) { + scope.addScope(new PatchScopeItem(attachment)); + } else { + scope.addScope(new ResourceScopeItem(attachment)); + } } taskMapper.mapScopeToTask(scope, taskProperties); } public void selectionChanged(IAction action, ISelection selection) { - action.setEnabled(false); + action.setEnabled(true); if (selection instanceof IStructuredSelection) { + if (selection.isEmpty()) { + action.setEnabled(false); + return; + } IStructuredSelection structuredSelection = (IStructuredSelection) selection; - if (structuredSelection.size() == 1) { - if (structuredSelection.getFirstElement() instanceof ITaskAttachment) { - action.setEnabled(true); - taskAttachment = (ITaskAttachment) structuredSelection - .getFirstElement(); - ITaskProperties taskProperties = TaskProperties - .fromTaskData(TasksUi.getTaskDataManager(), - taskAttachment.getTaskAttribute() - .getTaskData()); - // FIXME date from task attachment - this.attachment = ReviewsUtil.findAttachment(taskAttachment - .getFileName(), taskAttachment.getAuthor() - .getPersonId(), taskAttachment.getCreationDate() - .toString(), taskProperties); + selection2 = new ArrayList<ITaskAttachment>(); + @SuppressWarnings("unchecked") + Iterator<ITaskAttachment> iterator = structuredSelection.iterator(); + TaskRepository taskRepository = null; + while (iterator.hasNext()) { + ITaskAttachment attachment = iterator.next(); + if (taskRepository == null) { + taskRepository = attachment.getTaskRepository(); + } else if (!taskRepository.equals(attachment + .getTaskRepository())) { + action.setEnabled(false); } + + selection2.add(attachment); } } }
b33db73c932cd41bc19b9f5018c94c673dbe23d0
spring-framework
SPR-5251: URI Templates for @InitBinder--
a
https://github.com/spring-projects/spring-framework
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvoker.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvoker.java index 45a781c2a9f9..3d4f08da0114 100644 --- a/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvoker.java +++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvoker.java @@ -280,6 +280,7 @@ private Object[] resolveInitBinderArguments(Object handler, String paramName = null; boolean paramRequired = false; String paramDefaultValue = null; + String pathVarName = null; Object[] paramAnns = methodParam.getParameterAnnotations(); for (Object paramAnn : paramAnns) { @@ -294,9 +295,13 @@ else if (ModelAttribute.class.isInstance(paramAnn)) { throw new IllegalStateException( "@ModelAttribute is not supported on @InitBinder methods: " + initBinderMethod); } + else if (PathVariable.class.isInstance(paramAnn)) { + PathVariable pathVar = (PathVariable) paramAnn; + pathVarName = pathVar.value(); + } } - if (paramName == null) { + if (paramName == null && pathVarName == null) { Object argValue = resolveCommonArgument(methodParam, webRequest); if (argValue != WebArgumentResolver.UNRESOLVED) { initBinderArgs[i] = argValue; @@ -319,6 +324,8 @@ else if (BeanUtils.isSimpleProperty(paramType)) { if (paramName != null) { initBinderArgs[i] = resolveRequestParam(paramName, paramRequired, paramDefaultValue, methodParam, webRequest, null); + } else if (pathVarName != null) { + initBinderArgs[i] = resolvePathVariable(pathVarName, methodParam, webRequest, null); } } diff --git a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java index bcf535702fd3..d234cf1efa33 100644 --- a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java +++ b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java @@ -40,7 +40,6 @@ import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.aop.interceptor.SimpleTraceInterceptor; import org.springframework.aop.support.DefaultPointcutAdvisor; -import org.springframework.beans.BeansException; import org.springframework.beans.DerivedTestBean; import org.springframework.beans.ITestBean; import org.springframework.beans.TestBean; @@ -64,7 +63,6 @@ import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @@ -798,24 +796,6 @@ protected WebApplicationContext createWebApplicationContext(WebApplicationContex } } - @Test - public void uriTemplates() throws Exception { - DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(UriTemplateController.class)); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42/bookings/21"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("test-42-21", response.getContentAsString()); - } /* * Controllers @@ -1338,15 +1318,5 @@ public void get() { } } - @Controller - public static class UriTemplateController { - - @RequestMapping("/hotels/{hotel}/bookings/{booking}") - public void handle(@PathVariable("hotel") int hotel, @PathVariable int booking, HttpServletResponse response) - throws IOException { - response.getWriter().write("test-" + hotel + "-" + booking); - } - - } } diff --git a/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/UriTemplateServletAnnotationControllerTests.java b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/UriTemplateServletAnnotationControllerTests.java new file mode 100644 index 000000000000..dcbad780a13a --- /dev/null +++ b/org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/mvc/annotation/UriTemplateServletAnnotationControllerTests.java @@ -0,0 +1,112 @@ +package org.springframework.web.servlet.mvc.annotation; + +import java.io.IOException; +import java.io.Writer; +import java.text.SimpleDateFormat; +import java.util.Date; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletResponse; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.beans.propertyeditors.CustomDateEditor; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockServletConfig; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.support.GenericWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +/** @author Arjen Poutsma */ +public class UriTemplateServletAnnotationControllerTests { + + private DispatcherServlet servlet; + + @Test + public void simple() throws Exception { + initServlet(SimpleUriTemplateController.class); + + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42/bookings/21"); + MockHttpServletResponse response = new MockHttpServletResponse(); + servlet.service(request, response); + assertEquals("test-42-21", response.getContentAsString()); + } + + @Test + public void binding() throws Exception { + initServlet(BindingUriTemplateController.class); + + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42/dates/2008-11-18"); + MockHttpServletResponse response = new MockHttpServletResponse(); + servlet.service(request, response); + assertEquals("test-42", response.getContentAsString()); + } + + private void initServlet(final Class<?> controllerclass) throws ServletException { + servlet = new DispatcherServlet() { + @Override + protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) + throws BeansException { + GenericWebApplicationContext wac = new GenericWebApplicationContext(); + wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerclass)); + wac.refresh(); + return wac; + } + }; + servlet.init(new MockServletConfig()); + } + + @Controller + public static class SimpleUriTemplateController { + + @RequestMapping("/hotels/{hotel}/bookings/{booking}") + public void handle(@PathVariable("hotel") String hotel, @PathVariable int booking, Writer writer) throws IOException { + assertEquals("Invalid path variable value", "42", hotel); + assertEquals("Invalid path variable value", 21, booking); + writer.write("test-" + hotel + "-" + booking); + } + + } + + @Controller + public static class BindingUriTemplateController { + + @InitBinder + public void initBinder(WebDataBinder binder, @PathVariable("hotel") String hotel) { + assertEquals("Invalid path variable value", "42", hotel); + binder.initBeanPropertyAccess(); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + dateFormat.setLenient(false); + binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); + } + + @RequestMapping("/hotels/{hotel}/dates/{date}") + public void handle(@PathVariable("hotel") String hotel, @PathVariable Date date, Writer writer) throws IOException { + assertEquals("Invalid path variable value", "42", hotel); + assertEquals("Invalid path variable value", new Date(108, 10, 18), date); + writer.write("test-" + hotel); + } + + } + + @Controller + @RequestMapping("/hotels/{hotel}/**") + public static class RelativePathUriTemplateController { + + @RequestMapping("/bookings/{booking}") + public void handle(@PathVariable("hotel") int hotel, @PathVariable int booking, HttpServletResponse response) + throws IOException { + response.getWriter().write("test-" + hotel + "-" + booking); + } + + } + +}
d23a54277258ea0cd8b255e85e1550de118c65ff
tapiji
Releases V0.0.2
p
https://github.com/tapiji/tapiji
diff --git a/com.essiembre.eclipse.i18n.resourcebundle/plugin.xml b/com.essiembre.eclipse.i18n.resourcebundle/plugin.xml index 77908b1c..9e48013b 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/plugin.xml +++ b/com.essiembre.eclipse.i18n.resourcebundle/plugin.xml @@ -3,7 +3,7 @@ <plugin id="com.essiembre.eclipse.i18n.resourcebundle" name="%plugin.name" - version="0.7.7" + version="0.7.8" provider-name="%plugin.provider" class="com.essiembre.eclipse.rbe.RBEPlugin"> diff --git a/org.eclipselabs.tapiji.tools.core/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.tools.core/META-INF/MANIFEST.MF index e939d4c4..9fdd0908 100644 --- a/org.eclipselabs.tapiji.tools.core/META-INF/MANIFEST.MF +++ b/org.eclipselabs.tapiji.tools.core/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: TapiJI Tools Bundle-SymbolicName: org.eclipselabs.tapiji.tools.core;singleton:=true -Bundle-Version: 0.0.1.qualifier +Bundle-Version: 0.0.2.qualifier Bundle-Activator: org.eclipselabs.tapiji.tools.core.Activator Bundle-Vendor: Vienna University of Technology Require-Bundle: org.eclipse.ui, diff --git a/org.eclipselabs.tapiji.tools.feature/feature.xml b/org.eclipselabs.tapiji.tools.feature/feature.xml index 13e86664..f185d570 100644 --- a/org.eclipselabs.tapiji.tools.feature/feature.xml +++ b/org.eclipselabs.tapiji.tools.feature/feature.xml @@ -2,7 +2,7 @@ <feature id="org.eclipselabs.tapiji.tools.feature" label="Internationalization Feature" - version="0.0.1.qualifier" + version="0.0.2.qualifier" provider-name="Vienna University of Technology" plugin="org.eclipselabs.tapiji.tools.feature" os="linux,macosx,win32"> @@ -137,27 +137,34 @@ This Agreement is governed by the laws of the State of New York and the intellec id="com.essiembre.eclipse.i18n.resourcebundle" download-size="0" install-size="0" - version="0.7.7"/> + version="0.7.8"/> <plugin id="org.eclipselabs.tapiji.tools.core" download-size="0" install-size="0" - version="0.0.0" + version="0.0.2.qualifier" unpack="false"/> <plugin id="org.eclipselabs.tapiji.tools.java" download-size="0" install-size="0" - version="0.0.0" + version="0.0.2.qualifier" unpack="false"/> <plugin id="org.eclipselabs.tapiji.translator.rbe" download-size="0" install-size="0" - version="0.0.0" + version="0.0.2.qualifier" + unpack="false"/> + + <plugin + id="org.eclipselabs.tapiji.tools.rbmanager" + download-size="0" + install-size="0" + version="0.0.2.qualifier" unpack="false"/> </feature> diff --git a/org.eclipselabs.tapiji.tools.java/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.tools.java/META-INF/MANIFEST.MF index 979bf42a..7286ce8e 100644 --- a/org.eclipselabs.tapiji.tools.java/META-INF/MANIFEST.MF +++ b/org.eclipselabs.tapiji.tools.java/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: JavaBuilderExtension Bundle-SymbolicName: org.eclipselabs.tapiji.tools.java;singleton:=true -Bundle-Version: 0.0.1.qualifier +Bundle-Version: 0.0.2.qualifier Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Require-Bundle: org.eclipse.core.resources;bundle-version="3.6.0", org.eclipse.jdt.core;bundle-version="3.6.0", diff --git a/org.eclipselabs.tapiji.tools.jsf.feature/feature.xml b/org.eclipselabs.tapiji.tools.jsf.feature/feature.xml index fc68241c..731cfe18 100644 --- a/org.eclipselabs.tapiji.tools.jsf.feature/feature.xml +++ b/org.eclipselabs.tapiji.tools.jsf.feature/feature.xml @@ -2,7 +2,7 @@ <feature id="org.eclipselabs.tapiji.tools.jsf.feature" label="JSF Internationalization Feature" - version="0.0.1.qualifier" + version="0.0.2.qualifier" provider-name="Vienna University of Technology" plugin="org.eclipselabs.tapiji.tools.jsf"> @@ -130,7 +130,7 @@ This Agreement is governed by the laws of the State of New York and the intellec id="org.eclipselabs.tapiji.tools.jsf" download-size="0" install-size="0" - version="0.0.1.qualifier" + version="0.0.2.qualifier" unpack="false"/> </feature> diff --git a/org.eclipselabs.tapiji.tools.jsf/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.tools.jsf/META-INF/MANIFEST.MF index 41ac1153..a3b8cf0a 100644 --- a/org.eclipselabs.tapiji.tools.jsf/META-INF/MANIFEST.MF +++ b/org.eclipselabs.tapiji.tools.jsf/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: JsfBuilderExtension Bundle-SymbolicName: org.eclipselabs.tapiji.tools.jsf;singleton:=true -Bundle-Version: 0.0.1.qualifier +Bundle-Version: 0.0.2.qualifier Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Require-Bundle: org.eclipse.core.resources;bundle-version="3.6.0", org.eclipse.jface, diff --git a/org.eclipselabs.tapiji.tools.rbmanager/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.tools.rbmanager/META-INF/MANIFEST.MF index b69f01c8..0549af22 100644 --- a/org.eclipselabs.tapiji.tools.rbmanager/META-INF/MANIFEST.MF +++ b/org.eclipselabs.tapiji.tools.rbmanager/META-INF/MANIFEST.MF @@ -2,14 +2,14 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: Manager Bundle-SymbolicName: org.eclipselabs.tapiji.tools.rbmanager;singleton:=true -Bundle-Version: 1.0.0.qualifier +Bundle-Version: 0.0.2.qualifier Bundle-Activator: org.eclipselabs.tapiji.tools.rbmanager.RBManagerActivator Bundle-Vendor: GKNSINTERMETALS Require-Bundle: org.eclipse.core.runtime, - org.eclipse.core.resources;bundle-version="3.6.100", + org.eclipse.core.resources;bundle-version="3.6", org.eclipse.ui, org.eclipse.ui.ide;bundle-version="3.6.0", - org.eclipse.ui.navigator;bundle-version="3.5.100", + org.eclipse.ui.navigator;bundle-version="3.5", org.eclipselabs.tapiji.tools.core;bundle-version="0.0.1" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Bundle-ActivationPolicy: lazy diff --git a/org.eclipselabs.tapiji.tools.rbmanager/build.properties b/org.eclipselabs.tapiji.tools.rbmanager/build.properties index 6f20375d..f84becc0 100644 --- a/org.eclipselabs.tapiji.tools.rbmanager/build.properties +++ b/org.eclipselabs.tapiji.tools.rbmanager/build.properties @@ -2,4 +2,11 @@ source.. = src/ output.. = bin/ bin.includes = META-INF/,\ .,\ - plugin.xml + plugin.xml,\ + bin/,\ + icons/ +src.includes = icons/,\ + src/,\ + plugin.xml,\ + bin/,\ + META-INF/ diff --git a/org.eclipselabs.tapiji.translator.rbe/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator.rbe/META-INF/MANIFEST.MF index e462b490..8b38a22f 100644 --- a/org.eclipselabs.tapiji.translator.rbe/META-INF/MANIFEST.MF +++ b/org.eclipselabs.tapiji.translator.rbe/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: ResourceBundleEditorAPI Bundle-SymbolicName: org.eclipselabs.tapiji.translator.rbe -Bundle-Version: 0.0.1.qualifier +Bundle-Version: 0.0.2.qualifier Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Export-Package: org.eclipselabs.tapiji.translator.rbe.model.analyze, org.eclipselabs.tapiji.translator.rbe.model.bundle, diff --git a/org.eclipselabs.tapiji.translator/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator/META-INF/MANIFEST.MF index 5013a625..36fd70c2 100644 --- a/org.eclipselabs.tapiji.translator/META-INF/MANIFEST.MF +++ b/org.eclipselabs.tapiji.translator/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: TapiJI Translator Bundle-SymbolicName: org.eclipselabs.tapiji.translator;singleton:=true -Bundle-Version: 0.0.1.qualifier +Bundle-Version: 0.0.2.qualifier Bundle-Activator: org.eclipselabs.tapiji.translator.Activator Require-Bundle: org.eclipse.ui, org.eclipse.core.runtime,
c0bae1256c20ddb0c76da865f2c0470fb0b1db1c
Mylyn Reviews
322734: Avoid exception, when loading non-existant local cache of review data
c
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataStore.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataStore.java index 7a8b715b..f24ad5a6 100644 --- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataStore.java +++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewDataStore.java @@ -72,6 +72,9 @@ public List<Review> loadReviewData(String repositoryUrl, String taskId) { try { File file = getFile(repositoryUrl, taskId); + if(!file.exists()) { + return reviews; + } ZipInputStream inputStream = new ZipInputStream( new FileInputStream(file)); inputStream.getNextEntry();
1e6f2e79b9e0162f8a111acbe7f2876d0d8eeebe
spring-framework
Adapted getXmlAsSource implementation to avoid- compilation failure in IntelliJ IDEA--
p
https://github.com/spring-projects/spring-framework
diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/support/xml/Jdbc4SqlXmlHandler.java b/spring-jdbc/src/main/java/org/springframework/jdbc/support/xml/Jdbc4SqlXmlHandler.java index 0234cf59b25f..247e53681467 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/support/xml/Jdbc4SqlXmlHandler.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/support/xml/Jdbc4SqlXmlHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,15 +23,15 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLXML; - import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; -import org.springframework.dao.DataAccessResourceFailureException; import org.w3c.dom.Document; +import org.springframework.dao.DataAccessResourceFailureException; + /** * Default implementation of the {@link SqlXmlHandler} interface. * Provides database-specific implementations for storing and @@ -83,12 +83,14 @@ public Reader getXmlAsCharacterStream(ResultSet rs, int columnIndex) throws SQLE @Override public Source getXmlAsSource(ResultSet rs, String columnName, Class<? extends Source> sourceClass) throws SQLException { - return rs.getSQLXML(columnName).getSource(sourceClass != null ? sourceClass : DOMSource.class); + SQLXML xmlObject = rs.getSQLXML(columnName); + return (sourceClass != null ? xmlObject.getSource(sourceClass) : xmlObject.getSource(DOMSource.class)); } @Override public Source getXmlAsSource(ResultSet rs, int columnIndex, Class<? extends Source> sourceClass) throws SQLException { - return rs.getSQLXML(columnIndex).getSource(sourceClass != null ? sourceClass : DOMSource.class); + SQLXML xmlObject = rs.getSQLXML(columnIndex); + return (sourceClass != null ? xmlObject.getSource(sourceClass) : xmlObject.getSource(DOMSource.class)); }
62c8bfade88dc4b72a07c4a0d6f6633e5d0fcdad
orientdb
Fixed issue 1198: NullPointerException in- OCommandExecutorSQLResultsetAbstract.assignTarget--
c
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java index feb3d9fac59..5be0dcec737 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java @@ -145,7 +145,7 @@ else if (parsedTarget.getTargetVariable() != null) { return true; } else if (var instanceof OIdentifiable) { final ArrayList<OIdentifiable> list = new ArrayList<OIdentifiable>(); - ((List<OIdentifiable>) target).add((OIdentifiable) var); + list.add((OIdentifiable) var); target = list.iterator(); } else if (var instanceof Iterable<?>) target = ((Iterable<? extends OIdentifiable>) var).iterator(); diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLInsertTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLInsertTest.java index 9498b38513e..c8f2826d5b1 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLInsertTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLInsertTest.java @@ -16,6 +16,7 @@ package com.orientechnologies.orient.test.database.auto; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.Map; @@ -230,6 +231,33 @@ public void insertWithNoSpaces() { database.close(); } + @Test + public void insertAvoidingSubQuery() { + database.open("admin", "admin"); + + ODocument doc = (ODocument) database.command(new OCommandSQL("INSERT INTO test(text) VALUES ('(Hello World)')")).execute(); + + Assert.assertTrue(doc != null); + Assert.assertEquals(doc.field("text"), "(Hello World)"); + + database.close(); + } + + @Test + public void insertSubQuery() { + database.open("admin", "admin"); + + ODocument doc = (ODocument) database.command(new OCommandSQL("INSERT INTO test SET names = (select name from OUser)")) + .execute(); + + Assert.assertTrue(doc != null); + Assert.assertNotNull(doc.field("names")); + Assert.assertTrue(doc.field("names") instanceof Collection); + Assert.assertEquals(((Collection<?>) doc.field("names")).size(), 3); + + database.close(); + } + @Test public void insertCluster() { database.open("admin", "admin"); @@ -274,7 +302,7 @@ private List<OClusterPosition> getValidPositions(int clusterId) { for (int i = 0; i < 100; i++) { if (!iteratorCluster.hasNext()) break; - ORecord doc = iteratorCluster.next(); + ORecord<?> doc = iteratorCluster.next(); positions.add(doc.getIdentity().getClusterPosition()); } return positions;
d9dbcbd78c093f4d7d326babab7d64262c2e0280
drools
JBRULES-340 core implementation for 'from' -The- from node is now added -ReteooBuilder is added
a
https://github.com/kiegroup/drools
diff --git a/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java b/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java index b10c07473da..f6cfd376433 100644 --- a/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java +++ b/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java @@ -95,7 +95,7 @@ public abstract class AbstractWorkingMemory protected final AgendaEventSupport agendaEventSupport = new AgendaEventSupport( this ); /** The <code>RuleBase</code> with which this memory is associated. */ - protected transient InternalRuleBase ruleBase; + protected transient InternalRuleBase ruleBase; protected final FactHandleFactory handleFactory; @@ -156,40 +156,75 @@ public AbstractWorkingMemory(final int id, void setRuleBase(InternalRuleBase ruleBase) { this.ruleBase = ruleBase; } - + public void addEventListener(final WorkingMemoryEventListener listener) { - this.workingMemoryEventSupport.addEventListener( listener ); + try { + lock.lock(); + this.workingMemoryEventSupport.addEventListener( listener ); + } finally { + lock.unlock(); + } } public void removeEventListener(final WorkingMemoryEventListener listener) { - this.workingMemoryEventSupport.removeEventListener( listener ); + try { + lock.lock(); + this.workingMemoryEventSupport.removeEventListener( listener ); + } finally { + lock.unlock(); + } } public List getWorkingMemoryEventListeners() { - return this.workingMemoryEventSupport.getEventListeners(); + try { + lock.lock(); + return this.workingMemoryEventSupport.getEventListeners(); + } finally { + lock.unlock(); + } } public void addEventListener(final AgendaEventListener listener) { - this.agendaEventSupport.addEventListener( listener ); + try { + lock.lock(); + this.agendaEventSupport.addEventListener( listener ); + } finally { + lock.unlock(); + } } public void removeEventListener(final AgendaEventListener listener) { - this.agendaEventSupport.removeEventListener( listener ); + try { + lock.lock(); + this.agendaEventSupport.removeEventListener( listener ); + } finally { + lock.unlock(); + } } - public FactHandleFactory getFactHandleFactory() { - return this.handleFactory; + public List getAgendaEventListeners() { + try { + lock.lock(); + return this.agendaEventSupport.getEventListeners(); + } finally { + lock.unlock(); + } } - public List getAgendaEventListeners() { - return this.agendaEventSupport.getEventListeners(); + public FactHandleFactory getFactHandleFactory() { + return this.handleFactory; } /** * @see WorkingMemory */ public Map getGlobals() { - return this.globals; + try { + lock.lock(); + return this.globals; + } finally { + lock.unlock(); + } } /** @@ -197,20 +232,25 @@ public Map getGlobals() { */ public void setGlobal(final String name, final Object value) { - // Make sure the global has been declared in the RuleBase - final Map globalDefintions = this.ruleBase.getGlobals(); - final Class type = (Class) globalDefintions.get( name ); - if ( (type == null) ) { - throw new RuntimeException( "Unexpected global [" + name + "]" ); - } else if ( !type.isInstance( value ) ) { - throw new RuntimeException( "Illegal class for global. " + "Expected [" + type.getName() + "], " + "found [" + value.getClass().getName() + "]." ); + try { + lock.lock(); + // Make sure the global has been declared in the RuleBase + final Map globalDefintions = this.ruleBase.getGlobals(); + final Class type = (Class) globalDefintions.get( name ); + if ( (type == null) ) { + throw new RuntimeException( "Unexpected global [" + name + "]" ); + } else if ( !type.isInstance( value ) ) { + throw new RuntimeException( "Illegal class for global. " + "Expected [" + type.getName() + "], " + "found [" + value.getClass().getName() + "]." ); - } else { - this.globals.put( name, - value ); + } else { + this.globals.put( name, + value ); + } + } finally { + lock.unlock(); } } - + public long getId() { return this.id; } @@ -219,8 +259,13 @@ public long getId() { * @see WorkingMemory */ public Object getGlobal(final String name) { - final Object object = this.globals.get( name ); - return object; + try { + lock.lock(); + final Object object = this.globals.get( name ); + return object; + } finally { + lock.unlock(); + } } /** @@ -293,14 +338,19 @@ public synchronized void fireAllRules(final AgendaFilter agendaFilter) throws Fa * */ public Object getObject(final FactHandle handle) { - // you must always take the value from the assertMap, incase the handle - // is not from this WorkingMemory - InternalFactHandle factHandle = (InternalFactHandle) this.assertMap.get( handle ); - if ( factHandle != null ) { - return factHandle.getObject(); - } + try { + lock.lock(); + // you must always take the value from the assertMap, incase the handle + // is not from this WorkingMemory + InternalFactHandle factHandle = (InternalFactHandle) this.assertMap.get( handle ); + if ( factHandle != null ) { + return factHandle.getObject(); + } - return null; + return null; + } finally { + lock.unlock(); + } } @@ -308,13 +358,23 @@ public Object getObject(final FactHandle handle) { * @see WorkingMemory */ public FactHandle getFactHandle(final Object object) { - final FactHandle factHandle = (FactHandle) this.assertMap.get( object ); + try { + lock.lock(); + final FactHandle factHandle = (FactHandle) this.assertMap.get( object ); - return factHandle; + return factHandle; + } finally { + lock.unlock(); + } } public List getFactHandles() { - return new ArrayList( this.assertMap.values() ); + try { + lock.lock(); + return new ArrayList( this.assertMap.values() ); + } finally { + lock.unlock(); + } } /** @@ -422,8 +482,8 @@ public FactHandle assertObject(final Object object, return null; } InternalFactHandle handle = null; - this.lock.lock(); try { + this.lock.lock(); // check if the object already exists in the WM handle = (InternalFactHandle) this.assertMap.get( object ); @@ -656,8 +716,8 @@ public void retractObject(final FactHandle factHandle, final boolean updateEqualsMap, final Rule rule, final Activation activation) throws FactException { - this.lock.lock(); try { + this.lock.lock(); final InternalFactHandle handle = (InternalFactHandle) factHandle; if ( handle.getId() == -1 ) { // can't retract an already retracted handle diff --git a/drools-core/src/main/java/org/drools/common/BetaNodeBinder.java b/drools-core/src/main/java/org/drools/common/BetaNodeBinder.java index 5b7ea409544..326442b2592 100644 --- a/drools-core/src/main/java/org/drools/common/BetaNodeBinder.java +++ b/drools-core/src/main/java/org/drools/common/BetaNodeBinder.java @@ -60,7 +60,7 @@ public boolean isAllowed(final InternalFactHandle handle, } for ( int i = 0; i < this.constraints.length; i++ ) { - if ( !this.constraints[i].isAllowed( handle, + if ( !this.constraints[i].isAllowed( handle.getObject(), tuple, workingMemory ) ) { return false; diff --git a/drools-core/src/main/java/org/drools/common/InstanceEqualsConstraint.java b/drools-core/src/main/java/org/drools/common/InstanceEqualsConstraint.java index 52cacdf05e9..61008d66b87 100644 --- a/drools-core/src/main/java/org/drools/common/InstanceEqualsConstraint.java +++ b/drools-core/src/main/java/org/drools/common/InstanceEqualsConstraint.java @@ -48,10 +48,10 @@ public Declaration[] getRequiredDeclarations() { return this.declarations; } - public boolean isAllowed(final InternalFactHandle handle, + public boolean isAllowed(final Object object, final Tuple tuple, final WorkingMemory workingMemory) { - return (tuple.get( this.otherColumn ).getObject() == handle.getObject()); + return (tuple.get( this.otherColumn ).getObject() == object); } public String toString() { diff --git a/drools-core/src/main/java/org/drools/common/InstanceNotEqualsConstraint.java b/drools-core/src/main/java/org/drools/common/InstanceNotEqualsConstraint.java index 89cb4eb38b5..2be1baefb7c 100644 --- a/drools-core/src/main/java/org/drools/common/InstanceNotEqualsConstraint.java +++ b/drools-core/src/main/java/org/drools/common/InstanceNotEqualsConstraint.java @@ -41,10 +41,10 @@ public Declaration[] getRequiredDeclarations() { return this.declarations; } - public boolean isAllowed(final InternalFactHandle handle, + public boolean isAllowed(final Object object, final Tuple tuple, final WorkingMemory workingMemory) { - return !(tuple.get( this.otherColumn ).getObject() == handle.getObject()); + return !(tuple.get( this.otherColumn ).getObject() == object); } public String toString() { diff --git a/drools-core/src/main/java/org/drools/leaps/AlphaMemory.java b/drools-core/src/main/java/org/drools/leaps/AlphaMemory.java index 3d2ee8ec637..ec11da7389a 100644 --- a/drools-core/src/main/java/org/drools/leaps/AlphaMemory.java +++ b/drools-core/src/main/java/org/drools/leaps/AlphaMemory.java @@ -19,7 +19,7 @@ boolean checkAlpha( final FieldConstraint alpha, final WorkingMemory workingMemory ) { Boolean ret = (Boolean) this.alphaChecks.get( factHandle ); if (ret == null) { - ret = new Boolean( alpha.isAllowed( factHandle, tuple, workingMemory ) ); + ret = new Boolean( alpha.isAllowed( factHandle.getObject(), tuple, workingMemory ) ); this.alphaChecks.put( factHandle, ret ); } diff --git a/drools-core/src/main/java/org/drools/leaps/ColumnConstraints.java b/drools-core/src/main/java/org/drools/leaps/ColumnConstraints.java index 1b3f6f03be6..99de09d18ab 100644 --- a/drools-core/src/main/java/org/drools/leaps/ColumnConstraints.java +++ b/drools-core/src/main/java/org/drools/leaps/ColumnConstraints.java @@ -85,7 +85,7 @@ public final boolean isAllowedAlpha(final InternalFactHandle factHandle, if ( this.alphaPresent ) { for ( int i = 0, length = this.alphaConstraints.length; i < length; i++ ) { // escape immediately if some condition does not match - if ( !this.alphaConstraints[i].isAllowed( factHandle, + if ( !this.alphaConstraints[i].isAllowed( factHandle.getObject(), tuple, workingMemory ) ) { return false; diff --git a/drools-core/src/main/java/org/drools/leaps/LeapsWorkingMemory.java b/drools-core/src/main/java/org/drools/leaps/LeapsWorkingMemory.java index af7d4513e68..32bee42bb93 100644 --- a/drools-core/src/main/java/org/drools/leaps/LeapsWorkingMemory.java +++ b/drools-core/src/main/java/org/drools/leaps/LeapsWorkingMemory.java @@ -71,7 +71,7 @@ class LeapsWorkingMemory extends AbstractWorkingMemory implements EventSupport, PropertyChangeListener { - private static final long serialVersionUID = -2524904474925421759L; + private static final long serialVersionUID = 320; private final Map queryResults; @@ -326,8 +326,8 @@ public void modifyObject(final FactHandle factHandle, final Object object, final Rule rule, final Activation activation) throws FactException { - this.getLock().lock(); try { + this.getLock().lock(); final PropagationContext propagationContext = new PropagationContextImpl( this.propagationIdCounter++, PropagationContext.MODIFICATION, rule, diff --git a/drools-core/src/main/java/org/drools/reteoo/AlphaNode.java b/drools-core/src/main/java/org/drools/reteoo/AlphaNode.java index 709baa87638..b65c2fd9f76 100644 --- a/drools-core/src/main/java/org/drools/reteoo/AlphaNode.java +++ b/drools-core/src/main/java/org/drools/reteoo/AlphaNode.java @@ -131,7 +131,7 @@ public void assertObject(final DefaultFactHandle handle, final PropagationContext context, final ReteooWorkingMemory workingMemory) throws FactException { final Set memory = (Set) workingMemory.getNodeMemory( this ); - if ( this.constraint.isAllowed( handle, + if ( this.constraint.isAllowed( handle.getObject(), null, workingMemory ) ) { memory.add( handle ); @@ -157,7 +157,7 @@ public void modifyObject(final DefaultFactHandle handle, final ReteooWorkingMemory workingMemory) { final Set memory = (Set) workingMemory.getNodeMemory( this ); - if ( this.constraint.isAllowed( handle, + if ( this.constraint.isAllowed( handle.getObject(), null, workingMemory ) ) { if ( memory.add( handle ) ) { diff --git a/drools-core/src/main/java/org/drools/reteoo/FromNode.java b/drools-core/src/main/java/org/drools/reteoo/FromNode.java new file mode 100644 index 00000000000..d0b263655ae --- /dev/null +++ b/drools-core/src/main/java/org/drools/reteoo/FromNode.java @@ -0,0 +1,236 @@ +package org.drools.reteoo; + +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.drools.RuleBaseConfiguration; +import org.drools.common.BetaNodeBinder; +import org.drools.common.DefaultFactHandle; +import org.drools.common.InternalFactHandle; +import org.drools.common.NodeMemory; +import org.drools.common.PropagationContextImpl; +import org.drools.rule.Declaration; +import org.drools.rule.EvalCondition; +import org.drools.rule.From; +import org.drools.spi.Constraint; +import org.drools.spi.DataProvider; +import org.drools.spi.FieldConstraint; +import org.drools.spi.PropagationContext; + +public class FromNode extends TupleSource + implements + TupleSink, + NodeMemory { + /** + * + */ + private static final long serialVersionUID = 320; + + private DataProvider dataProvider; + private TupleSource tupleSource; + private FieldConstraint[] constraints; + private BetaNodeBinder binder; + + public FromNode(final int id, + final DataProvider dataProvider, + final TupleSource tupleSource, + final FieldConstraint[] constraints, + final BetaNodeBinder binder) { + super( id ); + this.dataProvider = dataProvider; + this.tupleSource = tupleSource; + this.constraints = constraints; + if ( binder == null ) { + this.binder = new BetaNodeBinder(); + } else { + this.binder = binder; + } + } + + /** + * This method isn't as efficient as it could be, as its using the standard join node mechanisms - so everything is bidirectionally + * linked. As FactHandle's are never retracted, this relationship does not need to be maintined - but as this optimisation would + * need refactoring, I've used the standard join node mechanism for now. + * + */ + public void assertTuple(ReteTuple leftTuple, + PropagationContext context, + ReteooWorkingMemory workingMemory) { + final BetaMemory memory = (BetaMemory) workingMemory.getNodeMemory( this ); + + memory.add( workingMemory, + leftTuple ); + + for ( Iterator it = this.dataProvider.getResults( leftTuple ); it.hasNext(); ) { + Object object = it.next(); + + // First alpha node filters + boolean isAllowed = true; + for ( int i = 0, length = this.constraints.length; i < length; i++ ) { + if ( !this.constraints[i].isAllowed( object, leftTuple, workingMemory ) ) { + isAllowed = false; + break; + } + } + + if ( !isAllowed ) { + continue; + } + + final InternalFactHandle handle = workingMemory.getFactHandleFactory().newFactHandle( object ); + final ObjectMatches objectMatches = new ObjectMatches( (DefaultFactHandle) handle ); + + if ( binder.isAllowed( handle, + leftTuple, + workingMemory ) ) { + final TupleMatch tupleMatch = new TupleMatch( leftTuple, + objectMatches ); + + leftTuple.addTupleMatch( (DefaultFactHandle) handle, + tupleMatch ); + + propagateAssertTuple( new ReteTuple( leftTuple, + (DefaultFactHandle) handle ), + tupleMatch, + context, + workingMemory ); + } + } + } + + /** + * This could be made more intelligent by finding out if the modified Fact is depended upon by the requiredDeclarations. + * If it isn't then we can continue to just propagate as a normal modify, without having to retrieve and check values + * from the DataProvider. + */ + public void modifyTuple(ReteTuple leftTuple, + PropagationContext context, + ReteooWorkingMemory workingMemory) { + final BetaMemory memory = (BetaMemory) workingMemory.getNodeMemory( this ); + + // We remove the tuple as now its modified it needs to go to the top of + // the stack, which is added back in else where + memory.remove( workingMemory, + leftTuple ); + + final Map matches = leftTuple.getTupleMatches(); + + if ( matches.isEmpty() ) { + // No child propagations, so try as a new assert, will ensure the + // tuple is added to the top of the memory + assertTuple( leftTuple, + context, + workingMemory ); + } else { + // first purge the network of all future uses of the 'from' facts + for ( final Iterator it = matches.values().iterator(); it.hasNext(); ) { + final TupleMatch tupleMatch = (TupleMatch) it.next(); + workingMemory.getFactHandleFactory().destroyFactHandle( tupleMatch.getObjectMatches().getFactHandle() ); + propagateRetractTuple( tupleMatch, + context, + workingMemory ); + } + + // now all existing matches must now be cleared and the DataProvider re-processed. + leftTuple.clearTupleMatches(); + + assertTuple( leftTuple, + context, + workingMemory ); + + } + } + + public void retractTuple(ReteTuple leftTuple, + PropagationContext context, + ReteooWorkingMemory workingMemory) { + final BetaMemory memory = (BetaMemory) workingMemory.getNodeMemory( this ); + memory.remove( workingMemory, + leftTuple ); + + final Map matches = leftTuple.getTupleMatches(); + + if ( !matches.isEmpty() ) { + for ( final Iterator it = matches.values().iterator(); it.hasNext(); ) { + final TupleMatch tupleMatch = (TupleMatch) it.next(); + workingMemory.getFactHandleFactory().destroyFactHandle( tupleMatch.getObjectMatches().getFactHandle() ); + propagateRetractTuple( tupleMatch, + context, + workingMemory ); + } + } + } + + public List getPropagatedTuples(ReteooWorkingMemory workingMemory, + TupleSink sink) { + // TODO Auto-generated method stub + return null; + } + + public void attach() { + this.tupleSource.addTupleSink( this ); + } + + public void attach(ReteooWorkingMemory[] workingMemories) { + attach(); + + for ( int i = 0, length = workingMemories.length; i < length; i++ ) { + final ReteooWorkingMemory workingMemory = workingMemories[i]; + final PropagationContext propagationContext = new PropagationContextImpl( workingMemory.getNextPropagationIdCounter(), + PropagationContext.RULE_ADDITION, + null, + null ); + this.tupleSource.updateNewNode( workingMemory, + propagationContext ); + } + } + + public void remove(BaseNode node, + ReteooWorkingMemory[] workingMemories) { + getTupleSinks().remove( node ); + removeShare(); + + if ( this.sharedCount < 0 ) { + for ( int i = 0, length = workingMemories.length; i < length; i++ ) { + workingMemories[i].clearNodeMemory( this ); + } + this.tupleSource.remove( this, + workingMemories ); + } + } + + public void updateNewNode(ReteooWorkingMemory workingMemory, + PropagationContext context) { + this.attachingNewNode = true; + + final BetaMemory memory = (BetaMemory) workingMemory.getNodeMemory( this ); + + // @todo:as there is no right memory + + // for ( final Iterator it = memory.getRightObjectMemory().iterator(); it.hasNext(); ) { + // final ObjectMatches objectMatches = (ObjectMatches) it.next(); + // final DefaultFactHandle handle = objectMatches.getFactHandle(); + // for ( TupleMatch tupleMatch = objectMatches.getFirstTupleMatch(); tupleMatch != null; tupleMatch = (TupleMatch) tupleMatch.getNext() ) { + // final ReteTuple tuple = new ReteTuple( tupleMatch.getTuple(), + // handle ); + // final TupleSink sink = (TupleSink) this.tupleSinks.get( this.tupleSinks.size() - 1 ); + // if ( sink != null ) { + // tupleMatch.addJoinedTuple( tuple ); + // sink.assertTuple( tuple, + // context, + // workingMemory ); + // } else { + // throw new RuntimeException( "Possible BUG: trying to propagate an assert to a node that was the last added node" ); + // } + // } + // } + + this.attachingNewNode = false; + } + + public Object createMemory(RuleBaseConfiguration config) { + return new BetaMemory( config, + this.binder ); + } +} diff --git a/drools-core/src/main/java/org/drools/reteoo/ReteTuple.java b/drools-core/src/main/java/org/drools/reteoo/ReteTuple.java index 7a2ed20cf43..2b04de5b13d 100644 --- a/drools-core/src/main/java/org/drools/reteoo/ReteTuple.java +++ b/drools-core/src/main/java/org/drools/reteoo/ReteTuple.java @@ -203,6 +203,10 @@ public void clearLinkedTuple() { this.linkedTuples.clear(); } + public void clearTupleMatches() { + this.matches.clear(); + } + public void addTupleMatch(final DefaultFactHandle handle, final TupleMatch node) { if ( this.matches == Collections.EMPTY_MAP ) { diff --git a/drools-core/src/main/java/org/drools/reteoo/ReteooBuilder.java b/drools-core/src/main/java/org/drools/reteoo/ReteooBuilder.java index 53dd1363397..4cf8a5bb231 100644 --- a/drools-core/src/main/java/org/drools/reteoo/ReteooBuilder.java +++ b/drools-core/src/main/java/org/drools/reteoo/ReteooBuilder.java @@ -41,6 +41,7 @@ import org.drools.rule.Declaration; import org.drools.rule.EvalCondition; import org.drools.rule.Exists; +import org.drools.rule.From; import org.drools.rule.GroupElement; import org.drools.rule.InvalidPatternException; import org.drools.rule.LiteralConstraint; @@ -555,6 +556,63 @@ private TupleSource attachNode(final TupleSource candidate) { return node; } + + private void attachFrom(final TupleSource tupleSource, + final From from) { + Column column = from.getColumn(); + + // Adjusting offset in case a previous Initial-Fact was added to the network + column.adjustOffset( this.currentOffsetAdjustment ); + + final List constraints = column.getConstraints(); + + // Check if the Column is bound + if ( column.getDeclaration() != null ) { + final Declaration declaration = column.getDeclaration(); + // Add the declaration the map of previously bound declarations + this.declarations.put( declaration.getIdentifier(), + declaration ); + } + + final List predicateConstraints = new ArrayList(); + final List alphaNodeConstraints = new ArrayList(); + + for ( final Iterator it = constraints.iterator(); it.hasNext(); ) { + final Object object = it.next(); + // Check if its a declaration + if ( object instanceof Declaration ) { + final Declaration declaration = (Declaration) object; + // Add the declaration the map of previously bound declarations + this.declarations.put( declaration.getIdentifier(), + declaration ); + continue; + } + + final FieldConstraint fieldConstraint = (FieldConstraint) object; + if ( fieldConstraint instanceof LiteralConstraint ) { + alphaNodeConstraints.add( fieldConstraint ); + } else { + checkUnboundDeclarations( fieldConstraint.getRequiredDeclarations() ); + predicateConstraints.add( fieldConstraint ); + } + } + + + BetaNodeBinder binder; + + if ( !predicateConstraints.isEmpty() ) { + binder = new BetaNodeBinder( (FieldConstraint[]) predicateConstraints.toArray( new FieldConstraint[predicateConstraints.size()] ) ); + } else { + binder = new BetaNodeBinder(); + } + + FromNode node = new FromNode( id, + from.getDataProvider(), + this.tupleSource, + ( FieldConstraint[] ) alphaNodeConstraints.toArray( new FieldConstraint[ alphaNodeConstraints.size() ] ), + binder ); + + } private ObjectSource attachNode(final ObjectSource candidate) { ObjectSource node = (ObjectSource) this.attachedNodes.get( candidate ); diff --git a/drools-core/src/main/java/org/drools/reteoo/ReteooWorkingMemory.java b/drools-core/src/main/java/org/drools/reteoo/ReteooWorkingMemory.java index 6e58b189b2c..d0fc775bfb5 100644 --- a/drools-core/src/main/java/org/drools/reteoo/ReteooWorkingMemory.java +++ b/drools-core/src/main/java/org/drools/reteoo/ReteooWorkingMemory.java @@ -48,7 +48,7 @@ public class ReteooWorkingMemory extends AbstractWorkingMemory { /** * */ - private static final long serialVersionUID = -5107074490638575715L; + private static final long serialVersionUID = 320; /** * Construct. @@ -87,8 +87,8 @@ public void modifyObject(final FactHandle factHandle, final Object object, final Rule rule, final Activation activation) throws FactException { - this.lock.lock(); try { + this.lock.lock(); final int status = ((InternalFactHandle) factHandle).getEqualityKey().getStatus(); final InternalFactHandle handle = (InternalFactHandle) factHandle; final Object originalObject = handle.getObject(); diff --git a/drools-core/src/main/java/org/drools/reteoo/TerminalNode.java b/drools-core/src/main/java/org/drools/reteoo/TerminalNode.java index 1b20118858c..2d28ed3cbc9 100644 --- a/drools-core/src/main/java/org/drools/reteoo/TerminalNode.java +++ b/drools-core/src/main/java/org/drools/reteoo/TerminalNode.java @@ -52,7 +52,7 @@ final class TerminalNode extends BaseNode /** * */ - private static final long serialVersionUID = -4172639826881353001L; + private static final long serialVersionUID = 320; /** The rule to invoke upon match. */ private final Rule rule; private final TupleSource tupleSource; diff --git a/drools-core/src/main/java/org/drools/rule/AndCompositeRestriction.java b/drools-core/src/main/java/org/drools/rule/AndCompositeRestriction.java index 0c2fe45e803..1fd2668ef83 100644 --- a/drools-core/src/main/java/org/drools/rule/AndCompositeRestriction.java +++ b/drools-core/src/main/java/org/drools/rule/AndCompositeRestriction.java @@ -4,7 +4,6 @@ import java.util.Set; import org.drools.WorkingMemory; -import org.drools.common.InternalFactHandle; import org.drools.spi.Restriction; import org.drools.spi.Tuple; @@ -17,13 +16,11 @@ public AndCompositeRestriction(Restriction[] restriction) { } public boolean isAllowed(final Object object, - final InternalFactHandle handle, final Tuple tuple, final WorkingMemory workingMemory) { for ( int i = 0, ilength = this.restrictions.length; i < ilength; i++ ) { if ( !restrictions[i].isAllowed( object, - handle, tuple, workingMemory ) ) { return false; diff --git a/drools-core/src/main/java/org/drools/rule/Column.java b/drools-core/src/main/java/org/drools/rule/Column.java index 6358c5140aa..e05f550552b 100644 --- a/drools-core/src/main/java/org/drools/rule/Column.java +++ b/drools-core/src/main/java/org/drools/rule/Column.java @@ -33,7 +33,7 @@ public class Column /** * */ - private static final long serialVersionUID = 9167552040211010022L; + private static final long serialVersionUID = 320; private final ObjectType objectType; private List constraints = Collections.EMPTY_LIST; final Declaration declaration; diff --git a/drools-core/src/main/java/org/drools/rule/From.java b/drools-core/src/main/java/org/drools/rule/From.java new file mode 100644 index 00000000000..1d34d086dc5 --- /dev/null +++ b/drools-core/src/main/java/org/drools/rule/From.java @@ -0,0 +1,25 @@ +package org.drools.rule; + +import java.io.Serializable; + +import org.drools.spi.DataProvider; + +public class From implements Serializable{ + private Column column; + + private DataProvider dataProvider; + + public From(final Column column, + final DataProvider dataProvider) { + this.column = column; + this.dataProvider = dataProvider; + } + + public Column getColumn() { + return column; + } + + public DataProvider getDataProvider() { + return dataProvider; + } +} diff --git a/drools-core/src/main/java/org/drools/rule/LiteralConstraint.java b/drools-core/src/main/java/org/drools/rule/LiteralConstraint.java index 8091b853a65..e84e1abea08 100644 --- a/drools-core/src/main/java/org/drools/rule/LiteralConstraint.java +++ b/drools-core/src/main/java/org/drools/rule/LiteralConstraint.java @@ -17,7 +17,6 @@ */ import org.drools.WorkingMemory; -import org.drools.common.InternalFactHandle; import org.drools.spi.Evaluator; import org.drools.spi.FieldConstraint; import org.drools.spi.FieldExtractor; @@ -71,10 +70,10 @@ public Declaration[] getRequiredDeclarations() { return this.restriction.getRequiredDeclarations(); } - public boolean isAllowed(final InternalFactHandle handle, + public boolean isAllowed(final Object object, final Tuple tuple, final WorkingMemory workingMemory) { - return this.restriction.isAllowed( this.extractor.getValue( handle.getObject() ), handle, tuple, workingMemory ); + return this.restriction.isAllowed( this.extractor.getValue( object ), tuple, workingMemory ); } public String toString() { diff --git a/drools-core/src/main/java/org/drools/rule/LiteralRestriction.java b/drools-core/src/main/java/org/drools/rule/LiteralRestriction.java index 5e2f85db22b..c422d889941 100644 --- a/drools-core/src/main/java/org/drools/rule/LiteralRestriction.java +++ b/drools-core/src/main/java/org/drools/rule/LiteralRestriction.java @@ -17,7 +17,6 @@ */ import org.drools.WorkingMemory; -import org.drools.common.InternalFactHandle; import org.drools.spi.Evaluator; import org.drools.spi.FieldConstraint; import org.drools.spi.FieldExtractor; @@ -64,7 +63,6 @@ public Declaration[] getRequiredDeclarations() { } public boolean isAllowed(final Object object, - final InternalFactHandle handle, final Tuple tuple, final WorkingMemory workingMemory) { return this.evaluator.evaluate( object, diff --git a/drools-core/src/main/java/org/drools/rule/MultiRestrictionFieldConstraint.java b/drools-core/src/main/java/org/drools/rule/MultiRestrictionFieldConstraint.java index 143690164fd..ddca8293c45 100644 --- a/drools-core/src/main/java/org/drools/rule/MultiRestrictionFieldConstraint.java +++ b/drools-core/src/main/java/org/drools/rule/MultiRestrictionFieldConstraint.java @@ -4,7 +4,6 @@ import java.util.Set; import org.drools.WorkingMemory; -import org.drools.common.InternalFactHandle; import org.drools.spi.Evaluator; import org.drools.spi.Extractor; import org.drools.spi.FieldConstraint; @@ -40,11 +39,10 @@ public Declaration[] getRequiredDeclarations() { return this.restrictions.getRequiredDeclarations(); } - public boolean isAllowed(final InternalFactHandle handle, + public boolean isAllowed(final Object object, final Tuple tuple, final WorkingMemory workingMemory) { - return this.restrictions.isAllowed( this.extractor.getValue( handle.getObject() ), - handle, + return this.restrictions.isAllowed( this.extractor.getValue( object ), tuple, workingMemory ); } diff --git a/drools-core/src/main/java/org/drools/rule/OrCompositeRestriction.java b/drools-core/src/main/java/org/drools/rule/OrCompositeRestriction.java index 56fb080a103..6f8e19f36bb 100644 --- a/drools-core/src/main/java/org/drools/rule/OrCompositeRestriction.java +++ b/drools-core/src/main/java/org/drools/rule/OrCompositeRestriction.java @@ -5,7 +5,6 @@ import java.util.Set; import org.drools.WorkingMemory; -import org.drools.common.InternalFactHandle; import org.drools.spi.Restriction; import org.drools.spi.Tuple; @@ -18,13 +17,11 @@ public OrCompositeRestriction(Restriction[] restriction) { } public boolean isAllowed(final Object object, - final InternalFactHandle handle, final Tuple tuple, final WorkingMemory workingMemory) { for ( int i = 0, ilength = this.restrictions.length; i < ilength; i++ ) { if ( restrictions[i].isAllowed( object, - handle, tuple, workingMemory ) ) { return true; diff --git a/drools-core/src/main/java/org/drools/rule/PredicateConstraint.java b/drools-core/src/main/java/org/drools/rule/PredicateConstraint.java index ea108f33a21..a0e5e40bf93 100644 --- a/drools-core/src/main/java/org/drools/rule/PredicateConstraint.java +++ b/drools-core/src/main/java/org/drools/rule/PredicateConstraint.java @@ -18,7 +18,6 @@ import org.drools.RuntimeDroolsException; import org.drools.WorkingMemory; -import org.drools.common.InternalFactHandle; import org.drools.spi.FieldConstraint; import org.drools.spi.PredicateExpression; import org.drools.spi.Tuple; @@ -85,12 +84,12 @@ public String toString() { return "[PredicateConstraint declarations=" + this.requiredDeclarations + "]"; } - public boolean isAllowed(final InternalFactHandle handle, + public boolean isAllowed(final Object object, final Tuple tuple, final WorkingMemory workingMemory) { try { - return this.expression.evaluate( tuple, - handle, + return this.expression.evaluate( object, + tuple, this.declaration, this.requiredDeclarations, workingMemory ); diff --git a/drools-core/src/main/java/org/drools/rule/ReturnValueConstraint.java b/drools-core/src/main/java/org/drools/rule/ReturnValueConstraint.java index 66ab234668a..26fe31fc289 100644 --- a/drools-core/src/main/java/org/drools/rule/ReturnValueConstraint.java +++ b/drools-core/src/main/java/org/drools/rule/ReturnValueConstraint.java @@ -18,7 +18,6 @@ import org.drools.RuntimeDroolsException; import org.drools.WorkingMemory; -import org.drools.common.InternalFactHandle; import org.drools.spi.Evaluator; import org.drools.spi.FieldConstraint; import org.drools.spi.FieldExtractor; @@ -77,11 +76,10 @@ public Evaluator getEvaluator() { return this.restriction.getEvaluator(); } - public boolean isAllowed(final InternalFactHandle handle, + public boolean isAllowed(final Object object, final Tuple tuple, final WorkingMemory workingMemory) { - return this.restriction.isAllowed( this.fieldExtractor.getValue( handle.getObject() ), - handle, + return this.restriction.isAllowed( this.fieldExtractor.getValue( object ), tuple, workingMemory ); } diff --git a/drools-core/src/main/java/org/drools/rule/ReturnValueRestriction.java b/drools-core/src/main/java/org/drools/rule/ReturnValueRestriction.java index bf37691e79c..53f23a2e946 100644 --- a/drools-core/src/main/java/org/drools/rule/ReturnValueRestriction.java +++ b/drools-core/src/main/java/org/drools/rule/ReturnValueRestriction.java @@ -20,7 +20,6 @@ import org.drools.RuntimeDroolsException; import org.drools.WorkingMemory; -import org.drools.common.InternalFactHandle; import org.drools.spi.Evaluator; import org.drools.spi.FieldConstraint; import org.drools.spi.FieldExtractor; @@ -93,7 +92,6 @@ public Evaluator getEvaluator() { } public boolean isAllowed(final Object object, - final InternalFactHandle handle, final Tuple tuple, final WorkingMemory workingMemory) { try { diff --git a/drools-core/src/main/java/org/drools/rule/VariableConstraint.java b/drools-core/src/main/java/org/drools/rule/VariableConstraint.java index d8acc9e768e..6b138d7b516 100644 --- a/drools-core/src/main/java/org/drools/rule/VariableConstraint.java +++ b/drools-core/src/main/java/org/drools/rule/VariableConstraint.java @@ -17,7 +17,6 @@ */ import org.drools.WorkingMemory; -import org.drools.common.InternalFactHandle; import org.drools.spi.Evaluator; import org.drools.spi.FieldConstraint; import org.drools.spi.FieldExtractor; @@ -61,11 +60,10 @@ public Evaluator getEvaluator() { return this.restriction.getEvaluator(); } - public boolean isAllowed(final InternalFactHandle handle, + public boolean isAllowed(final Object object, final Tuple tuple, final WorkingMemory workingMemory) { - return this.restriction.isAllowed( this.fieldExtractor.getValue( handle.getObject() ), - handle, + return this.restriction.isAllowed( this.fieldExtractor.getValue( object ), tuple, workingMemory ); } diff --git a/drools-core/src/main/java/org/drools/rule/VariableRestriction.java b/drools-core/src/main/java/org/drools/rule/VariableRestriction.java index 574e18bae04..483c7e36b6f 100644 --- a/drools-core/src/main/java/org/drools/rule/VariableRestriction.java +++ b/drools-core/src/main/java/org/drools/rule/VariableRestriction.java @@ -19,7 +19,6 @@ import java.util.Arrays; import org.drools.WorkingMemory; -import org.drools.common.InternalFactHandle; import org.drools.spi.Evaluator; import org.drools.spi.FieldConstraint; import org.drools.spi.FieldExtractor; @@ -57,7 +56,6 @@ public Evaluator getEvaluator() { } public boolean isAllowed(final Object object, - final InternalFactHandle handle, final Tuple tuple, final WorkingMemory workingMemory) { return this.evaluator.evaluate( object, diff --git a/drools-core/src/main/java/org/drools/spi/DataProvider.java b/drools-core/src/main/java/org/drools/spi/DataProvider.java new file mode 100644 index 00000000000..d8ec24c4eb1 --- /dev/null +++ b/drools-core/src/main/java/org/drools/spi/DataProvider.java @@ -0,0 +1,13 @@ +package org.drools.spi; + +import java.util.Iterator; +import java.util.List; + +import org.drools.rule.Declaration; + +public interface DataProvider { + + public Declaration[] getRequiredDeclarations(); + + public Iterator getResults(Tuple tuple); +} diff --git a/drools-core/src/main/java/org/drools/spi/FieldConstraint.java b/drools-core/src/main/java/org/drools/spi/FieldConstraint.java index db3b3bb67e2..b6382ce41a8 100644 --- a/drools-core/src/main/java/org/drools/spi/FieldConstraint.java +++ b/drools-core/src/main/java/org/drools/spi/FieldConstraint.java @@ -17,13 +17,12 @@ */ import org.drools.WorkingMemory; -import org.drools.common.InternalFactHandle; import org.drools.rule.Declaration; public interface FieldConstraint extends Constraint { - public boolean isAllowed(InternalFactHandle handle, + public boolean isAllowed(Object object, Tuple tuple, WorkingMemory workingMemory); diff --git a/drools-core/src/main/java/org/drools/spi/PredicateExpression.java b/drools-core/src/main/java/org/drools/spi/PredicateExpression.java index 32b43c48525..e1b420a2bea 100644 --- a/drools-core/src/main/java/org/drools/spi/PredicateExpression.java +++ b/drools-core/src/main/java/org/drools/spi/PredicateExpression.java @@ -23,8 +23,8 @@ public interface PredicateExpression extends Invoker { - public boolean evaluate(Tuple tuple, - FactHandle factHandle, + public boolean evaluate(Object object, + Tuple tuple, Declaration declaration, Declaration[] requiredDeclarations, WorkingMemory workingMemory) throws Exception; diff --git a/drools-core/src/main/java/org/drools/spi/Restriction.java b/drools-core/src/main/java/org/drools/spi/Restriction.java index 5a8db16e415..e90b1681c7e 100644 --- a/drools-core/src/main/java/org/drools/spi/Restriction.java +++ b/drools-core/src/main/java/org/drools/spi/Restriction.java @@ -3,14 +3,12 @@ import java.io.Serializable; import org.drools.WorkingMemory; -import org.drools.common.InternalFactHandle; import org.drools.rule.Declaration; public interface Restriction extends Serializable { Declaration[] getRequiredDeclarations(); public boolean isAllowed(Object object, - InternalFactHandle handle, Tuple tuple, WorkingMemory workingMemory); } diff --git a/drools-core/src/test/java/org/drools/reteoo/FromNodeTest.java b/drools-core/src/test/java/org/drools/reteoo/FromNodeTest.java new file mode 100644 index 00000000000..f97eafda904 --- /dev/null +++ b/drools-core/src/test/java/org/drools/reteoo/FromNodeTest.java @@ -0,0 +1,423 @@ +package org.drools.reteoo; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; + +import org.drools.Cheese; +import org.drools.FactHandle; +import org.drools.RuleBaseFactory; +import org.drools.base.ClassFieldExtractor; +import org.drools.base.ClassObjectType; +import org.drools.base.ValueType; +import org.drools.base.evaluators.Operator; +import org.drools.common.DefaultFactHandle; +import org.drools.common.InternalFactHandle; +import org.drools.common.PropagationContextImpl; +import org.drools.rule.Column; +import org.drools.rule.Declaration; +import org.drools.rule.From; +import org.drools.rule.LiteralConstraint; +import org.drools.rule.VariableConstraint; +import org.drools.spi.DataProvider; +import org.drools.spi.Evaluator; +import org.drools.spi.FieldConstraint; +import org.drools.spi.FieldValue; +import org.drools.spi.MockField; +import org.drools.spi.PropagationContext; +import org.drools.spi.Tuple; + +import junit.framework.TestCase; + +public class FromNodeTest extends TestCase { + + public void testAlphaNode() { + final PropagationContext context = new PropagationContextImpl( 0, + PropagationContext.ASSERTION, + null, + null ); + final ReteooWorkingMemory workingMemory = new ReteooWorkingMemory( 1, + (ReteooRuleBase) RuleBaseFactory.newRuleBase() ); + final ClassFieldExtractor extractor = new ClassFieldExtractor( Cheese.class, + "type" ); + + final FieldValue field = new MockField( "stilton" ); + final LiteralConstraint constraint = new LiteralConstraint( extractor, + ValueType.STRING_TYPE.getEvaluator( Operator.EQUAL ), + field ); + + List list = new ArrayList(); + Cheese cheese1 = new Cheese( "cheddar", + 20 ); + Cheese cheese2 = new Cheese( "brie", + 20 ); + list.add( cheese1 ); + list.add( cheese2 ); + MockDataProvider dataProvider = new MockDataProvider( list ); + + FromNode from = new FromNode( 3, + dataProvider, + null, + new FieldConstraint[]{constraint}, + null ); + MockTupleSink sink = new MockTupleSink( 5 ); + from.addTupleSink( sink ); + + Person person1 = new Person( "xxx1", + 30 ); + FactHandle person1Handle = workingMemory.assertObject( person1 ); + ReteTuple tuple1 = new ReteTuple( (DefaultFactHandle) person1Handle ); + from.assertTuple( tuple1, + context, + workingMemory ); + + // nothing should be asserted, as cheese1 is cheddar and we are filtering on stilton + assertEquals( 0, + sink.getAsserted().size() ); + + //Set cheese1 to stilton and it should now propagate + cheese1.setType( "stilton" ); + Person person2 = new Person( "xxx2", + 30 ); + FactHandle person2Handle = workingMemory.assertObject( person2 ); + ReteTuple tuple2 = new ReteTuple( (DefaultFactHandle) person2Handle ); + from.assertTuple( tuple2, + context, + workingMemory ); + + List asserted = sink.getAsserted(); + assertEquals( 1, + asserted.size() ); + ReteTuple tuple = (ReteTuple) ((Object[]) asserted.get( 0 ))[0]; + assertSame( person2, + tuple.getFactHandles()[0].getObject() ); + assertSame( cheese1, + tuple.getFactHandles()[1].getObject() ); + + cheese2.setType( "stilton" ); + Person person3 = new Person( "xxx2", + 30 ); + FactHandle person3Handle = workingMemory.assertObject( person3 ); + ReteTuple tuple3 = new ReteTuple( (DefaultFactHandle) person3Handle ); + from.assertTuple( tuple3, + context, + workingMemory ); + + assertEquals( 3, + asserted.size() ); + tuple = (ReteTuple) ((Object[]) asserted.get( 1 ))[0]; + assertSame( person3, + tuple.getFactHandles()[0].getObject() ); + assertSame( cheese1, + tuple.getFactHandles()[1].getObject() ); + tuple = (ReteTuple) ((Object[]) asserted.get( 2 ))[0]; + assertSame( person3, + tuple.getFactHandles()[0].getObject() ); + assertSame( cheese2, + tuple.getFactHandles()[1].getObject() ); + + assertNotSame( cheese1, + cheese2 ); + } + + public void testBetaNode() { + final PropagationContext context = new PropagationContextImpl( 0, + PropagationContext.ASSERTION, + null, + null ); + + final ReteooWorkingMemory workingMemory = new ReteooWorkingMemory( 1, + (ReteooRuleBase) RuleBaseFactory.newRuleBase() ); + + final ClassFieldExtractor priceExtractor = new ClassFieldExtractor( Cheese.class, + "price" ); + + final ClassFieldExtractor ageExtractor = new ClassFieldExtractor( Person.class, + "age" ); + + Declaration declaration = new Declaration( "age", + ageExtractor, + 0 ); + + VariableConstraint variableConstraint = new VariableConstraint( priceExtractor, + declaration, + ValueType.INTEGER_TYPE.getEvaluator( Operator.EQUAL ) ); + + List list = new ArrayList(); + Cheese cheese1 = new Cheese( "cheddar", + 18 ); + Cheese cheese2 = new Cheese( "brie", + 12 ); + list.add( cheese1 ); + list.add( cheese2 ); + MockDataProvider dataProvider = new MockDataProvider( list ); + + FromNode from = new FromNode( 3, + dataProvider, + null, + new FieldConstraint[]{variableConstraint}, + null ); + MockTupleSink sink = new MockTupleSink( 5 ); + from.addTupleSink( sink ); + + Person person1 = new Person( "xxx1", + 30 ); + FactHandle person1Handle = workingMemory.assertObject( person1 ); + ReteTuple tuple1 = new ReteTuple( (DefaultFactHandle) person1Handle ); + from.assertTuple( tuple1, + context, + workingMemory ); + + // nothing should be asserted, as cheese1 is cheddar and we are filtering on stilton + assertEquals( 0, + sink.getAsserted().size() ); + + //Set cheese1 to stilton and it should now propagate + cheese1.setPrice( 30 ); + Person person2 = new Person( "xxx2", + 30 ); + FactHandle person2Handle = workingMemory.assertObject( person2 ); + ReteTuple tuple2 = new ReteTuple( (DefaultFactHandle) person2Handle ); + from.assertTuple( tuple2, + context, + workingMemory ); + + List asserted = sink.getAsserted(); + assertEquals( 1, + asserted.size() ); + ReteTuple tuple = (ReteTuple) ((Object[]) asserted.get( 0 ))[0]; + assertSame( person2, + tuple.getFactHandles()[0].getObject() ); + assertSame( cheese1, + tuple.getFactHandles()[1].getObject() ); + + cheese2.setPrice( 30 ); + Person person3 = new Person( "xxx2", + 30 ); + FactHandle person3Handle = workingMemory.assertObject( person3 ); + ReteTuple tuple3 = new ReteTuple( (DefaultFactHandle) person3Handle ); + from.assertTuple( tuple3, + context, + workingMemory ); + + assertEquals( 3, + asserted.size() ); + tuple = (ReteTuple) ((Object[]) asserted.get( 1 ))[0]; + assertSame( person3, + tuple.getFactHandles()[0].getObject() ); + assertSame( cheese1, + tuple.getFactHandles()[1].getObject() ); + tuple = (ReteTuple) ((Object[]) asserted.get( 2 ))[0]; + assertSame( person3, + tuple.getFactHandles()[0].getObject() ); + assertSame( cheese2, + tuple.getFactHandles()[1].getObject() ); + + assertNotSame( cheese1, + cheese2 ); + } + + public void testRestract() { + final PropagationContext context = new PropagationContextImpl( 0, + PropagationContext.ASSERTION, + null, + null ); + final ReteooWorkingMemory workingMemory = new ReteooWorkingMemory( 1, + (ReteooRuleBase) RuleBaseFactory.newRuleBase() ); + final ClassFieldExtractor extractor = new ClassFieldExtractor( Cheese.class, + "type" ); + + final FieldValue field = new MockField( "stilton" ); + final LiteralConstraint constraint = new LiteralConstraint( extractor, + ValueType.STRING_TYPE.getEvaluator( Operator.EQUAL ), + field ); + + List list = new ArrayList(); + Cheese cheese1 = new Cheese( "stilton", + 5 ); + Cheese cheese2 = new Cheese( "stilton", + 15 ); + list.add( cheese1 ); + list.add( cheese2 ); + MockDataProvider dataProvider = new MockDataProvider( list ); + + FromNode from = new FromNode( 3, + dataProvider, + null, + new FieldConstraint[]{constraint}, + null ); + MockTupleSink sink = new MockTupleSink( 5 ); + from.addTupleSink( sink ); + + List asserted = sink.getAsserted(); + + Person person1 = new Person( "xxx2", + 30 ); + FactHandle person1Handle = workingMemory.assertObject( person1 ); + ReteTuple tuple = new ReteTuple( (DefaultFactHandle) person1Handle ); + from.assertTuple( tuple, + context, + workingMemory ); + + assertEquals( 2, + asserted.size() ); + + BetaMemory memory = (BetaMemory) workingMemory.getNodeMemory( from ); + assertEquals( 1, + memory.getLeftTupleMemory().size() ); + assertEquals( 0, + memory.getRightObjectMemory().size() ); + assertEquals( 2, + tuple.getTupleMatches().size() ); + + list = new ArrayList(); + for ( Iterator it = tuple.getTupleMatches().values().iterator(); it.hasNext(); ) { + TupleMatch tupleMatch = (TupleMatch) it.next(); + list.add( tupleMatch.getObjectMatches().getFactHandle().getObject() ); + } + assertEquals( 2, + list.size() ); + assertTrue( list.contains( cheese1 ) ); + assertTrue( list.contains( cheese2 ) ); + + from.retractTuple( tuple, + context, + workingMemory ); + assertEquals( 0, + memory.getLeftTupleMemory().size() ); + assertEquals( 0, + memory.getRightObjectMemory().size() ); + } + + public void testModify() { + final PropagationContext context = new PropagationContextImpl( 0, + PropagationContext.ASSERTION, + null, + null ); + final ReteooWorkingMemory workingMemory = new ReteooWorkingMemory( 1, + (ReteooRuleBase) RuleBaseFactory.newRuleBase() ); + final ClassFieldExtractor extractor = new ClassFieldExtractor( Cheese.class, + "type" ); + + final FieldValue field = new MockField( "stilton" ); + final LiteralConstraint constraint = new LiteralConstraint( extractor, + ValueType.STRING_TYPE.getEvaluator( Operator.EQUAL ), + field ); + + List list = new ArrayList(); + Cheese cheese1 = new Cheese( "cheddar", + 20 ); + Cheese cheese2 = new Cheese( "brie", + 20 ); + list.add( cheese1 ); + list.add( cheese2 ); + MockDataProvider dataProvider = new MockDataProvider( list ); + + FromNode from = new FromNode( 3, + dataProvider, + null, + new FieldConstraint[]{constraint}, + null ); + MockTupleSink sink = new MockTupleSink( 5 ); + from.addTupleSink( sink ); + + Person person1 = new Person( "xxx1", + 30 ); + FactHandle person1Handle = workingMemory.assertObject( person1 ); + ReteTuple tuple1 = new ReteTuple( (DefaultFactHandle) person1Handle ); + from.assertTuple( tuple1, + context, + workingMemory ); + + // nothing should be asserted, as cheese1 is cheddar and we are filtering on stilton + assertEquals( 0, + sink.getAsserted().size() ); + + //Set cheese1 to stilton and it should now propagate + cheese1.setType( "stilton" ); + from.modifyTuple( tuple1, + context, + workingMemory ); + List asserted = sink.getAsserted(); + assertEquals( 1, + asserted.size() ); + ReteTuple tuple = (ReteTuple) ((Object[]) asserted.get( 0 ))[0]; + assertSame( person1, + tuple.getFactHandles()[0].getObject() ); + assertSame( cheese1, + tuple.getFactHandles()[1].getObject() ); + + cheese2.setType( "stilton" ); + from.modifyTuple( tuple1, + context, + workingMemory ); + + // A modify when using from involves a retract and an assert - so make sure there was a retraction and no modify propagations + assertEquals( 0 , sink.getModified().size() ); + assertEquals( 1, sink.getRetracted().size() ); + + assertEquals( 3, + asserted.size() ); + tuple = (ReteTuple) ((Object[]) asserted.get( 1 ))[0]; + assertSame( person1, + tuple.getFactHandles()[0].getObject() ); + assertSame( cheese1, + tuple.getFactHandles()[1].getObject() ); + + tuple = (ReteTuple) ((Object[]) asserted.get( 2 ))[0]; + assertSame( person1, + tuple.getFactHandles()[0].getObject() ); + assertSame( cheese2, + tuple.getFactHandles()[1].getObject() ); + + // Double check the nodes memory + BetaMemory memory = (BetaMemory) workingMemory.getNodeMemory( from ); + assertEquals( 1, + memory.getLeftTupleMemory().size() ); + assertEquals( 0, + memory.getRightObjectMemory().size() ); + assertEquals( 2, + tuple1.getTupleMatches().size() ); + } + + public static class MockDataProvider + implements + DataProvider { + + private Collection collection; + + public Declaration[] getRequiredDeclarations() { + return null; + } + + public MockDataProvider(Collection collection) { + this.collection = collection; + } + + public Iterator getResults(Tuple tuple) { + return this.collection.iterator(); + } + } + + public static class Person { + private String name; + private int age; + + public Person(String name, + int age) { + super(); + this.name = name; + this.age = age; + } + + public int getAge() { + return age; + } + + public String getName() { + return name; + } + } +} diff --git a/drools-core/src/test/java/org/drools/reteoo/MockTupleSource.java b/drools-core/src/test/java/org/drools/reteoo/MockTupleSource.java index 4a7f82b6189..2d0b59099d4 100644 --- a/drools-core/src/test/java/org/drools/reteoo/MockTupleSource.java +++ b/drools-core/src/test/java/org/drools/reteoo/MockTupleSource.java @@ -38,7 +38,6 @@ public MockTupleSource(final int id) { public void attach() { this.attached++; - } public int getAttached() { diff --git a/drools-core/src/test/java/org/drools/rule/FieldConstraintTest.java b/drools-core/src/test/java/org/drools/rule/FieldConstraintTest.java index 0e7eafd6cb4..bdba597c349 100644 --- a/drools-core/src/test/java/org/drools/rule/FieldConstraintTest.java +++ b/drools-core/src/test/java/org/drools/rule/FieldConstraintTest.java @@ -78,7 +78,7 @@ public void testLiteralConstraint() throws IntrospectionException { final InternalFactHandle cheddarHandle = (InternalFactHandle) workingMemory.assertObject( cheddar ); // check constraint - assertTrue( constraint.isAllowed( cheddarHandle, + assertTrue( constraint.isAllowed( cheddarHandle.getObject(), null, workingMemory ) ); @@ -88,7 +88,7 @@ public void testLiteralConstraint() throws IntrospectionException { final InternalFactHandle stiltonHandle = (InternalFactHandle) workingMemory.assertObject( stilton ); // check constraint - assertFalse( constraint.isAllowed( stiltonHandle, + assertFalse( constraint.isAllowed( stiltonHandle.getObject(), null, workingMemory ) ); } @@ -131,13 +131,13 @@ public void testPredicateConstraint() throws IntrospectionException { */ private static final long serialVersionUID = -7805842671538257493L; - public boolean evaluate(Tuple tuple, - FactHandle factHandle, + public boolean evaluate(Object object, + Tuple tuple, Declaration declaration, Declaration[] declarations, WorkingMemory workingMemory) { int price1 = ((Integer) declarations[0].getValue( workingMemory.getObject( tuple.get( declarations[0] ) ) )).intValue(); - int price2 = ((Integer) declaration.getValue( workingMemory.getObject( factHandle ) )).intValue(); + int price2 = ((Integer) declaration.getValue( object )).intValue(); return (price2 == (price1 * 2)); @@ -160,7 +160,7 @@ public boolean evaluate(Tuple tuple, tuple = new InstrumentedReteTuple( tuple, f1 ); - assertTrue( constraint1.isAllowed( f1, + assertTrue( constraint1.isAllowed( f1.getObject(), tuple, workingMemory ) ); } @@ -228,11 +228,11 @@ public Object evaluate(Tuple tuple, // ?price tuple = new InstrumentedReteTuple( tuple, f1 ); - assertTrue( constraint1.isAllowed( f1, + assertTrue( constraint1.isAllowed( f1.getObject(), tuple, workingMemory ) ); - assertFalse( constraint2.isAllowed( f1, + assertFalse( constraint2.isAllowed( f1.getObject(), tuple, workingMemory ) ); @@ -241,7 +241,7 @@ public Object evaluate(Tuple tuple, // ?price final InternalFactHandle f2 = (InternalFactHandle) workingMemory.assertObject( cheddar2 ); - assertTrue( constraint2.isAllowed( f2, + assertTrue( constraint2.isAllowed( f2.getObject(), tuple, workingMemory ) ); } diff --git a/drools-core/src/test/java/org/drools/spi/MockConstraint.java b/drools-core/src/test/java/org/drools/spi/MockConstraint.java index c9fd203b045..7cc2f2a23e6 100644 --- a/drools-core/src/test/java/org/drools/spi/MockConstraint.java +++ b/drools-core/src/test/java/org/drools/spi/MockConstraint.java @@ -17,7 +17,6 @@ */ import org.drools.WorkingMemory; -import org.drools.common.InternalFactHandle; import org.drools.rule.Declaration; public class MockConstraint @@ -33,7 +32,7 @@ public class MockConstraint public boolean isAllowed = true; - public boolean isAllowed(final InternalFactHandle handle, + public boolean isAllowed(final Object object, final Tuple tuple, final WorkingMemory workingMemory) { return this.isAllowed;
bfb2bf6246c48caaca6926e9cba6fae052242939
restlet-framework-java
JAX-RS extension: - added to changes.txt
a
https://github.com/restlet/restlet-framework-java
diff --git a/build/tmpl/text/changes.txt b/build/tmpl/text/changes.txt index 31944d2089..0dfb6fac68 100644 --- a/build/tmpl/text/changes.txt +++ b/build/tmpl/text/changes.txt @@ -19,6 +19,8 @@ Changes log Ricard. - Misc - Updated Db4O to version 7.4.58. + - API Enhancements + - Updated to JAX-RS API 0.11 - 1.1 Release candidate 1 (08/20/2008) - Breaking change - The logger names used by Restlet have been fully refactored diff --git a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/JaxRsRestlet.java b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/JaxRsRestlet.java index 7748f95fc5..3eb1d1abb0 100644 --- a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/JaxRsRestlet.java +++ b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/JaxRsRestlet.java @@ -45,6 +45,7 @@ import java.util.List; import java.util.Set; +import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MultivaluedMap; @@ -393,8 +394,6 @@ private ResObjAndMeth requestMatching() throws RequestHandledException, return method; } - // FIXME neues: sortierkreterium explizite RegExp vor ohne (=String) - /** * Identifies the root resource class, see JAX-RS-Spec (2008-04-16), section * 3.7.2 "Request Matching", Part 1: "Identify the root resource class" @@ -738,7 +737,7 @@ private Representation convertToRepresentation(Object entity, methodAnnotations = EMPTY_ANNOTATION_ARRAY; if (entity instanceof GenericEntity) { - GenericEntity<?> genericEntity = (GenericEntity) entity; + GenericEntity<?> genericEntity = (GenericEntity<?>) entity; genericReturnType = genericEntity.getType(); entityClass = genericEntity.getRawType(); entity = genericEntity.getEntity(); @@ -749,44 +748,39 @@ private Representation convertToRepresentation(Object entity, else genericReturnType = null; if (genericReturnType instanceof Class - && ((Class) genericReturnType) + && ((Class<?>) genericReturnType) .isAssignableFrom(javax.ws.rs.core.Response.class)) { genericReturnType = entityClass; } } - MessageBodyWriterSubSet mbws; + final MultivaluedMap<String, Object> httpResponseHeaders = new WrappedRequestForHttpHeaders( + tlContext.get().getResponse(), jaxRsRespHeaders); + final Representation repr; + if (entity != null) { + final MediaType respMediaType = determineMediaType( + jaxRsResponseMediaType, resourceMethod, entityClass, + genericReturnType); + + final MessageBodyWriterSubSet mbws; mbws = providers.writerSubSet(entityClass, genericReturnType); if (mbws.isEmpty()) throw excHandler.noMessageBodyWriter(entityClass, genericReturnType, methodAnnotations, null, null); - } else { - mbws = MessageBodyWriterSubSet.empty(); - } - final MediaType respMediaType; - if (jaxRsResponseMediaType != null) - respMediaType = jaxRsResponseMediaType; - else if (resourceMethod != null) - respMediaType = determineMediaType(resourceMethod, mbws); - else - respMediaType = MediaType.TEXT_PLAIN; - final Response response = tlContext.get().getResponse(); - MultivaluedMap<String, Object> httpResponseHeaders = new WrappedRequestForHttpHeaders( - response, jaxRsRespHeaders); - final Representation repr; - if (entity == null) { - repr = Representation.createEmpty(); - repr.setMediaType(respMediaType); - } else { - final MessageBodyWriter mbw; - mbw = mbws.getBestWriter(respMediaType, accMediaTypes); + + final MessageBodyWriter mbw = mbws.getBestWriter(respMediaType, + methodAnnotations, accMediaTypes); if (mbw == null) throw excHandler.noMessageBodyWriter(entityClass, genericReturnType, methodAnnotations, respMediaType, accMediaTypes); repr = new JaxRsOutputRepresentation(entity, genericReturnType, respMediaType, methodAnnotations, mbw, httpResponseHeaders); + } else { // entity == null + repr = Representation.createEmpty(); + repr.setMediaType(determineMediaType(jaxRsResponseMediaType, + resourceMethod, entityClass, genericReturnType)); } repr.setCharacterSet(getSupportedCharSet(httpResponseHeaders)); return repr; @@ -796,26 +790,42 @@ else if (resourceMethod != null) * Determines the MediaType for a response, see JAX-RS-Spec (2008-08-27), * section 3.8 "Determining the MediaType of Responses" * + * @param jaxRsResponseMediaType * @param resourceMethod * The ResourceMethod that created the entity. + * @param entityClass + * needed, if neither the resource method nor the resource + * class is annotated with &#64;{@link Produces}. + * @param genericReturnType + * needed, if neither the resource method nor the resource + * class is annotated with &#64;{@link Produces}. + * @param methodAnnotation + * needed, if neither the resource method nor the resource + * class is annotated with &#64;{@link Produces}. * @param mbws * The {@link MessageBodyWriter}s, that support the class of - * the returned entity object. - * @return the determined {@link MediaType} - * @throws RequestHandledException + * the returned entity object as generic type of the + * {@link MessageBodyWriter}. + * @return the determined {@link MediaType}. If no method is given, + * "text/plain" is returned. * @throws WebApplicationException */ - private MediaType determineMediaType(ResourceMethod resourceMethod, - MessageBodyWriterSubSet mbws) throws WebApplicationException { + private MediaType determineMediaType(MediaType jaxRsResponseMediaType, + ResourceMethod resourceMethod, Class<?> entityClass, + Type genericReturnType) throws WebApplicationException { // 1. if the Response contains a MediaType, use it. - // TODO wenn MediaType in Response enthalten, nimm den + if (jaxRsResponseMediaType != null) + return jaxRsResponseMediaType; + if (resourceMethod == null) + return MediaType.TEXT_PLAIN; CallContext callContext = tlContext.get(); // 2. Gather the set of producible media types P: // (a) + (b) Collection<MediaType> p = resourceMethod.getProducedMimes(); // 2. (c) if (p.isEmpty()) { - p = mbws.getAllProducibleMediaTypes(); + p = providers.writerSubSet(entityClass, genericReturnType) + .getAllProducibleMediaTypes(); // 3. if (p.isEmpty()) // '*/*', in conjunction with 8.: diff --git a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/core/CallContext.java b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/core/CallContext.java index ad43c7cf46..5ea28a2e5d 100644 --- a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/core/CallContext.java +++ b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/core/CallContext.java @@ -26,8 +26,15 @@ */ package org.restlet.ext.jaxrs.internal.core; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Reader; +import java.io.Writer; import java.net.URI; import java.net.URISyntaxException; +import java.nio.channels.ReadableByteChannel; +import java.nio.channels.WritableByteChannel; import java.security.Principal; import java.util.ArrayList; import java.util.Arrays; @@ -64,11 +71,9 @@ import org.restlet.data.ChallengeResponse; import org.restlet.data.ChallengeScheme; import org.restlet.data.CharacterSet; -import org.restlet.data.Conditions; import org.restlet.data.Dimension; import org.restlet.data.Form; import org.restlet.data.Language; -import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.data.Request; import org.restlet.data.Status; @@ -339,18 +344,6 @@ protected void checkChangeable() throws IllegalStateException { } } - private boolean checkIfOneMatch(List<Tag> requestETags, Tag entityTag) { - if (entityTag.isWeak()) { - return false; - } - for (final Tag requestETag : requestETags) { - if (entityTag.equals(requestETag)) { - return true; - } - } - return false; - } - /** * Creates an unmodifiable List of {@link PathSegment}s. * @@ -425,8 +418,82 @@ public boolean equals(Object anotherObject) { * @see javax.ws.rs.core.Request#evaluatePreconditions(java.util.Date) */ public ResponseBuilder evaluatePreconditions(Date lastModified) { - // TODO throw IllegalArgumentException if null - return evaluatePreconditions(lastModified, null); + if (lastModified == null) { + throw new IllegalArgumentException( + "The last modification date must not be null"); + } + return evaluatePreconditionsInternal(lastModified, null); + } + + /** + * Evaluates the preconditions of the current request against the given last + * modified date and / or the given entity tag. This method does not check, + * if the arguments are not null. + * + * @param lastModified + * @param entityTag + * @return + * @see Request#evaluateConditions(Tag, Date) + */ + private ResponseBuilder evaluatePreconditionsInternal( + final Date lastModified, final EntityTag entityTag) { + // Status status = this.request.getConditions().getStatus( + // this.request.getMethod(), true, + // Converter.toRestletTag(entityTag), lastModified); + Status status = this.request.getConditions().getStatus( + this.request.getMethod(), new Representation() { + // this anonymous class is a temporary solution + // see commented code above + @Override + public Tag getTag() { + return Converter.toRestletTag(entityTag); + } + + @Override + public Date getModificationDate() { + return lastModified; + } + + @Override + public ReadableByteChannel getChannel() throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public Reader getReader() throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public InputStream getStream() throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public void write(OutputStream outputStream) { + throw new UnsupportedOperationException(); + } + + @Override + public void write(WritableByteChannel writableChannel) { + throw new UnsupportedOperationException(); + } + + @Override + public void write(Writer writer) throws IOException { + throw new UnsupportedOperationException(); + } + }); + if (status == null) + return null; + if (status.equals(Status.REDIRECTION_NOT_MODIFIED)) { + final ResponseBuilder rb = Response.notModified(); + rb.lastModified(lastModified); + rb.tag(entityTag); + return rb; + } else { + return Response.status(STATUS_PREC_FAILED); + } } /** @@ -465,76 +532,15 @@ public ResponseBuilder evaluatePreconditions(Date lastModified) { */ public ResponseBuilder evaluatePreconditions(Date lastModified, EntityTag entityTag) { - // TODO throw IllegalArgumentException if null - // NICE Vorbed. werden mit Conditions.getStatus() unterstuetzt. - if ((lastModified == null) && (entityTag == null)) { - return null; - } - ResponseBuilder rb = null; - final Method requestMethod = this.request.getMethod(); - final Conditions conditions = this.request.getConditions(); - if (lastModified != null) { - // Header "If-Modified-Since" - final Date modSinceCond = conditions.getModifiedSince(); - if (modSinceCond != null) { - if (modSinceCond.after(lastModified)) { - // the Entity was not changed - final boolean readRequest = requestMethod - .equals(Method.GET) - || requestMethod.equals(Method.HEAD); - if (readRequest) { - rb = Response.notModified(); - rb.lastModified(lastModified); - rb.tag(entityTag); - } else { - return precFailed("The entity was not modified since " - + Util.formatDate(modSinceCond, false)); - } - } else { - // entity was changed -> check for other precoditions - } - } - // Header "If-Unmodified-Since" - final Date unmodSinceCond = conditions.getUnmodifiedSince(); - if (unmodSinceCond != null) { - if (unmodSinceCond.after(lastModified)) { - // entity was not changed -> Web Service must recalculate it - return null; - } else { - // the Entity was changed - return precFailed("The entity was modified since " - + Util.formatDate(unmodSinceCond, false)); - } - } + if (lastModified == null) { + throw new IllegalArgumentException( + "The last modification date must not be null"); } - if (entityTag != null) { - final Tag actualEntityTag = Converter.toRestletTag(entityTag); - // Header "If-Match" - final List<Tag> requestMatchETags = conditions.getMatch(); - if (!requestMatchETags.isEmpty()) { - final boolean match = checkIfOneMatch(requestMatchETags, - actualEntityTag); - if (!match) { - return precFailed("The entity does not match Entity Tag " - + entityTag); - } - } else { - // default answer to the request - } - // Header "If-None-Match" - final List<Tag> requestNoneMatchETags = conditions.getNoneMatch(); - if (!requestNoneMatchETags.isEmpty()) { - final boolean match = checkIfOneMatch(requestNoneMatchETags, - actualEntityTag); - if (match) { - return precFailed("The entity matches Entity Tag " - + entityTag); - } - } else { - // default answer to the request - } + if (entityTag == null) { + throw new IllegalArgumentException( + "The entity tag must not be null"); } - return rb; + return evaluatePreconditionsInternal(lastModified, entityTag); } /** @@ -554,8 +560,11 @@ public ResponseBuilder evaluatePreconditions(Date lastModified, * @see javax.ws.rs.core.Request#evaluatePreconditions(javax.ws.rs.core.EntityTag) */ public ResponseBuilder evaluatePreconditions(EntityTag entityTag) { - // TODO throw IllegalArgumentException if null - return evaluatePreconditions(null, entityTag); + if (entityTag == null) { + throw new IllegalArgumentException( + "The entity tag must not be null"); + } + return evaluatePreconditionsInternal(null, entityTag); } /** @@ -1196,23 +1205,6 @@ public Iterator<String> pathSegementEncIter(PathParam pathParam) { throw new NotYetImplementedException(); } - /** - * Creates a response with status 412 (Precondition Failed). - * - * @param entityMessage - * Plain Text error message. Will be returned as entity. - * @return Returns a response with status 412 (Precondition Failed) and the - * given message as entity. - */ - private ResponseBuilder precFailed(String entityMessage) { - final ResponseBuilder rb = Response.status(STATUS_PREC_FAILED); - rb.entity(entityMessage); - rb.language(Language.ENGLISH.getName()); - rb.type(Converter.toJaxRsMediaType( - org.restlet.data.MediaType.TEXT_PLAIN, null)); - return rb; - } - /** * Select the representation variant that best matches the request. More * explicit variants are chosen ahead of less explicit ones. A vary header diff --git a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/core/JaxRsUriBuilder.java b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/core/JaxRsUriBuilder.java index b867137924..632a5fa75a 100644 --- a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/core/JaxRsUriBuilder.java +++ b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/core/JaxRsUriBuilder.java @@ -216,7 +216,7 @@ public URI buildFromEncoded(Object... values) @Override public URI buildFromEncodedMap(Map<String, ? extends Object> values) throws IllegalArgumentException, UriBuilderException { - return this.buildFromMap(values, true); + return this.buildFromMap(values, false); } /** @@ -225,7 +225,7 @@ public URI buildFromEncodedMap(Map<String, ? extends Object> values) @Override public URI buildFromMap(Map<String, ? extends Object> values) throws IllegalArgumentException, UriBuilderException { - return this.buildFromMap(values, false); + return this.buildFromMap(values, true); } /** @@ -236,6 +236,8 @@ public URI buildFromMap(Map<String, ? extends Object> values) * * @param values * a map of URI template parameter names and values + * @param encode + * true, if the value should be encoded, or false if not. * @return the URI built from the UriBuilder * @throws IllegalArgumentException * if automatic encoding is disabled and a supplied value @@ -247,7 +249,7 @@ public URI buildFromMap(Map<String, ? extends Object> values) * @see javax.ws.rs.core.UriBuilder#build(java.util.Map) */ private URI buildFromMap(final Map<String, ? extends Object> values, - final boolean encoded) throws IllegalArgumentException, + final boolean encode) throws IllegalArgumentException, UriBuilderException { final Template template = new Template(toStringWithCheck(false)); return buildUri(template.format(new Resolver<String>() { @@ -259,7 +261,7 @@ public String resolve(String variableName) { "The value Map must contain a value for all given Templet variables. The value for variable " + variableName + " is missing"); } - return EncodeOrCheck.all(varValue.toString(), encoded); + return EncodeOrCheck.all(varValue.toString(), encode); } })); } diff --git a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/todo/Notizen.java b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/todo/Notizen.java index 04472b0a2b..79c202c301 100644 --- a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/todo/Notizen.java +++ b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/todo/Notizen.java @@ -39,8 +39,6 @@ public class Notizen { // TESTEN do not decode @FormParam, @MatrixParam, @QueryParam // TESTEN do not encode keys of Form entity - // TODO status 500 instead of 406, if no message body writer could be found - // REQUEST could the implementation see, what is required to add // after precondition evaluating into the ResponseBuilder diff --git a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/util/AlgorithmUtil.java b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/util/AlgorithmUtil.java index 61287c6055..86c4310c87 100644 --- a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/util/AlgorithmUtil.java +++ b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/util/AlgorithmUtil.java @@ -283,7 +283,7 @@ private static List<MediaType> getConsOrProdMimes( * <li>the number of capturing groups as a secondary key (descending * order),</li> * <li>the number of capturing groups with non-default regular expressions - * (i.e. not "([ˆ/]+?)") as the tertiary key (descending order), and </li> + * (i.e. not "([^/]+?)") as the tertiary key (descending order), and </li> * <li>the source of each member as quaternary key sorting those derived * from T<sub>method</sub> ahead of those derived from T<sub>locator</sub>.</li> * </ol> diff --git a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/util/EncodeOrCheck.java b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/util/EncodeOrCheck.java index fe2b89737a..8eb84ee9cd 100644 --- a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/util/EncodeOrCheck.java +++ b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/util/EncodeOrCheck.java @@ -84,7 +84,7 @@ public class EncodeOrCheck { * Checks / encodes all chars of the given char sequence. * * @param string - * @param encode + * @param encode true, if the value should be encoded, or false if not. * @return * @throws IllegalArgumentException * if encode is false and at least one character of the @@ -673,7 +673,7 @@ public static void toHex(char toEncode, StringBuilder stb) { * * @param c * @param stb - * @param encode + * @param encode true, if the value should be encoded, or false if not. * @throws IllegalArgumentException */ private static void toHexOrReject(char c, StringBuilder stb, boolean encode) diff --git a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/util/ExceptionHandler.java b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/util/ExceptionHandler.java index 2cb25c5bc1..79c987a168 100644 --- a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/util/ExceptionHandler.java +++ b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/util/ExceptionHandler.java @@ -237,7 +237,7 @@ public WebApplicationException noMessageBodyWriter( annotations.toString(); // LATER log also annotations // NICE get as parameters the accMediaTypes and the entityClass. // and return supported MediaTypes as entity - throw new WebApplicationException(Status.NOT_ACCEPTABLE); + throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR); } /** diff --git a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/util/Util.java b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/util/Util.java index 5d63b6871a..bd9921be90 100644 --- a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/util/Util.java +++ b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/util/Util.java @@ -35,11 +35,13 @@ import java.lang.reflect.AccessibleObject; import java.lang.reflect.Array; import java.lang.reflect.Field; +import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; import java.nio.charset.Charset; import java.security.AccessController; import java.security.PrivilegedAction; @@ -74,10 +76,12 @@ import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnClassException; import org.restlet.ext.jaxrs.internal.exceptions.IllegalPathOnMethodException; +import org.restlet.ext.jaxrs.internal.exceptions.ImplementationException; import org.restlet.ext.jaxrs.internal.exceptions.InjectException; import org.restlet.ext.jaxrs.internal.exceptions.JaxRsRuntimeException; import org.restlet.ext.jaxrs.internal.exceptions.MethodInvokeException; import org.restlet.ext.jaxrs.internal.exceptions.MissingAnnotationException; +import org.restlet.ext.jaxrs.internal.provider.JaxbElementProvider; import org.restlet.resource.Representation; import org.restlet.util.DateUtils; import org.restlet.util.Engine; @@ -621,14 +625,26 @@ public static <K, V> V getFirstValue(Map<K, V> map) */ public static Class<?> getGenericClass(Class<?> clazz, Class<?> implInterface) { - for (Type genericType : clazz.getGenericInterfaces()) { - if (!(genericType instanceof ParameterizedType)) { + return getGenericClass(clazz, implInterface, null); + } + + private static Class<?> getGenericClass(Class<?> clazz, + Class<?> implInterface, Type[] gsatp) { + if(clazz.equals(JaxbElementProvider.class)) { + clazz.toString(); + } + else if(clazz.equals(MultivaluedMap.class)) { + clazz.toString(); + } + for (Type ifGenericType : clazz.getGenericInterfaces()) { + if (!(ifGenericType instanceof ParameterizedType)) { continue; } - final ParameterizedType pt = (ParameterizedType) genericType; + final ParameterizedType pt = (ParameterizedType) ifGenericType; if (!pt.getRawType().equals(implInterface)) continue; - final Type atp = pt.getActualTypeArguments()[0]; + final Type[] atps = pt.getActualTypeArguments(); + final Type atp = atps[0]; if (atp instanceof Class) { return (Class<?>) atp; } @@ -638,10 +654,95 @@ public static Class<?> getGenericClass(Class<?> clazz, return (Class<?>) rawType; } } + if (atp instanceof TypeVariable<?>) { + TypeVariable<?> tv = (TypeVariable<?>) atp; + String name = tv.getName(); + // clazz = AbstractProvider + // implInterface = MessageBodyReader + // name = "T" + // pt = MessageBodyReader<T> + for (int i = 0; i < atps.length; i++) { + TypeVariable<?> tv2 = (TypeVariable<?>)atps[i]; + if (tv2.getName().equals(name)) { + Type gsatpn = gsatp[i]; + if(gsatpn instanceof Class) { + return (Class<?>)gsatpn; + } + if(gsatpn instanceof ParameterizedType) { + final Type rawType = ((ParameterizedType)gsatpn).getRawType(); + if(rawType instanceof Class) + return (Class<?>)rawType; + throw new ImplementationException("Sorry, don't know how to return the class here"); + } + if(gsatpn instanceof GenericArrayType) { + Type genCompType = ((GenericArrayType)gsatpn).getGenericComponentType(); + return getArrayClass(genCompType, gsatpn); + } + //if(gsatpn instanceof TypeVariable) { + // TypeVariable<Class<?>> tvn = (TypeVariable)gsatpn; + // Class<?> cl = tvn.getGenericDeclaration(); + // Type[] boulds = tvn.getBounds(); + // cl.toString(); + //} + // throw new ImplementationException("Sorry, could not handle a "+gsatpn.getClass()); + } + } + } } + Class<?> superClass = clazz.getSuperclass(); + Type genericSuperClass = clazz.getGenericSuperclass(); + if(genericSuperClass instanceof Class) { + return null; + } + if(gsatp == null) { + // LATER this is a hack + gsatp = ((ParameterizedType) genericSuperClass) + .getActualTypeArguments(); + } + if (superClass != null) + return getGenericClass(superClass, implInterface, gsatp); return null; } + /** + * @param genCompType + * @param forMessage + * @throws NegativeArraySizeException + * @throws ImplementationException + */ + private static Class<?> getArrayClass(Type genCompType, Type forMessage) + throws NegativeArraySizeException, ImplementationException { + if(genCompType.equals(Byte.TYPE)) { + return (new byte[0]).getClass(); + } + if(genCompType.equals(Short.TYPE)) { + return (new short[0]).getClass(); + } + if(genCompType.equals(Integer.TYPE)) { + return (new int[0]).getClass(); + } + if(genCompType.equals(Long.TYPE)) { + return (new long[0]).getClass(); + } + if(genCompType.equals(Float.TYPE)) { + return (new float[0]).getClass(); + } + if(genCompType.equals(Double.TYPE)) { + return (new double[0]).getClass(); + } + if(genCompType.equals(Character.TYPE)) { + return (new char[0]).getClass(); + } + if(genCompType.equals(Boolean.TYPE)) { + return (new boolean[0]).getClass(); + } + if(genCompType instanceof Class) { + return Array.newInstance((Class<?>)genCompType, 0).getClass(); + } + throw new ImplementationException("Sorry, could not handle a "+forMessage.getClass()); + // LATER could not handle all classes + } + /** * Example: in List&lt;String&lt; -&gt; out: String.class * diff --git a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/AbstractProviderWrapper.java b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/AbstractProviderWrapper.java index 2a07d4f79e..74b4ac4141 100644 --- a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/AbstractProviderWrapper.java +++ b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/AbstractProviderWrapper.java @@ -37,6 +37,7 @@ import org.restlet.data.MediaType; import org.restlet.ext.jaxrs.internal.util.Converter; +import org.restlet.ext.jaxrs.internal.util.Util; import org.restlet.ext.jaxrs.internal.wrappers.WrapperUtil; /** @@ -53,6 +54,10 @@ abstract class AbstractProviderWrapper implements ProviderWrapper { private final List<org.restlet.data.MediaType> producedMimes; + private final Class<?> genericMbrType; + + private final Class<?> genericMbwType; + /** * Creates a new wrapper for a Provider and initializes the provider. If the * given class is not a provider, an {@link IllegalArgumentException} is @@ -83,6 +88,12 @@ abstract class AbstractProviderWrapper implements ProviderWrapper { } else { this.producedMimes = Collections.singletonList(MediaType.ALL); } + + this.genericMbrType = Util.getGenericClass(jaxRsProviderClass, + javax.ws.rs.ext.MessageBodyReader.class); + this.genericMbwType = Util.getGenericClass(jaxRsProviderClass, + javax.ws.rs.ext.MessageBodyWriter.class); + // LATER use Type instead of Class here } @Override @@ -170,8 +181,17 @@ public List<MediaType> getProducedMimes() { * java.lang.reflect.Type) */ public boolean supportsWrite(Class<?> entityClass, Type genericType) { - // TODO AbstractProviderWrapper.supportsWrite(Class) - return true; + if (entityClass == null) { + return false; + } + if (genericType == null) { + // LATER use Type instead of Class + } + if(this.genericMbwType == null) { + return false; + } + final boolean supportsWrite = this.genericMbwType.isAssignableFrom(entityClass); + return supportsWrite; } /** @@ -187,8 +207,16 @@ public boolean supportsWrite(Class<?> entityClass, Type genericType) { * @see MessageBodyReader#supportsRead(Class, Type) */ public boolean supportsRead(Class<?> entityClass, Type genericType) { - // TODO AbstractProviderWrapper.supportsRead(Class) - return true; + if (entityClass == null) { + return false; + } + if (genericType == null) { + // LATER use Type instead of Class + } + if(this.genericMbrType == null) { + return false; + } + return this.genericMbrType.isAssignableFrom(entityClass); } /** diff --git a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/JaxRsProviders.java b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/JaxRsProviders.java index e08f7431a8..78a7299644 100644 --- a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/JaxRsProviders.java +++ b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/JaxRsProviders.java @@ -462,26 +462,29 @@ private void remove(ProviderWrapper provider) { } /** - * Returns a Collection of {@link MessageBodyWriter}s, that support the - * given entityClass. + * Returns a Collection of {@link MessageBodyWriter}s, which generic type + * supports the given entityClass. * * @param entityClass * @param genericType * may be null + * @param annotations + * @param mediaType * @return * @see javax.ws.rs.ext.MessageBodyWriter#isWriteable(Class, Type, * Annotation[]) */ public MessageBodyWriterSubSet writerSubSet(Class<?> entityClass, Type genericType) { - // NICE optimization: may be cached for speed. final List<MessageBodyWriter> mbws = new ArrayList<MessageBodyWriter>(); for (ProviderWrapper mbww : this.messageBodyWriterWrappers) { MessageBodyWriter mbw = mbww.getInitializedWriter(); - if (mbw.supportsWrite(entityClass, genericType)) + if (mbw.supportsWrite(entityClass, genericType)) { mbws.add(mbw); + } } - return new MessageBodyWriterSubSet(mbws); + // NICE optimization: may be cached for speed. + return new MessageBodyWriterSubSet(mbws, entityClass, genericType); } /** diff --git a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyReader.java b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyReader.java index f4de685b0d..20cfe77fd0 100644 --- a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyReader.java +++ b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyReader.java @@ -29,8 +29,8 @@ import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; -import java.lang.reflect.Type; import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Type; import java.util.List; import javax.ws.rs.WebApplicationException; @@ -40,9 +40,10 @@ import org.restlet.data.MediaType; /** - * Class to wrap an initialized {@link javax.ws.rs.ext.MessageBodyWriter} + * Class to wrap an initialized {@link javax.ws.rs.ext.MessageBodyReader} * * @author Stephan Koops + * @see javax.ws.rs.ext.MessageBodyReader */ public interface MessageBodyReader { diff --git a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyWriter.java b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyWriter.java index 016f9ef0b4..1decd6fd7b 100644 --- a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyWriter.java +++ b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyWriter.java @@ -42,6 +42,7 @@ * {@link javax.ws.rs.ext.MessageBodyWriter} * * @author Stephan Koops + * @see javax.ws.rs.ext.MessageBodyWriter */ public interface MessageBodyWriter { @@ -51,7 +52,7 @@ public interface MessageBodyWriter { * @param genericType * @param annotations * @param mediaType - * TODO + * The JAX-RS MediaType * @return * @see javax.ws.rs.ext.MessageBodyWriter#isWriteable(Class, Type, * Annotation[]) @@ -67,13 +68,10 @@ public boolean isWriteable(Class<?> type, Type genericType, * @param t * the instance to write * @param type - * TODO * @param genericType - * TODO * @param annotations - * TODO * @param mediaType - * TODO + * The Restlet MediaType * @return length in bytes or -1 if the length cannot be determined in * advance * @see javax.ws.rs.ext.MessageBodyWriter#getSize(Object, Class, Type, @@ -88,6 +86,7 @@ public long getSize(Object t, Class<?> type, Type genericType, * @param genericType * @param annotations * @param mediaType + * The Restlet MediaType * @param httpHeaders * @param entityStream * @throws IOException @@ -113,8 +112,8 @@ public void writeTo(Object object, Class<?> type, Type genericType, * Returns the list of produced {@link MediaType}s of the wrapped * {@link javax.ws.rs.ext.MessageBodyWriter}. * - * @return List of produced {@link MediaType}s. If the entity provider is - * not annotated with &#64; {@link javax.ws.rs.Produces}, '*<!---->/*' + * @return List of produced Restlet {@link MediaType}s. If the entity + * provider is not annotated with &#64; {@link javax.ws.rs.Produces}, '*<!---->/*' * is returned. */ public List<MediaType> getProducedMimes(); @@ -124,7 +123,7 @@ public void writeTo(Object object, Class<?> type, Type genericType, * given {@link MediaType}s. * * @param mediaTypes - * the {@link MediaType}s + * the Restlet {@link MediaType}s * @return true, if at least one of the requested {@link MediaType}s is * supported, otherwise false. */ @@ -135,7 +134,7 @@ public void writeTo(Object object, Class<?> type, Type genericType, * {@link MediaType}. * * @param mediaType - * the {@link MediaType} + * the Restlet {@link MediaType} * @return true, if the requested {@link MediaType} is supported, otherwise * false. */ diff --git a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyWriterSubSet.java b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyWriterSubSet.java index 906af4e7ec..56b89f688e 100644 --- a/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyWriterSubSet.java +++ b/modules/org.restlet.ext.jaxrs_0.11/src/org/restlet/ext/jaxrs/internal/wrappers/provider/MessageBodyWriterSubSet.java @@ -26,11 +26,14 @@ */ package org.restlet.ext.jaxrs.internal.wrappers.provider; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.restlet.data.MediaType; +import org.restlet.ext.jaxrs.internal.util.Converter; import org.restlet.ext.jaxrs.internal.util.SortedMetadata; /** @@ -41,7 +44,7 @@ public class MessageBodyWriterSubSet { private static final MessageBodyWriterSubSet EMPTY = new MessageBodyWriterSubSet( - new ArrayList<MessageBodyWriter>()); + new ArrayList<MessageBodyWriter>(), null, null); /** * @return @@ -50,10 +53,27 @@ public static MessageBodyWriterSubSet empty() { return EMPTY; } + /** + * The class supported by the contained message body writers, given by the + * type parameter of the {@link javax.ws.rs.ext.MessageBodyWriter}. Could + * be {@code null}. + */ + private final Class<?> type; + + /** + * The type supported by the contained message body writers, given by the + * type parameter of the {@link javax.ws.rs.ext.MessageBodyWriter}. Could + * be {@code null}. + */ + private final Type genericType; + private final List<MessageBodyWriter> mbws; - MessageBodyWriterSubSet(List<MessageBodyWriter> mbws) { + MessageBodyWriterSubSet(List<MessageBodyWriter> mbws, final Class<?> type, + final Type genericType) { this.mbws = mbws; + this.genericType = genericType; + this.type = type; } /** @@ -61,7 +81,8 @@ public static MessageBodyWriterSubSet empty() { * * @return a list of all producible media types. If this set is not empty, * this result is not empty. '*<!---->/*' is returned for a message - * body writer with no &#64;{@link javax.ws.rs.Produces} annotation. + * body writer with no &#64;{@link javax.ws.rs.Produces} + * annotation. */ public Collection<MediaType> getAllProducibleMediaTypes() { final List<MediaType> p = new ArrayList<MediaType>(); @@ -76,22 +97,27 @@ public Collection<MediaType> getAllProducibleMediaTypes() { * types of the response method and of the accepted {@link MediaType}s. * * @param determinedResponseMediaType - * The {@link MediaType}s of the response, declared by the - * resource methods or given by the - * {@link javax.ws.rs.core.Response}. + * The {@link MediaType}s of the response, declared by the + * resource methods or given by the + * {@link javax.ws.rs.core.Response}. + * @param annotations + * TODO * @param accMediaTypes - * the accepted media types. + * the accepted media types. * @return A {@link MessageBodyWriter} that best matches the given accepted. * Returns null, if no adequate {@link MessageBodyWriter} could be * found in this set. */ public MessageBodyWriter getBestWriter( - MediaType determinedResponseMediaType, + MediaType determinedResponseMediaType, Annotation[] annotations, SortedMetadata<MediaType> accMediaTypes) { final List<MessageBodyWriter> mbws = new ArrayList<MessageBodyWriter>(); for (final MessageBodyWriter mbw : this.mbws) { if (mbw.supportsWrite(determinedResponseMediaType)) { - mbws.add(mbw); + if (mbw.isWriteable(type, genericType, annotations, Converter + .toJaxRsMediaType(determinedResponseMediaType))) { + mbws.add(mbw); + } } } for (final Iterable<MediaType> amts : accMediaTypes.listOfColls()) { diff --git a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/NoProviderTest.java b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/NoProviderTest.java index ed88f10e95..4d8b3e7eab 100644 --- a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/NoProviderTest.java +++ b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/NoProviderTest.java @@ -44,11 +44,11 @@ protected Class<?> getRootResourceClass() { public void testNoMediaType() throws Exception { final Response response = get("no-mbw"); - assertEquals(Status.CLIENT_ERROR_NOT_ACCEPTABLE, response.getStatus()); + assertEquals(Status.SERVER_ERROR_INTERNAL, response.getStatus()); } public void testTextPlain() throws Exception { final Response response = get("text-plain"); - assertEquals(Status.CLIENT_ERROR_NOT_ACCEPTABLE, response.getStatus()); + assertEquals(Status.SERVER_ERROR_INTERNAL, response.getStatus()); } } \ No newline at end of file diff --git a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ProviderTest.java b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ProviderTest.java index 8ec4f0df86..c177793617 100644 --- a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ProviderTest.java +++ b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/ProviderTest.java @@ -224,6 +224,7 @@ public void testInputStreamPost() throws Exception { assertEquals("big test", entity.getText()); } + /** @see ProviderTestService#jaxbElementGet() */ public void testJaxbElementGet() throws Exception { getAndCheckJaxb("jaxbElement"); } @@ -297,6 +298,7 @@ public void testJaxbPost() throws Exception { postAndCheckXml("jaxb"); } + /** @see ProviderTestService#mMapGet() */ public void testMultivaluedMapGet() throws Exception { final Response response = get("MultivaluedMap"); assertEquals(Status.SUCCESS_OK, response.getStatus()); @@ -304,6 +306,7 @@ public void testMultivaluedMapGet() throws Exception { assertEquals("lastname=Merkel&firstname=Angela", entity.getText()); } + /** @see ProviderTestService#mMapPost(javax.ws.rs.core.MultivaluedMap) */ public void testMultivaluedMapPost() throws Exception { final Response response = post("MultivaluedMap", createForm() .getWebRepresentation()); diff --git a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/RequestTest.java b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/RequestTest.java index 4bb0c5e461..39f5953ab1 100644 --- a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/RequestTest.java +++ b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/RequestTest.java @@ -70,10 +70,16 @@ public class RequestTest extends JaxRsTestCase { * @see EvaluatePreconditionService#getLastModificationDateFromDatastore() */ @SuppressWarnings("deprecation") - public static final Date BEFORE = new Date(2007 - 1900, 11, 31); //2007-12-31 + public static final Date BEFORE = new Date(2007 - 1900, 11, 31); // 2007-12-31 private static final Status PREC_FAILED = Status.CLIENT_ERROR_PRECONDITION_FAILED; + /** + * Conditions.getStatus() has a bug. I've send a patch; it's not yet + * patchNotApplied to the trunk, while writing this. + */ + private static boolean CONDTIONS_GETSTATUS_PATCH_NOT_APPLIED = true; + /** * @param modifiedSince * @param entityTag @@ -132,13 +138,12 @@ public void testDateAndEntityTag2Get() throws Exception { } public void testDateAndEntityTag2Put() throws Exception { + if (CONDTIONS_GETSTATUS_PATCH_NOT_APPLIED) + return; final Conditions conditions = createConditions(AFTER, getDatastoreETag()); final Response response = put("date", null, conditions); assertEquals(PREC_FAILED, response.getStatus()); - assertTrue("Entity must contain \"was not modified\"", response - .getEntity().getText().contains( - "The entity was not modified since")); } public void testDateAndEntityTag3Get() throws Exception { @@ -146,13 +151,6 @@ public void testDateAndEntityTag3Get() throws Exception { "shkhsdk")); final Response response = get("date", conditions); assertEquals(PREC_FAILED, response.getStatus()); - final String entityText = response.getEntity().getText(); - assertTrue( - "Entity must contain \"was not modified\" or \"does not match Entity Tag\", but is \"" - + entityText + "\"", - entityText.contains("The entity was not modified since") - || entityText - .contains("The entity does not match Entity Tag")); } public void testDateAndEntityTag3Put() throws Exception { @@ -160,13 +158,6 @@ public void testDateAndEntityTag3Put() throws Exception { "shkhsdk")); final Response response = put("date", null, conditions); assertEquals(PREC_FAILED, response.getStatus()); - final String entityText = response.getEntity().getText(); - assertTrue( - "Entity must contain \"was not modified\" or \"does not match Entity Tag\", but is \"" - + entityText + "\"", - entityText.contains("The entity was not modified since") - || entityText - .contains("The entity does not match Entity Tag")); } public void testDateAndEntityTag4Get() throws Exception { @@ -174,13 +165,6 @@ public void testDateAndEntityTag4Get() throws Exception { new Tag("shkhsdk")); final Response response = get("date", conditions); assertEquals(PREC_FAILED, response.getStatus()); - final String entityText = response.getEntity().getText(); - assertTrue( - "Entity must contain \"was not modified\" or \"does not match Entity Tag\", but is \"" - + entityText + "\"", - entityText.contains("The entity was not modified since") - || entityText - .contains("The entity does not match Entity Tag")); } public void testDateAndEntityTag4Put() throws Exception { @@ -188,13 +172,6 @@ public void testDateAndEntityTag4Put() throws Exception { new Tag("shkhsdk")); final Response response = put("date", null, conditions); assertEquals(PREC_FAILED, response.getStatus()); - final String entityText = response.getEntity().getText(); - assertTrue( - "Entity must contain \"was not modified\" or \"does not match Entity Tag\", but is \"" - + entityText + "\"", - entityText.contains("The entity was not modified since") - || entityText - .contains("The entity does not match Entity Tag")); } public void testGetDateNotModified() throws Exception { @@ -227,19 +204,13 @@ public void testGetEntityTagMatch() throws Exception { conditions.setMatch(TestUtils.createList(new Tag("affer"))); response = get("date", conditions); assertEquals(PREC_FAILED, response.getStatus()); - assertTrue("Entity must contain \"does not match Entity Tag\"", - response.getEntity().getText().contains( - "The entity does not match Entity Tag")); } public void testGetEntityTagNoneMatch() throws Exception { Conditions conditions = new Conditions(); conditions.setNoneMatch(TestUtils.createList(getDatastoreETag())); Response response = get("date", conditions); - assertEquals(PREC_FAILED, response.getStatus()); - assertTrue("Entity must contain \"matches Entity Tag\"", response - .getEntity().getText() - .contains("The entity matches Entity Tag")); + assertEquals(Status.REDIRECTION_NOT_MODIFIED, response.getStatus()); conditions = new Conditions(); conditions.setNoneMatch(TestUtils.createList(new Tag("affer"))); @@ -287,8 +258,6 @@ public void testGetUnmodifiedSince() throws Exception { conditions.setUnmodifiedSince(BEFORE); response = get("date", conditions); assertEquals(PREC_FAILED, response.getStatus()); - assertTrue("Entity must contain \"was modified\"", response.getEntity() - .getText().contains("The entity was modified since")); // NICE testen, was bei ungultigem Datum passiert: // If-Unmodified-Since-Header ignorieren. @@ -312,6 +281,8 @@ public void testOptions() { * @throws Exception */ public void testPutModifiedSince() throws Exception { + if (CONDTIONS_GETSTATUS_PATCH_NOT_APPLIED) + return; Conditions conditions = new Conditions(); conditions.setModifiedSince(BEFORE); Response response = put("date", null, conditions); @@ -321,9 +292,6 @@ public void testPutModifiedSince() throws Exception { conditions.setModifiedSince(AFTER); response = put("date", null, conditions); assertEquals(PREC_FAILED, response.getStatus()); - assertTrue("Entity must contain \"was not modified\"", response - .getEntity().getText().contains( - "The entity was not modified since")); } public void testPutUnmodifiedSince() throws Exception { @@ -336,9 +304,6 @@ public void testPutUnmodifiedSince() throws Exception { conditions.setUnmodifiedSince(BEFORE); response = put("date", null, conditions); assertEquals(PREC_FAILED, response.getStatus()); - final String respEntity = response.getEntity().getText(); - assertTrue("Entity must contain \"was not modified\"", respEntity - .contains("The entity was modified since")); } public void testSelectVariant() {
5f232224c4de92467c4de6385590ec19e0568ba5
Mylyn Reviews
322734: Display just the last review result for a task
p
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java index d1a7e91b..9cd94ab5 100644 --- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java +++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java @@ -148,12 +148,32 @@ public static List<Review> getReviewAttachmentFromTask( List<Review> reviews = new ArrayList<Review>(); TaskData taskData = taskDataManager.getTaskData(task); if (taskData != null) { - for (TaskAttribute attribute : getReviewAttachments( - repositoryModel, taskData)) { - reviews.addAll(parseAttachments(attribute, - new NullProgressMonitor())); + List<TaskAttribute> attributesByType = taskData + .getAttributeMapper().getAttributesByType(taskData, + TaskAttribute.TYPE_ATTACHMENT); + ITaskAttachment lastReview = null; + + for (TaskAttribute attribute : attributesByType) { + // TODO move RepositoryModel.createTaskAttachment to interface? + ITaskAttachment taskAttachment = ((RepositoryModel) repositoryModel) + .createTaskAttachment(attribute); + if (taskAttachment != null + && taskAttachment.getFileName().equals( + ReviewConstants.REVIEW_DATA_CONTAINER)) { + + if (lastReview == null + || lastReview.getCreationDate().before( + taskAttachment.getCreationDate())) { + lastReview = taskAttachment; + } + } } + + if (lastReview != null) { + reviews.addAll(parseAttachments(lastReview.getTaskAttribute(), + new NullProgressMonitor())); + } } return reviews; @@ -203,4 +223,5 @@ public static void markAsReview(ITask task) { public static boolean hasReviewMarker(ITask task) { return task.getAttribute(ReviewConstants.ATTR_REVIEW_FLAG) != null; } + }
2daa05f2bd185e3de5c2e85afc86b2bc6194b41b
Valadoc
gtkdoc: accept %<numeric>
a
https://github.com/GNOME/vala/
diff --git a/src/libvaladoc/documentation/gtkdoccommentparser.vala b/src/libvaladoc/documentation/gtkdoccommentparser.vala index 1fcafbc753..79392168a5 100644 --- a/src/libvaladoc/documentation/gtkdoccommentparser.vala +++ b/src/libvaladoc/documentation/gtkdoccommentparser.vala @@ -44,6 +44,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { private string[]? comment_lines; + private Regex? is_numeric_regex = null; private Regex? normalize_regex = null; private HashMap<Api.SourceFile, GirMetaData> metadata = new HashMap<Api.SourceFile, GirMetaData> (); @@ -76,15 +77,16 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { private string normalize (string text) { try { - if (normalize_regex == null) { - normalize_regex = new Regex ("( |\n|\t)+"); - } return normalize_regex.replace (text, -1, 0, " "); } catch (RegexError e) { assert_not_reached (); } } + private bool is_numeric (string str) { + return is_numeric_regex.match (str); + } + private inline Text? split_text (Text text) { int offset = 0; while ((offset = text.content.index_of_char ('.', offset)) >= 0) { @@ -230,6 +232,13 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { this.reporter = reporter; this.settings = settings; this.tree = tree; + + try { + is_numeric_regex = new Regex ("^[+-]?([0-9]*\\.?[0-9]+|[0-9]+\\.?[0-9]*)([eE][+-]?[0-9]+)?$", RegexCompileFlags.OPTIMIZE); + normalize_regex = new Regex ("( |\n|\t)+", RegexCompileFlags.OPTIMIZE); + } catch (RegexError e) { + assert_not_reached (); + } } private Api.Node? element; @@ -1493,7 +1502,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { } private Inline create_type_link (string name) { - if (name == "TRUE" || name == "FALSE" || name == "NULL") { + if (name == "TRUE" || name == "FALSE" || name == "NULL" || is_numeric (name)) { var monospaced = factory.create_run (Run.Style.MONOSPACED); monospaced.content.add (factory.create_text (name.down ())); return monospaced;
d51eaf7a642b4b4572aa9628e66b760e5c3ee2d5
drools
JBRULES-1102 Bug in DefaultBetaConstraint class- indexing to never turn on -Fixed DefaultBetaConstraints -Added comprehensive- unit test--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@14396 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
c
https://github.com/kiegroup/drools
diff --git a/drools-core/src/main/java/org/drools/common/DefaultBetaConstraints.java b/drools-core/src/main/java/org/drools/common/DefaultBetaConstraints.java index 8a06d895ea6..5e1593a5228 100644 --- a/drools-core/src/main/java/org/drools/common/DefaultBetaConstraints.java +++ b/drools-core/src/main/java/org/drools/common/DefaultBetaConstraints.java @@ -72,7 +72,7 @@ public DefaultBetaConstraints(final BetaNodeFieldConstraint[] constraints, // First create a LinkedList of constraints, with the indexed constraints first. for ( int i = 0, length = constraints.length; i < length; i++ ) { // Determine if this constraint is indexable - if ( (!disableIndexing) && conf.isIndexLeftBetaMemory() && conf.isIndexRightBetaMemory() && isIndexable( constraints[i] ) && ( depth <= this.indexed ) ) { + if ( (!disableIndexing) && conf.isIndexLeftBetaMemory() && conf.isIndexRightBetaMemory() && isIndexable( constraints[i] ) && ( this.indexed < depth-1 ) ) { if ( depth >= 1 && this.indexed == -1 ) { // first index, so just add to the front this.constraints.insertAfter( null, @@ -189,7 +189,12 @@ public boolean isAllowedCachedRight(final ReteTuple tuple) { } public boolean isIndexed() { - return this.indexed > 0; + // false if -1 + return this.indexed >= 0; + } + + public int getIndexCount() { + return this.indexed; } public boolean isEmpty() { @@ -198,11 +203,11 @@ public boolean isEmpty() { public BetaMemory createBetaMemory(RuleBaseConfiguration config) { BetaMemory memory; - if ( this.indexed > 0 ) { + if ( this.indexed >= 0 ) { LinkedListEntry entry = (LinkedListEntry) this.constraints.getFirst(); final List list = new ArrayList(); - for ( int pos = 0; pos < this.indexed; pos++ ) { + for ( int pos = 0; pos <= this.indexed; pos++ ) { final Constraint constraint = (Constraint) entry.getObject(); final VariableConstraint variableConstraint = (VariableConstraint) constraint; final FieldIndex index = new FieldIndex( variableConstraint.getFieldExtractor(), diff --git a/drools-core/src/main/java/org/drools/reteoo/ReteooRuleBase.java b/drools-core/src/main/java/org/drools/reteoo/ReteooRuleBase.java index c50bffccc5d..353d6841b19 100644 --- a/drools-core/src/main/java/org/drools/reteoo/ReteooRuleBase.java +++ b/drools-core/src/main/java/org/drools/reteoo/ReteooRuleBase.java @@ -221,7 +221,7 @@ public synchronized StatefulSession newStatefulSession(final boolean keepReferen throw new RuntimeException( "Cannot have a stateful rule session, with sequential configuration set to true" ); } ReteooStatefulSession session = null; - + synchronized ( this.pkgs ) { ExecutorService executor = this.config.getExecutorService(); session = new ReteooStatefulSession( nextWorkingMemoryCounter(), @@ -237,10 +237,10 @@ public synchronized StatefulSession newStatefulSession(final boolean keepReferen final InitialFactHandle handle = new InitialFactHandle( session.getFactHandleFactory().newFactHandle( new InitialFactHandleDummyObject() ) ); session.queueWorkingMemoryAction( new WorkingMemoryReteAssertAction( handle, - false, - true, - null, - null ) ); + false, + true, + null, + null ) ); } return session; } diff --git a/drools-core/src/main/java/org/drools/util/AbstractHashTable.java b/drools-core/src/main/java/org/drools/util/AbstractHashTable.java index 53b19fb4cb0..a425e4175b7 100644 --- a/drools-core/src/main/java/org/drools/util/AbstractHashTable.java +++ b/drools-core/src/main/java/org/drools/util/AbstractHashTable.java @@ -434,7 +434,9 @@ public Evaluator getEvaluator() { } } - public static interface Index { + public static interface Index { + public FieldIndex getFieldIndex(int index); + public int hashCodeOf(ReteTuple tuple); public int hashCodeOf(Object object); @@ -466,9 +468,16 @@ public SingleIndex(final FieldIndex[] indexes, this.extractor = indexes[0].extractor; this.declaration = indexes[0].declaration; this.evaluator = indexes[0].evaluator; - } + public FieldIndex getFieldIndex(int index) { + if ( index > 0 ) { + throw new IllegalArgumentException("Index position " + index + " does not exist" ); + } + return new FieldIndex(extractor, declaration, evaluator); + } + + public int hashCodeOf(final Object object) { int hashCode = this.startResult; hashCode = TupleIndexHashTable.PRIME * hashCode + this.extractor.getHashCode( null, object ); @@ -534,7 +543,17 @@ public DoubleCompositeIndex(final FieldIndex[] indexes, this.index0 = indexes[0]; this.index1 = indexes[1]; - + } + + public FieldIndex getFieldIndex(int index) { + switch ( index ) { + case 0: + return index0; + case 1: + return index1; + default: + throw new IllegalArgumentException("Index position " + index + " does not exist" ); + } } public int hashCodeOf(final Object object) { @@ -622,8 +641,20 @@ public TripleCompositeIndex(final FieldIndex[] indexes, this.index0 = indexes[0]; this.index1 = indexes[1]; this.index2 = indexes[2]; - } + + public FieldIndex getFieldIndex(int index) { + switch ( index ) { + case 0: + return index0; + case 1: + return index1; + case 2: + return index2; + default: + throw new IllegalArgumentException("Index position " + index + " does not exist" ); + } + } public int hashCodeOf(final Object object) { int hashCode = this.startResult; diff --git a/drools-core/src/main/java/org/drools/util/FactHandleIndexHashTable.java b/drools-core/src/main/java/org/drools/util/FactHandleIndexHashTable.java index a7d23b4bebe..f26f47938ee 100644 --- a/drools-core/src/main/java/org/drools/util/FactHandleIndexHashTable.java +++ b/drools-core/src/main/java/org/drools/util/FactHandleIndexHashTable.java @@ -77,6 +77,10 @@ public Iterator iterator(final ReteTuple tuple) { public boolean isIndexed() { return true; } + + public Index getIndex() { + return this.index; + } public Entry getBucket(final Object object) { final int hashCode = this.index.hashCodeOf( object ); diff --git a/drools-core/src/main/java/org/drools/util/TupleIndexHashTable.java b/drools-core/src/main/java/org/drools/util/TupleIndexHashTable.java index 44f8b092088..7971a8250d5 100644 --- a/drools-core/src/main/java/org/drools/util/TupleIndexHashTable.java +++ b/drools-core/src/main/java/org/drools/util/TupleIndexHashTable.java @@ -81,6 +81,10 @@ public Iterator iterator(final InternalFactHandle handle) { public boolean isIndexed() { return true; } + + public Index getIndex() { + return this.index; + } public Entry getBucket(final Object object) { final int hashCode = this.index.hashCodeOf( object ); diff --git a/drools-core/src/test/java/org/drools/common/DefaultBetaConstraintsTest.java b/drools-core/src/test/java/org/drools/common/DefaultBetaConstraintsTest.java new file mode 100644 index 00000000000..f04181075ca --- /dev/null +++ b/drools-core/src/test/java/org/drools/common/DefaultBetaConstraintsTest.java @@ -0,0 +1,249 @@ +package org.drools.common; + +import java.util.ArrayList; +import java.util.List; + +import org.drools.Cheese; +import org.drools.Person; +import org.drools.RuleBaseConfiguration; +import org.drools.RuleBaseFactory; +import org.drools.base.ClassFieldExtractor; +import org.drools.base.ClassFieldExtractorCache; +import org.drools.base.ClassObjectType; +import org.drools.base.FieldFactory; +import org.drools.base.ValueType; +import org.drools.base.evaluators.Operator; +import org.drools.base.evaluators.StringFactory; +import org.drools.reteoo.BetaMemory; +import org.drools.reteoo.ReteooRuleBase; +import org.drools.rule.Declaration; +import org.drools.rule.LiteralConstraint; +import org.drools.rule.Pattern; +import org.drools.rule.VariableConstraint; +import org.drools.spi.BetaNodeFieldConstraint; +import org.drools.spi.Evaluator; +import org.drools.spi.FieldExtractor; +import org.drools.spi.FieldValue; +import org.drools.util.FactHandleIndexHashTable; +import org.drools.util.FactHashTable; +import org.drools.util.TupleHashTable; +import org.drools.util.TupleIndexHashTable; +import org.drools.util.AbstractHashTable.DoubleCompositeIndex; +import org.drools.util.AbstractHashTable.FieldIndex; +import org.drools.util.AbstractHashTable.Index; +import org.drools.util.AbstractHashTable.SingleIndex; +import org.drools.util.AbstractHashTable.TripleCompositeIndex; + +import junit.framework.TestCase; + +public class DefaultBetaConstraintsTest extends TestCase { + + public void testNoIndexConstraints() { + VariableConstraint constraint0 = ( VariableConstraint ) getConstraint( "cheeseType0", Operator.NOT_EQUAL, "type", Cheese.class ); + VariableConstraint[] constraints = new VariableConstraint[] { constraint0 }; + checkBetaConstraints( constraints ); + + VariableConstraint constraint1 = ( VariableConstraint ) getConstraint( "cheeseType1", Operator.NOT_EQUAL, "type", Cheese.class ); + constraints = new VariableConstraint[] { constraint0, constraint1 }; + checkBetaConstraints( constraints ); + + VariableConstraint constraint2 = ( VariableConstraint ) getConstraint( "cheeseType2", Operator.NOT_EQUAL, "type", Cheese.class ); + constraints = new VariableConstraint[] { constraint0, constraint1, constraint2 }; + checkBetaConstraints( constraints ); + + VariableConstraint constraint3 = ( VariableConstraint ) getConstraint( "cheeseType3", Operator.NOT_EQUAL, "type", Cheese.class ); + constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3 }; + checkBetaConstraints( constraints ); + + VariableConstraint constraint4 = ( VariableConstraint ) getConstraint( "cheeseType4", Operator.NOT_EQUAL, "type", Cheese.class ); + constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4 }; + checkBetaConstraints( constraints ); + + VariableConstraint constraint5 = ( VariableConstraint ) getConstraint( "cheeseType5", Operator.NOT_EQUAL, "type", Cheese.class ); + constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3,constraint5 }; + checkBetaConstraints( constraints ); + + VariableConstraint constraint6 = ( VariableConstraint ) getConstraint( "cheeseType6", Operator.NOT_EQUAL, "type", Cheese.class ); + constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4, constraint5, constraint6 }; + checkBetaConstraints( constraints ); + } + + public void testIndexedConstraint() { + VariableConstraint constraint0 = ( VariableConstraint ) getConstraint( "cheeseType0", Operator.EQUAL, "type", Cheese.class ); + VariableConstraint[] constraints = new VariableConstraint[] { constraint0 }; + checkBetaConstraints( constraints ); + + VariableConstraint constraint1 = ( VariableConstraint ) getConstraint( "cheeseType1", Operator.EQUAL, "type", Cheese.class ); + constraints = new VariableConstraint[] { constraint0, constraint1 }; + checkBetaConstraints( constraints ); + + VariableConstraint constraint2 = ( VariableConstraint ) getConstraint( "cheeseType2", Operator.EQUAL, "type", Cheese.class ); + constraints = new VariableConstraint[] { constraint0, constraint1, constraint2 }; + checkBetaConstraints( constraints ); + + VariableConstraint constraint3 = ( VariableConstraint ) getConstraint( "cheeseType3", Operator.EQUAL, "type", Cheese.class ); + constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3 }; + checkBetaConstraints( constraints ); + + VariableConstraint constraint4 = ( VariableConstraint ) getConstraint( "cheeseType4", Operator.EQUAL, "type", Cheese.class ); + constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4 }; + checkBetaConstraints( constraints ); + + VariableConstraint constraint5 = ( VariableConstraint ) getConstraint( "cheeseType5", Operator.EQUAL, "type", Cheese.class ); + constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4, constraint5 }; + checkBetaConstraints( constraints ); + + VariableConstraint constraint6 = ( VariableConstraint ) getConstraint( "cheeseType6", Operator.EQUAL, "type", Cheese.class ); + constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4, constraint5, constraint6 }; + checkBetaConstraints( constraints ); + } + + + public void testSingleIndex() { + VariableConstraint constraint0 = ( VariableConstraint ) getConstraint( "cheeseType1", Operator.EQUAL, "type", Cheese.class ); + VariableConstraint constraint1 = ( VariableConstraint ) getConstraint( "cheeseType2", Operator.NOT_EQUAL, "type", Cheese.class ); + VariableConstraint constraint2 = ( VariableConstraint ) getConstraint( "cheeseType3", Operator.NOT_EQUAL, "type", Cheese.class ); + VariableConstraint constraint3 = ( VariableConstraint ) getConstraint( "cheeseType4", Operator.NOT_EQUAL, "type", Cheese.class ); + VariableConstraint constraint4 = ( VariableConstraint ) getConstraint( "cheeseType5", Operator.NOT_EQUAL, "type", Cheese.class ); + + VariableConstraint[] constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4 }; + checkBetaConstraints( constraints ); + } + + public void testSingleIndexNotFirst() { + VariableConstraint constraint0 = ( VariableConstraint ) getConstraint( "cheeseType1", Operator.NOT_EQUAL, "type", Cheese.class ); + VariableConstraint constraint1 = ( VariableConstraint ) getConstraint( "cheeseType2", Operator.NOT_EQUAL, "type", Cheese.class ); + VariableConstraint constraint2 = ( VariableConstraint ) getConstraint( "cheeseType3", Operator.NOT_EQUAL, "type", Cheese.class ); + VariableConstraint constraint3 = ( VariableConstraint ) getConstraint( "cheeseType4", Operator.NOT_EQUAL, "type", Cheese.class ); + VariableConstraint constraint4 = ( VariableConstraint ) getConstraint( "cheeseType5", Operator.EQUAL, "type", Cheese.class ); + + VariableConstraint[] constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4 }; + + checkBetaConstraints( constraints ); + } + + public void testDoubleIndex() { + VariableConstraint constraint0 = ( VariableConstraint ) getConstraint( "cheeseType1", Operator.EQUAL, "type", Cheese.class ); + VariableConstraint constraint1 = ( VariableConstraint ) getConstraint( "cheeseType2", Operator.NOT_EQUAL, "type", Cheese.class ); + VariableConstraint constraint2 = ( VariableConstraint ) getConstraint( "cheeseType3", Operator.NOT_EQUAL, "type", Cheese.class ); + VariableConstraint constraint3 = ( VariableConstraint ) getConstraint( "cheeseType4", Operator.EQUAL, "type", Cheese.class ); + VariableConstraint constraint4 = ( VariableConstraint ) getConstraint( "cheeseType5", Operator.NOT_EQUAL, "type", Cheese.class ); + + VariableConstraint[] constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4 }; + + checkBetaConstraints( constraints ); + } + + public void testDoubleIndexNotFirst() { + VariableConstraint constraint0 = ( VariableConstraint ) getConstraint( "cheeseType1", Operator.NOT_EQUAL, "type", Cheese.class ); + VariableConstraint constraint1 = ( VariableConstraint ) getConstraint( "cheeseType2", Operator.NOT_EQUAL, "type", Cheese.class ); + VariableConstraint constraint2 = ( VariableConstraint ) getConstraint( "cheeseType3", Operator.NOT_EQUAL, "type", Cheese.class ); + VariableConstraint constraint3 = ( VariableConstraint ) getConstraint( "cheeseType4", Operator.EQUAL, "type", Cheese.class ); + VariableConstraint constraint4 = ( VariableConstraint ) getConstraint( "cheeseType5", Operator.EQUAL, "type", Cheese.class ); + + VariableConstraint[] constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4 }; + + checkBetaConstraints( constraints ); + } + + + public void testTripleIndex() { + VariableConstraint constraint0 = ( VariableConstraint ) getConstraint( "cheeseType1", Operator.EQUAL, "type", Cheese.class ); + VariableConstraint constraint1 = ( VariableConstraint ) getConstraint( "cheeseType2", Operator.NOT_EQUAL, "type", Cheese.class ); + VariableConstraint constraint2 = ( VariableConstraint ) getConstraint( "cheeseType3", Operator.NOT_EQUAL, "type", Cheese.class ); + VariableConstraint constraint3 = ( VariableConstraint ) getConstraint( "cheeseType4", Operator.EQUAL, "type", Cheese.class ); + VariableConstraint constraint4 = ( VariableConstraint ) getConstraint( "cheeseType5", Operator.EQUAL, "type", Cheese.class ); + + VariableConstraint[] constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4 }; + + checkBetaConstraints( constraints ); + } + + public void testTripleIndexNotFirst() { + VariableConstraint constraint0 = ( VariableConstraint ) getConstraint( "cheeseType1", Operator.NOT_EQUAL, "type", Cheese.class ); + VariableConstraint constraint1 = ( VariableConstraint ) getConstraint( "cheeseType2", Operator.EQUAL, "type", Cheese.class ); + VariableConstraint constraint2 = ( VariableConstraint ) getConstraint( "cheeseType3", Operator.NOT_EQUAL, "type", Cheese.class ); + VariableConstraint constraint3 = ( VariableConstraint ) getConstraint( "cheeseType4", Operator.EQUAL, "type", Cheese.class ); + VariableConstraint constraint4 = ( VariableConstraint ) getConstraint( "cheeseType5", Operator.EQUAL, "type", Cheese.class ); + + VariableConstraint[] constraints = new VariableConstraint[] { constraint0, constraint1, constraint2, constraint3, constraint4 }; + + checkBetaConstraints( constraints ); + } + + private BetaNodeFieldConstraint getConstraint(String identifier, + Operator operator, + String fieldName, + Class clazz) { + FieldExtractor extractor = ClassFieldExtractorCache.getExtractor( clazz, + fieldName, + getClass().getClassLoader() ); + Declaration declaration = new Declaration( identifier, + extractor, + new Pattern( 0, + new ClassObjectType( clazz ) ) ); + Evaluator evaluator = StringFactory.getInstance().getEvaluator( operator ); + return new VariableConstraint( extractor, + declaration, + evaluator ); + } + + + private void checkBetaConstraints(VariableConstraint[] constraints) { + RuleBaseConfiguration config = new RuleBaseConfiguration(); + int depth = config.getCompositeKeyDepth(); + + List list = new ArrayList(); + + // get indexed positions + for ( int i = 0; i < constraints.length && list.size() < depth; i++ ) { + if ( constraints[i].getEvaluator().getOperator() == Operator.EQUAL ) { + list.add( new Integer(i) ); + } + } + + // convert to array + int[] indexedPositions = new int[ list.size() ]; + for ( int i = 0; i < list.size(); i++ ) { + indexedPositions[i] = ( (Integer)list.get( i ) ).intValue(); + } + + DefaultBetaConstraints betaConstraints = new DefaultBetaConstraints(constraints, config ); + + assertEquals( ( indexedPositions.length > 0 ), betaConstraints.isIndexed() ); + assertEquals(indexedPositions.length-1, betaConstraints.getIndexCount() ); + BetaMemory betaMemory = betaConstraints.createBetaMemory( config ); + + // test tuple side + if ( indexedPositions.length > 0 ) { + TupleIndexHashTable tupleHashTable = ( TupleIndexHashTable ) betaMemory.getTupleMemory(); + assertTrue( tupleHashTable.isIndexed() ); + Index index = tupleHashTable.getIndex(); + + for ( int i = 0; i < indexedPositions.length; i++ ) { + checkSameConstraintForIndex( constraints[indexedPositions[i]], index.getFieldIndex(i) ); + } + + FactHandleIndexHashTable factHashTable = ( FactHandleIndexHashTable ) betaMemory.getFactHandleMemory(); + assertTrue( factHashTable.isIndexed() ); + index = factHashTable.getIndex(); + + for ( int i = 0; i < indexedPositions.length; i++ ) { + checkSameConstraintForIndex( constraints[indexedPositions[i]], index.getFieldIndex(i) ); + } + } else { + TupleHashTable tupleHashTable = ( TupleHashTable ) betaMemory.getTupleMemory(); + assertFalse( tupleHashTable.isIndexed() ); + + FactHashTable factHashTable = ( FactHashTable ) betaMemory.getFactHandleMemory(); + assertFalse( factHashTable.isIndexed() ); + } + } + + + private void checkSameConstraintForIndex(VariableConstraint constraint, FieldIndex fieldIndex) { + assertSame( constraint.getRequiredDeclarations()[0], fieldIndex.getDeclaration() ); + assertSame( constraint.getEvaluator(), fieldIndex.getEvaluator() ); + assertSame( constraint.getFieldExtractor(), fieldIndex.getExtractor() ); + } +}
013fd99d0dd0df30e0bb7fcb98e41cd1633319cb
hbase
HBASE-2513 hbase-2414 added bug where we'd- tight-loop if no root available--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@941546 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/core/src/main/java/org/apache/hadoop/hbase/master/RegionServerOperationQueue.java b/core/src/main/java/org/apache/hadoop/hbase/master/RegionServerOperationQueue.java index c85c1414b086..3749805ccc2d 100644 --- a/core/src/main/java/org/apache/hadoop/hbase/master/RegionServerOperationQueue.java +++ b/core/src/main/java/org/apache/hadoop/hbase/master/RegionServerOperationQueue.java @@ -122,8 +122,8 @@ public synchronized ProcessingResultCode process(final HServerAddress rootRegion // it first. if (rootRegionLocation != null) { op = delayedToDoQueue.poll(); - } else { - // if there aren't any todo items in the queue, sleep for a bit. + } + if (op == null) { try { op = toDoQueue.poll(threadWakeFrequency, TimeUnit.MILLISECONDS); } catch (InterruptedException e) {
5acb3713b509efd92e51d2e3501988ff6ec4f34d
intellij-community
IDEA-81004 Deadlock (SoftWrapApplianceManager)--Breaking potentially endless loop and report an error-
c
https://github.com/JetBrains/intellij-community
diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceManager.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceManager.java index 948b08c570382..323e15b63b1a1 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceManager.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -419,13 +419,31 @@ private boolean processOutOfDateFoldRegion(FoldRegion foldRegion) { * <code>'Token'</code> here stands for the number of subsequent symbols that are represented using the same font by IJ editor. */ private void processNonFoldToken() { + int limit = 3 * (myContext.tokenEndOffset - myContext.lineStartPosition.offset); + int counter = 0; + int startOffset = myContext.currentPosition.offset; while (myContext.currentPosition.offset < myContext.tokenEndOffset) { - //for (int i = myContext.startOffset; i < myContext.endOffset; i++) { + if (counter++ > limit) { + String editorInfo = myEditor instanceof EditorImpl ? ((EditorImpl)myEditor).dumpState() : myEditor.getClass().toString(); + LogMessageEx.error(LOG, "Cycled soft wraps recalculation detected", String.format( + "Start recalculation offset: %d, visible area width: %d, calculation context: %s, editor info: %s", + startOffset, myVisibleAreaWidth, myContext, editorInfo)); + for (int i = myContext.currentPosition.offset; i < myContext.tokenEndOffset; i++) { + char c = myContext.text.charAt(i); + if (c == '\n') { + myContext.onNewLine(); + } + else { + myContext.onNonLineFeedSymbol(c); + } + } + return; + } int offset = myContext.currentPosition.offset; if (offset > myContext.rangeEndOffset) { return; } - + if (myContext.delayedSoftWrap != null && myContext.delayedSoftWrap.getStart() == offset) { processSoftWrap(myContext.delayedSoftWrap); myContext.delayedSoftWrap = null; @@ -442,7 +460,7 @@ private void processNonFoldToken() { createSoftWrapIfPossible(); continue; } - + int newX = offsetToX(offset, c); if (myContext.exceedsVisualEdge(newX) && myContext.delayedSoftWrap == null) { createSoftWrapIfPossible(); @@ -1119,6 +1137,14 @@ private class ProcessingContext { public boolean notifyListenersOnLineStartPosition; public boolean skipToLineEnd; + @Override + public String toString() { + return "reserved width: " + reservedWidthInPixels + ", soft wrap start offset: " + softWrapStartOffset + ", range end offset: " + + rangeEndOffset + ", token offsets: [" + tokenStartOffset + "; " + tokenEndOffset + "], font type: " + fontType + + ", skip to line end: " + skipToLineEnd + ", delayed soft wrap: " + delayedSoftWrap + ", current position: "+ currentPosition + + "line start position: " + lineStartPosition; + } + public void reset() { text = null; lineStartPosition = null;
cc6bd6239a2cf8db9b661e987e22c36737621db2
kotlin
Remove unused method--
p
https://github.com/JetBrains/kotlin
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/BasicExpressionTypingVisitor.java b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/BasicExpressionTypingVisitor.java index 2f07308102b69..bc9a03f608cc9 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/BasicExpressionTypingVisitor.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/BasicExpressionTypingVisitor.java @@ -19,7 +19,6 @@ import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.intellij.lang.ASTNode; -import com.intellij.openapi.util.Pair; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; @@ -70,7 +69,7 @@ protected BasicExpressionTypingVisitor(@NotNull ExpressionTypingInternals facade public JetTypeInfo visitSimpleNameExpression(JetSimpleNameExpression expression, ExpressionTypingContext context) { // TODO : other members // TODO : type substitutions??? - JetTypeInfo typeInfo = getSelectorReturnTypeInfo(NO_RECEIVER, null, expression, context); + JetTypeInfo typeInfo = getSimpleNameExpressionTypeInfo(expression, NO_RECEIVER, null, context); JetType type = DataFlowUtils.checkType(typeInfo.getType(), expression, context); ExpressionTypingUtils.checkWrappingInRef(expression, context.trace, context.scope); return JetTypeInfo.create(type, typeInfo.getDataFlowInfo()); // TODO : Extensions to this @@ -769,7 +768,7 @@ private JetType getVariableType(@NotNull JetSimpleNameExpression nameExpression, } @NotNull - public JetTypeInfo getSelectorReturnTypeInfo(@NotNull ReceiverValue receiver, @Nullable ASTNode callOperationNode, @NotNull JetExpression selectorExpression, @NotNull ExpressionTypingContext context) { + private JetTypeInfo getSelectorReturnTypeInfo(@NotNull ReceiverValue receiver, @Nullable ASTNode callOperationNode, @NotNull JetExpression selectorExpression, @NotNull ExpressionTypingContext context) { if (selectorExpression instanceof JetCallExpression) { return getCallExpressionTypeInfo((JetCallExpression) selectorExpression, receiver, callOperationNode, context); } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingInternals.java b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingInternals.java index df4c2a5cac081..c9b826f6d6207 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingInternals.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingInternals.java @@ -16,20 +16,14 @@ package org.jetbrains.jet.lang.types.expressions; -import com.intellij.lang.ASTNode; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.psi.JetElement; import org.jetbrains.jet.lang.psi.JetExpression; import org.jetbrains.jet.lang.psi.JetSimpleNameExpression; -import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverValue; import org.jetbrains.jet.lang.types.JetTypeInfo; /*package*/ interface ExpressionTypingInternals extends ExpressionTypingFacade { - - @NotNull - JetTypeInfo getSelectorReturnTypeInfo(@NotNull ReceiverValue receiver, @Nullable ASTNode callOperationNode, @NotNull JetExpression selectorExpression, @NotNull ExpressionTypingContext context); - @NotNull JetTypeInfo checkInExpression(JetElement callElement, @NotNull JetSimpleNameExpression operationSign, @Nullable JetExpression left, @NotNull JetExpression right, ExpressionTypingContext context); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingVisitorDispatcher.java b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingVisitorDispatcher.java index 8d4d338837c9c..ee9a8737fb3cc 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingVisitorDispatcher.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/types/expressions/ExpressionTypingVisitorDispatcher.java @@ -16,14 +16,12 @@ package org.jetbrains.jet.lang.types.expressions; -import com.intellij.lang.ASTNode; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.psi.*; import org.jetbrains.jet.lang.resolve.BindingContext; import org.jetbrains.jet.lang.resolve.calls.autocasts.DataFlowInfo; import org.jetbrains.jet.lang.resolve.scopes.WritableScope; -import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverValue; import org.jetbrains.jet.lang.types.DeferredType; import org.jetbrains.jet.lang.types.ErrorUtils; import org.jetbrains.jet.lang.types.JetTypeInfo; @@ -64,11 +62,6 @@ private ExpressionTypingVisitorDispatcher(WritableScope writableScope) { } } - @Override - public JetTypeInfo getSelectorReturnTypeInfo(@NotNull ReceiverValue receiver, @Nullable ASTNode callOperationNode, @NotNull JetExpression selectorExpression, @NotNull ExpressionTypingContext context) { - return basic.getSelectorReturnTypeInfo(receiver, callOperationNode, selectorExpression, context); - } - @NotNull @Override public JetTypeInfo checkInExpression(JetElement callElement, @NotNull JetSimpleNameExpression operationSign, @Nullable JetExpression left, @NotNull JetExpression right, ExpressionTypingContext context) {
c5c3e019a461fedf064eef019f4536f00df61dec
restlet-framework-java
- Continued support for non-blocking HTTPS to the- internal NIO connectors
a
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet/src/org/restlet/engine/io/ReadableSslChannel.java b/modules/org.restlet/src/org/restlet/engine/io/ReadableSslChannel.java index 860d7de34e..eb27e8119e 100644 --- a/modules/org.restlet/src/org/restlet/engine/io/ReadableSslChannel.java +++ b/modules/org.restlet/src/org/restlet/engine/io/ReadableSslChannel.java @@ -32,11 +32,13 @@ import java.io.IOException; import java.nio.ByteBuffer; +import java.util.logging.Level; import javax.net.ssl.SSLEngineResult; import org.restlet.engine.connector.SslConnection; import org.restlet.engine.security.SslManager; +import org.restlet.engine.security.SslState; /** * SSL byte channel that unwraps all read data using the SSL/TLS protocols. It @@ -78,13 +80,18 @@ public int read(ByteBuffer dst) throws IOException { // If the packet buffer is empty, first try to refill it refill(); - if (getPacketBufferState() == BufferState.DRAINING) { + if ((getPacketBufferState() == BufferState.DRAINING) + || (getManager().getState() == SslState.HANDSHAKING)) { int dstSize = dst.remaining(); if (dstSize > 0) { - SSLEngineResult sslResult = runEngine(dst); - handleResult(sslResult, dst); - refill(); + while (getPacketBuffer().hasRemaining() + && (getConnection().getInboundWay().getIoState() != IoState.IDLE)) { + SSLEngineResult sslResult = runEngine(dst); + handleResult(sslResult, dst); + refill(); + } + result = dstSize - dst.remaining(); } } @@ -105,6 +112,11 @@ protected int refill() throws IOException { if (getPacketBufferState() == BufferState.FILLING) { result = getWrappedChannel().read(getPacketBuffer()); + if (getConnection().getLogger().isLoggable(Level.INFO)) { + getConnection().getLogger().log(Level.INFO, + "Packet bytes read: " + result); + } + if (result > 0) { setPacketBufferState(BufferState.DRAINING); getPacketBuffer().flip(); @@ -117,16 +129,20 @@ protected int refill() throws IOException { @Override protected SSLEngineResult runEngine(ByteBuffer applicationBuffer) throws IOException { + if (getConnection().getLogger().isLoggable(Level.INFO)) { + getConnection().getLogger().log(Level.INFO, + "Unwrapping bytes with: " + getPacketBuffer()); + } + SSLEngineResult result = getManager().getEngine().unwrap( getPacketBuffer(), applicationBuffer); int remaining = getPacketBuffer().remaining(); if (remaining == 0) { setPacketBufferState(BufferState.FILLING); - refill(); + getPacketBuffer().clear(); } return result; } - } diff --git a/modules/org.restlet/src/org/restlet/engine/io/SslChannel.java b/modules/org.restlet/src/org/restlet/engine/io/SslChannel.java index 3041b97b99..3194f34462 100644 --- a/modules/org.restlet/src/org/restlet/engine/io/SslChannel.java +++ b/modules/org.restlet/src/org/restlet/engine/io/SslChannel.java @@ -188,7 +188,9 @@ protected void handleResult(SSLEngineResult sslResult, protected void log(SSLEngineResult sslResult) { if (Context.getCurrentLogger().isLoggable(Level.INFO)) { Context.getCurrentLogger().log(Level.INFO, - "SSL I/O result" + sslResult); + "SSL I/O result: " + sslResult); + Context.getCurrentLogger().log(Level.INFO, + "SSL Manager: " + getManager()); } } diff --git a/modules/org.restlet/src/org/restlet/engine/io/WritableSslChannel.java b/modules/org.restlet/src/org/restlet/engine/io/WritableSslChannel.java index 1030c4ad76..fca970ba0a 100644 --- a/modules/org.restlet/src/org/restlet/engine/io/WritableSslChannel.java +++ b/modules/org.restlet/src/org/restlet/engine/io/WritableSslChannel.java @@ -36,9 +36,9 @@ import javax.net.ssl.SSLEngineResult; -import org.restlet.Context; import org.restlet.engine.connector.SslConnection; import org.restlet.engine.security.SslManager; +import org.restlet.engine.security.SslState; /** * SSL byte channel that wraps all application data using the SSL/TLS protocols. @@ -77,6 +77,11 @@ protected int flush() throws IOException { if (getPacketBufferState() == BufferState.DRAINING) { result = getWrappedChannel().write(getPacketBuffer()); + if (getConnection().getLogger().isLoggable(Level.INFO)) { + getConnection().getLogger().log(Level.INFO, + "Packet bytes written: " + result); + } + if (getPacketBuffer().remaining() == 0) { setPacketBufferState(BufferState.FILLING); getPacketBuffer().clear(); @@ -89,6 +94,11 @@ protected int flush() throws IOException { @Override protected SSLEngineResult runEngine(ByteBuffer applicationBuffer) throws IOException { + if (getConnection().getLogger().isLoggable(Level.INFO)) { + getConnection().getLogger().log(Level.INFO, + "Wrapping bytes with: " + getPacketBuffer()); + } + SSLEngineResult result = getManager().getEngine().wrap( applicationBuffer, getPacketBuffer()); getPacketBuffer().flip(); @@ -96,7 +106,6 @@ protected SSLEngineResult runEngine(ByteBuffer applicationBuffer) if (remaining > 0) { setPacketBufferState(BufferState.DRAINING); - flush(); } else { getPacketBuffer().clear(); } @@ -115,21 +124,22 @@ protected SSLEngineResult runEngine(ByteBuffer applicationBuffer) public int write(ByteBuffer src) throws IOException { int result = 0; - if (Context.getCurrentLogger().isLoggable(Level.INFO)) { - Context.getCurrentLogger().log(Level.INFO, getManager().toString()); - } - // If the packet buffer isn't empty, first try to flush it flush(); // Refill the packet buffer - if (getPacketBufferState() == BufferState.FILLING) { + if ((getPacketBufferState() == BufferState.FILLING) + || (getManager().getState() == SslState.HANDSHAKING)) { int srcSize = src.remaining(); if (srcSize > 0) { - SSLEngineResult sslResult = runEngine(src); - handleResult(sslResult, src); - flush(); + while (getPacketBuffer().hasRemaining() + && (getConnection().getOutboundWay().getIoState() != IoState.IDLE)) { + SSLEngineResult sslResult = runEngine(src); + handleResult(sslResult, src); + flush(); + } + result = srcSize - src.remaining(); } } diff --git a/modules/org.restlet/src/org/restlet/engine/security/SslManager.java b/modules/org.restlet/src/org/restlet/engine/security/SslManager.java index a6728e4c9c..063205e425 100644 --- a/modules/org.restlet/src/org/restlet/engine/security/SslManager.java +++ b/modules/org.restlet/src/org/restlet/engine/security/SslManager.java @@ -146,7 +146,7 @@ public SslState getState() { @Override public String toString() { - return "SSL Manager: " + getState() + " | " + getEngine(); + return getState() + " | " + getEngine(); } /**
8933947b9549f6bbf4dd81034a6d47a22acdf895
elasticsearch
only pull Fields once from the reader--
c
https://github.com/elastic/elasticsearch
diff --git a/core/src/main/java/org/elasticsearch/search/suggest/completion/CompletionFieldStats.java b/core/src/main/java/org/elasticsearch/search/suggest/completion/CompletionFieldStats.java index e61c221a95937..90f00fb293ce7 100644 --- a/core/src/main/java/org/elasticsearch/search/suggest/completion/CompletionFieldStats.java +++ b/core/src/main/java/org/elasticsearch/search/suggest/completion/CompletionFieldStats.java @@ -20,6 +20,8 @@ package org.elasticsearch.search.suggest.completion; import com.carrotsearch.hppc.ObjectLongHashMap; + +import org.apache.lucene.index.Fields; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.LeafReader; import org.apache.lucene.index.LeafReaderContext; @@ -32,28 +34,35 @@ public class CompletionFieldStats { - public static CompletionStats completionStats(IndexReader indexReader, String ... fields) { + /** + * Returns total in-heap bytes used by all suggesters. This method is <code>O(numIndexedFields)</code>. + * + * @param fieldNamePatterns if non-null, any completion field name matching any of these patterns will break out its in-heap bytes + * separately in the returned {@link CompletionStats} + */ + public static CompletionStats completionStats(IndexReader indexReader, String ... fieldNamePatterns) { long sizeInBytes = 0; ObjectLongHashMap<String> completionFields = null; - if (fields != null && fields.length > 0) { - completionFields = new ObjectLongHashMap<>(fields.length); + if (fieldNamePatterns != null && fieldNamePatterns.length > 0) { + completionFields = new ObjectLongHashMap<>(fieldNamePatterns.length); } for (LeafReaderContext atomicReaderContext : indexReader.leaves()) { LeafReader atomicReader = atomicReaderContext.reader(); try { - for (String fieldName : atomicReader.fields()) { - Terms terms = atomicReader.fields().terms(fieldName); + Fields fields = atomicReader.fields(); + for (String fieldName : fields) { + Terms terms = fields.terms(fieldName); if (terms instanceof CompletionTerms) { // TODO: currently we load up the suggester for reporting its size long fstSize = ((CompletionTerms) terms).suggester().ramBytesUsed(); - if (fields != null && fields.length > 0 && Regex.simpleMatch(fields, fieldName)) { + if (fieldNamePatterns != null && fieldNamePatterns.length > 0 && Regex.simpleMatch(fieldNamePatterns, fieldName)) { completionFields.addTo(fieldName, fstSize); } sizeInBytes += fstSize; } } - } catch (IOException ignored) { - throw new ElasticsearchException(ignored); + } catch (IOException ioe) { + throw new ElasticsearchException(ioe); } } return new CompletionStats(sizeInBytes, completionFields);
1b7ce0a4407a5cbb1ae7cc0f3e1fc3a741cf9b86
arrayexpress$annotare2
Another round of refactoring of sign-up/sign-in functionality
p
https://github.com/arrayexpress/annotare2
diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountService.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountService.java index 82b954fd6..a56cf9e82 100644 --- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountService.java +++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountService.java @@ -28,12 +28,14 @@ */ public interface AccountService { - ValidationErrors signUp(HttpServletRequest request) throws AccountServiceException; - boolean isLoggedIn(HttpServletRequest request); ValidationErrors login(HttpServletRequest request) throws AccountServiceException; + ValidationErrors signUp(HttpServletRequest request) throws AccountServiceException; + + ValidationErrors changePassword(HttpServletRequest request) throws AccountServiceException; + void logout(HttpSession session); User getCurrentUser(HttpSession session); diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountServiceImpl.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountServiceImpl.java index 1faf49318..4dc9cae16 100644 --- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountServiceImpl.java +++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/AccountServiceImpl.java @@ -22,6 +22,7 @@ import org.slf4j.LoggerFactory; import uk.ac.ebi.fg.annotare2.db.om.User; import uk.ac.ebi.fg.annotare2.web.server.UnauthorizedAccessException; +import uk.ac.ebi.fg.annotare2.web.server.login.utils.FormParams; import uk.ac.ebi.fg.annotare2.web.server.services.AccountManager; import uk.ac.ebi.fg.annotare2.web.server.login.utils.RequestParam; import uk.ac.ebi.fg.annotare2.web.server.login.utils.SessionAttribute; @@ -33,8 +34,6 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; -import static java.util.Arrays.asList; - /** * @author Olga Melnichuk */ @@ -83,6 +82,31 @@ public ValidationErrors signUp(HttpServletRequest request) throws AccountService return errors; } + @Transactional + public ValidationErrors changePassword(HttpServletRequest request) throws AccountServiceException { + SignUpParams params = new SignUpParams(request); + ValidationErrors errors = params.validate(); + if (errors.isEmpty()) { + if (null != accountManager.getByEmail(params.getEmail())) { + errors.append("email", "User with this email already exists"); + } else { + User u = accountManager.createUser(params.getName(), params.getEmail(), params.getPassword()); + try { + emailer.sendFromTemplate( + EmailSender.NEW_USER_TEMPLATE, + ImmutableMap.of( + "to.name", u.getName(), + "to.email", u.getEmail(), + "verification.token", u.getVerificationToken() + ) + ); + } catch (MessagingException x) { + // + } + } + } + return errors; + } @Transactional public ValidationErrors login(HttpServletRequest request) throws AccountServiceException { @@ -112,78 +136,63 @@ public User getCurrentUser(HttpSession session) { return user; } - static class LoginParams { - public static final String EMAIL_PARAM = "email"; - public static final String PASSWORD_PARAM = "password"; - - private final RequestParam email; - private final RequestParam password; + static class LoginParams extends FormParams { private LoginParams(HttpServletRequest request) { - email = RequestParam.from(request, EMAIL_PARAM); - password = RequestParam.from(request, PASSWORD_PARAM); + addParam(RequestParam.from(request, EMAIL_PARAM), true); + addParam(RequestParam.from(request, PASSWORD_PARAM), true); } public ValidationErrors validate() { - ValidationErrors errors = new ValidationErrors(); - for (RequestParam p : asList(email, password)) { - if (p.isEmpty()) { - errors.append(p.getName(), "Please specify a value, " + p.getName() + " is required"); - } - } - return errors; + return validateMandatory(); } public String getEmail() { - return email.getValue(); + return getParamValue(EMAIL_PARAM); } public String getPassword() { - return password.getValue(); + return getParamValue(PASSWORD_PARAM); } } - static class SignUpParams { - public static final String NAME_PARAM = "name"; - public static final String EMAIL_PARAM = "email"; - public static final String PASSWORD_PARAM = "password"; - public static final String CONFIRM_PASSWORD_PARAM = "confirm-password"; - - private final RequestParam name; - private final RequestParam email; - private final RequestParam password; - private final RequestParam confirmPassword; + static class SignUpParams extends FormParams { private SignUpParams(HttpServletRequest request) { - name = RequestParam.from(request, NAME_PARAM); - email = RequestParam.from(request, EMAIL_PARAM); - password = RequestParam.from(request, PASSWORD_PARAM); - confirmPassword = RequestParam.from(request, CONFIRM_PASSWORD_PARAM); + addParam(RequestParam.from(request, NAME_PARAM), true); + addParam(RequestParam.from(request, EMAIL_PARAM), true); + addParam(RequestParam.from(request, PASSWORD_PARAM), true); + addParam(RequestParam.from(request, CONFIRM_PASSWORD_PARAM), false); } public ValidationErrors validate() { - ValidationErrors errors = new ValidationErrors(); - for (RequestParam p : asList(name, email, password)) { - if (p.isEmpty()) { - errors.append(p.getName(), "Please specify a value, " + p.getName() + " is required"); - } + ValidationErrors errors = validateMandatory(); + + if (!isEmailGoodEnough()) { + errors.append(EMAIL_PARAM, "Email is not valid; should at least contain @ sign"); } - if (!password.getValue().equals(confirmPassword.getValue())) { - errors.append(confirmPassword.getName(), "Passwords do not match"); + + if (!isPasswordGoodEnough()) { + errors.append(PASSWORD_PARAM, "Password is too weak; should be at least 4 characters long containing at least one digit"); + } + + if (!hasPasswordConfirmed()) { + errors.append(CONFIRM_PASSWORD_PARAM, "Passwords do not match"); } + return errors; } public String getName() { - return name.getValue(); + return getParamValue(NAME_PARAM); } public String getEmail() { - return email.getValue(); + return getParamValue(EMAIL_PARAM); } public String getPassword() { - return password.getValue(); + return getParamValue(PASSWORD_PARAM); } } } diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ChangePasswordServlet.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ChangePasswordServlet.java index 084ec5aa6..75d3dca75 100644 --- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ChangePasswordServlet.java +++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ChangePasswordServlet.java @@ -28,39 +28,46 @@ import javax.servlet.http.HttpServletResponse; import java.io.IOException; +import static uk.ac.ebi.fg.annotare2.web.server.login.ServletNavigation.CHANGE_PASSWORD; + +import static com.google.common.base.Strings.isNullOrEmpty; import static uk.ac.ebi.fg.annotare2.web.server.login.ServletNavigation.LOGIN; -import static uk.ac.ebi.fg.annotare2.web.server.login.ServletNavigation.SIGNUP; +import static uk.ac.ebi.fg.annotare2.web.server.login.SessionInformation.EMAIL_SESSION_ATTRIBUTE; +import static uk.ac.ebi.fg.annotare2.web.server.login.SessionInformation.INFO_SESSION_ATTRIBUTE; public class ChangePasswordServlet extends HttpServlet { - private static final Logger log = LoggerFactory.getLogger(SignUpServlet.class); + private static final Logger log = LoggerFactory.getLogger(ChangePasswordServlet.class); @Inject private AccountService accountService; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - log.debug("Sign-up data submitted; checking.."); + log.debug("Change password request received; processing"); ValidationErrors errors = new ValidationErrors(); + try { - errors.append(accountService.signUp(request)); + errors.append(accountService.changePassword(request)); if (errors.isEmpty()) { - log.debug("Sign-up successful; redirect to login page"); - LOGIN.redirect(request, response); - return; + if (!isNullOrEmpty(request.getParameter("token"))) { + log.debug("Password successfully changed; redirect to login page"); + INFO_SESSION_ATTRIBUTE.set(request.getSession(), "You have successfully changed password; please sign in now"); + LOGIN.redirect(request, response); + return; + } } - log.debug("Sign-up form had invalid entries"); - } catch (Exception e) { - log.debug("Sign-up failed"); + } catch (AccountServiceException e) { + log.debug("Change password request failed", e); errors.append(e.getMessage()); } request.setAttribute("errors", errors); - SIGNUP.forward(getServletConfig().getServletContext(), request, response); + CHANGE_PASSWORD.forward(getServletConfig().getServletContext(), request, response); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - SIGNUP.forward(getServletConfig().getServletContext(), request, response); + CHANGE_PASSWORD.forward(getServletConfig().getServletContext(), request, response); } } diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ServletNavigation.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ServletNavigation.java index 41d35d90e..9d1464445 100644 --- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ServletNavigation.java +++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/ServletNavigation.java @@ -38,7 +38,7 @@ enum ServletNavigation { LOGIN("/login", "/login.jsp"), SIGNUP("/sign-up", "/sign-up.jsp"), ACTIVATION("/activate", "/activate.jsp"), - PASSWORD_CHANGER("/change-password", "change-password.jsp"), + CHANGE_PASSWORD("/change-password", "/change-password.jsp"), HOME("/", "/home.jsp"), EDITOR("/edit/", "/editor.jsp"); diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/SignUpServlet.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/SignUpServlet.java index 5174f0f3e..fd8eeeb5b 100644 --- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/SignUpServlet.java +++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/SignUpServlet.java @@ -50,10 +50,10 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) LOGIN.redirect(request, response); return; } else { - log.debug("Sign-up form had invalid entries"); + log.debug("Sign-up form failed validation"); } } catch (AccountServiceException e) { - log.debug("Sign-up failed"); + log.debug("Sign-up failed", e); errors.append(e.getMessage()); } diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/utils/FormParams.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/utils/FormParams.java new file mode 100644 index 000000000..34c5a6263 --- /dev/null +++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/utils/FormParams.java @@ -0,0 +1,76 @@ +package uk.ac.ebi.fg.annotare2.web.server.login.utils; + +/* + * Copyright 2009-2013 European Molecular Biology Laboratory + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +import java.util.*; + +import static com.google.common.base.Strings.nullToEmpty; + +public abstract class FormParams { + protected static final String NAME_PARAM = "name"; + protected static final String EMAIL_PARAM = "email"; + protected static final String PASSWORD_PARAM = "password"; + protected static final String CONFIRM_PASSWORD_PARAM = "confirm-password"; + protected static final String TOKEN_PARAM = "token"; + + private Map<String,RequestParam> paramMap = new HashMap<String, RequestParam>(); + private Set<RequestParam> mandatoryParamSet = new HashSet<RequestParam>(); + + public String getParamValue(String paramName) { + if (paramMap.containsKey(paramName)) { + return paramMap.get(paramName).getValue(); + } + return null; + } + + public abstract ValidationErrors validate(); + + protected void addParam(RequestParam param, boolean isMandatory) + { + paramMap.put(param.getName(), param); + if (isMandatory) { + mandatoryParamSet.add(param); + } + } + + protected ValidationErrors validateMandatory() { + ValidationErrors errors = new ValidationErrors(); + for (RequestParam p : getMandatoryParams()) { + if (p.isEmpty()) { + errors.append(p.getName(), "Please specify a value, " + p.getName() + " is required"); + } + } + return errors; + } + + protected Collection<RequestParam> getMandatoryParams() { + return Collections.unmodifiableSet(mandatoryParamSet); + } + + protected boolean isEmailGoodEnough() { + return nullToEmpty(getParamValue(EMAIL_PARAM)).matches(".+@.+"); + } + + protected boolean isPasswordGoodEnough() { + return nullToEmpty(getParamValue(PASSWORD_PARAM)).matches("^(?=.*\\d).{4,}$"); + } + + protected boolean hasPasswordConfirmed() { + return getParamValue(PASSWORD_PARAM).equals(getParamValue(CONFIRM_PASSWORD_PARAM)); + } +} diff --git a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/utils/ValidationErrors.java b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/utils/ValidationErrors.java index 76b9d3ae2..d1263c79f 100644 --- a/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/utils/ValidationErrors.java +++ b/app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/utils/ValidationErrors.java @@ -53,7 +53,7 @@ public String getErrors() { public String getErrors(String name) { Collection<String> err = errors.get(name); - return err == null ? "" : on(", ").join(err); + return err == null ? "" : on(". ").join(err); } } diff --git a/app/web/src/main/webapp/change-password.jsp b/app/web/src/main/webapp/change-password.jsp index 3e9cae6e5..cb01a2882 100644 --- a/app/web/src/main/webapp/change-password.jsp +++ b/app/web/src/main/webapp/change-password.jsp @@ -13,29 +13,24 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --%> -<%-- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="f" %> <%@ page isELIgnored="false" %> -<%@ page import="uk.ac.ebi.fg.annotare2.web.server.login.utils.ValidationErrors" %> <% - ValidationErrors errors = (ValidationErrors) request.getAttribute("errors"); - if (errors != null) { - pageContext.setAttribute("dummyErrors", errors.getErrors()); - pageContext.setAttribute("emailErrors", errors.getErrors("email")); - pageContext.setAttribute("passwordErrors", errors.getErrors("password")); - } + pageContext.setAttribute("errors", request.getAttribute("errors")); - String[] values = request.getParameterValues("email"); - pageContext.setAttribute("email", values == null ? "" : values[0]); + String email = request.getParameter("email"); + if (null == email) { + email = (String)session.getAttribute("email"); + } + pageContext.setAttribute("email", email == null ? "" : email); %> ---%> <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> - <title>Annotare 2.0 - New user registration</title> + <title>Annotare 2.0 - Change password request</title> <link type="text/css" rel="stylesheet" href="general.css"> <link type="text/css" rel="stylesheet" href="login.css"> </head> @@ -49,38 +44,40 @@ <table class="form"> <tr> <td></td> - <td><h1>Annotare 2.0</h1></td> + <td><h1>Change password request</h1></td> </tr> - <tr class="error"> + <tr class="info"> <td></td> - <td>${dummyErrors}</td> - </tr> - <tr class="row right"> - <td>Email</td> - <td><input type="text" name="email" value="${email}" style="width:98%"/></td> + <td><c:out value="${sessionScope.info}" /><c:remove var="info" scope="session" /></td> </tr> <tr class="error"> <td></td> - <td>${emailErrors}</td> + <td>${errors}</td> </tr> <tr class="row right"> - <td>Password</td> - <td><input type="password" name="password" style="width:98%"/></td> - </tr> - <tr class="error"> - <td></td> - <td>${passwordErrors}</td> - </tr> - <tr class="row"> - <td></td> + <td>Email</td> <td> - <button name="signIn">Sign In</button>&nbsp;&nbsp;<a href="#" onclick="return false;">Forgot your password?</a> + <c:choose> + <c:when test="${email != ''}"> + <input type="text" name="email" value="${email}" style="width:98%"/> + </c:when> + <c:otherwise> + <input type="text" name="email" style="width:98%" autofocus="autofocus"/> + </c:otherwise> + </c:choose> </td> </tr> - <tr> + <tr class="row"> <td></td> <td> - <div style="margin-top:10px;">Don't have an account? <a href="#" onclick="return false;">Sign Up</a></div> + <c:choose> + <c:when test="${email != ''}"> + <button name="changePassword" autofocus="autofocus">Send</button> + </c:when> + <c:otherwise> + <button name="changePassword">Send</button> + </c:otherwise> + </c:choose> </td> </tr> </table> diff --git a/app/web/src/main/webapp/login.css b/app/web/src/main/webapp/login.css index 386e086ac..4fcb40929 100644 --- a/app/web/src/main/webapp/login.css +++ b/app/web/src/main/webapp/login.css @@ -44,7 +44,7 @@ text-align: left; } -.form { +table { border-collapse: collapse; color: #000; width: 100%; @@ -56,6 +56,10 @@ padding: 0 3px; } +.form tr td:first-child { + white-space: nowrap; +} + .form tr.row td { padding-top: 5px; padding-bottom: 5px; diff --git a/app/web/src/main/webapp/login.jsp b/app/web/src/main/webapp/login.jsp index c1e1537ac..be7d4396e 100644 --- a/app/web/src/main/webapp/login.jsp +++ b/app/web/src/main/webapp/login.jsp @@ -54,7 +54,6 @@ <tr class="info"> <td></td> <td><c:out value="${sessionScope.info}" /><c:remove var="info" scope="session" /></td> - </tr> <tr class="error"> <td></td>
6be933255f4d691485ec735c07ac5600a473d1df
belaban$jgroups
merge fast functionality (https://jira.jboss.org/jira/browse/JGRP-1191)
p
https://github.com/belaban/jgroups
diff --git a/src/org/jgroups/protocols/MERGE2.java b/src/org/jgroups/protocols/MERGE2.java index ea41b62e984..1555a978926 100644 --- a/src/org/jgroups/protocols/MERGE2.java +++ b/src/org/jgroups/protocols/MERGE2.java @@ -1,10 +1,7 @@ package org.jgroups.protocols; -import org.jgroups.Address; -import org.jgroups.Event; -import org.jgroups.View; -import org.jgroups.ViewId; +import org.jgroups.*; import org.jgroups.annotations.*; import org.jgroups.stack.Protocol; import org.jgroups.util.TimeScheduler; @@ -13,6 +10,8 @@ import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; /** @@ -39,7 +38,7 @@ * Requires: FIND_INITIAL_MBRS event from below<br> * Provides: sends MERGE event with list of coordinators up the stack<br> * @author Bela Ban, Oct 16 2001 - * @version $Id: MERGE2.java,v 1.79 2009/12/11 13:04:42 belaban Exp $ + * @version $Id: MERGE2.java,v 1.80 2010/04/15 13:00:41 belaban Exp $ */ @MBean(description="Protocol to discover subgroups existing due to a network partition") @DeprecatedProperty(names={"use_separate_thread"}) @@ -57,6 +56,13 @@ public class MERGE2 extends Protocol { @Property(description="Number of inconsistent views with only 1 coord after a MERGE event is sent up") protected int inconsistent_view_threshold=1; + @Property(description="When receiving a multicast message, checks if the sender is member of the cluster. " + + "If not, initiates a merge") + protected boolean merge_fast=true; + + @Property(description="The delay (in milliseconds) after which a merge fast execution is started") + protected long merge_fast_delay=1000; + /* ---------------------------------------------- JMX -------------------------------------------------------- */ @ManagedAttribute(writable=false, description="whether or not a merge task is currently running " + "(should be the case in a coordinator") @@ -69,6 +75,10 @@ public boolean isMergeTaskRunning() { private Address local_addr=null; private View view; + + private final Set<Address> members=new HashSet<Address>(); + + private final Set<Address> merge_candidates=new HashSet<Address>(); private final FindSubgroupsTask task=new FindSubgroupsTask(); @@ -133,6 +143,7 @@ public void sendMergeSolicitation() { public void stop() { is_coord=false; + merge_candidates.clear(); task.stop(); } @@ -148,6 +159,9 @@ public Object down(Event evt) { task.stop(); return ret; } + members.clear(); + members.addAll(mbrs); + merge_candidates.removeAll(members); Address coord=mbrs.elementAt(0); if(coord.equals(local_addr)) { is_coord=true; @@ -170,8 +184,31 @@ public Object down(Event evt) { default: return down_prot.down(evt); // Pass on to the layer below us } - } + } + public Object up(Event evt) { + switch(evt.getType()) { + case Event.MSG: + if(!merge_fast) + break; + Message msg=(Message)evt.getArg(); + Address dest=msg.getDest(); + boolean multicast=dest == null || dest.isMulticastAddress(); + if(!multicast) + break; + final Address sender=msg.getSrc(); + if(!members.contains(sender) && merge_candidates.add(sender)) { + timer.schedule(new Runnable() { + public void run() { + if(!members.contains(sender)) + task.findAndNotify(); + } + }, merge_fast_delay, TimeUnit.MILLISECONDS); + } + break; + } + return up_prot.up(evt); + } /** * Task periodically executing (if role is coordinator). Gets the initial membership and determines @@ -181,6 +218,7 @@ public Object down(Event evt) { private class FindSubgroupsTask { @GuardedBy("this") private Future<?> future; + private Lock lock=new ReentrantLock(); public synchronized void start() { if(future == null || future.isDone() || future.isCancelled()) { @@ -205,6 +243,17 @@ public synchronized boolean isRunning() { public void findAndNotify() { + if(lock.tryLock()) { + try { + _findAndNotify(); + } + finally { + lock.unlock(); + } + } + } + + private void _findAndNotify() { List<PingData> discovery_rsps=findAllMembers(); if(log.isTraceEnabled()) { @@ -258,6 +307,7 @@ public void findAndNotify() { } } + /** * Returns a random value within [min_interval - max_interval] */
069787a17d70841274d75458735e433288da53cb
Valadoc
drivers: Add 0.14.x driver
a
https://github.com/GNOME/vala/
diff --git a/configure.in b/configure.in index 40cafa4b57..4aaf044813 100755 --- a/configure.in +++ b/configure.in @@ -1,6 +1,6 @@ dnl configure.in AC_PREREQ(2.59) -AC_INIT(Valadoc, 0.3.1, [email protected]) +AC_INIT(Valadoc, 0.3.2, [email protected]) AM_INIT_AUTOMAKE AC_CONFIG_SRCDIR([src/valadoc/valadoc.vala]) AC_CONFIG_HEADER([config.h]) @@ -62,6 +62,13 @@ AC_SUBST(LIBGDKPIXBUF_LIBS) ## Drivers: ## + +PKG_CHECK_MODULES(LIBVALA_0_14_X, libvala-0.14 >= 0.14.0, have_libvala_0_14_x="yes", have_libvala_0_14_x="no") +AM_CONDITIONAL(HAVE_LIBVALA_0_14_X, test "$have_libvala_0_14_x" = "yes") +AC_SUBST(LIBVALA_0_14_X_CFLAGS) +AC_SUBST(LIBVALA_0_14_X_LIBS) + + PKG_CHECK_MODULES(LIBVALA_0_13_X, libvala-0.14 >= 0.13.1, have_libvala_0_13_x="yes", have_libvala_0_13_x="no") AM_CONDITIONAL(HAVE_LIBVALA_0_13_X, test "$have_libvala_0_13_x" = "yes") AC_SUBST(LIBVALA_0_13_X_CFLAGS) @@ -112,6 +119,7 @@ AC_CONFIG_FILES([Makefile src/driver/0.11.x/Makefile src/driver/0.12.x/Makefile src/driver/0.13.x/Makefile + src/driver/0.14.x/Makefile src/doclets/Makefile src/doclets/htm/Makefile src/doclets/devhelp/Makefile diff --git a/src/driver/0.13.x/treebuilder.vala b/src/driver/0.13.x/treebuilder.vala index efb8d44a0a..9739d927c2 100644 --- a/src/driver/0.13.x/treebuilder.vala +++ b/src/driver/0.13.x/treebuilder.vala @@ -405,7 +405,8 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { return null; } - SourceFile file = files.get (source_ref.file); + SourceFile? file = files.get (source_ref.file); + assert (file != null); return file; } @@ -606,8 +607,10 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { } string vapi_name = pkg + ".vapi"; + string gir_name = pkg + ".gir"; foreach (string source_file in settings.source_files) { - if (Path.get_basename (source_file) == vapi_name) { + string basename = Path.get_basename (source_file); + if (basename == vapi_name || basename == gir_name) { return true; } } @@ -735,6 +738,8 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { context.experimental_non_null = settings.experimental || settings.experimental_non_null; context.vapi_directories = settings.vapi_directories; context.report.enable_warnings = settings.verbose; + context.metadata_directories = settings.metadata_directories; + context.gir_directories = settings.gir_directories; if (settings.basedir == null) { context.basedir = realpath ("."); @@ -1127,6 +1132,10 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { public override void visit_error_code (Vala.ErrorCode element) { Api.ErrorDomain parent = (ErrorDomain) get_parent_node_for (element); SourceFile? file = get_source_file (element); + if (file == null) { + file = parent.get_source_file (); + } + SourceComment? comment = create_comment (element.comment); Symbol node = new Api.ErrorCode (parent, file, element.name, comment, get_cname (element), Vala.GDBusModule.get_dbus_name_for_member (element), element); diff --git a/src/driver/0.14.x/Makefile.am b/src/driver/0.14.x/Makefile.am new file mode 100755 index 0000000000..cc9d610ee0 --- /dev/null +++ b/src/driver/0.14.x/Makefile.am @@ -0,0 +1,63 @@ +NULL = + + + +AM_CFLAGS = -g \ + -DPACKAGE_ICONDIR=\"$(datadir)/valadoc/icons/\" \ + -I ../../libvaladoc/ \ + $(GLIB_CFLAGS) \ + $(LIBGEE_CFLAGS) \ + $(LIBVALA_0_14_X_CFLAGS) \ + $(NULL) + + + +BUILT_SOURCES = libdriver.vala.stamp + + +driverdir = $(libdir)/valadoc/drivers/0.14.x + + +libdriver_la_LDFLAGS = -module -avoid-version -no-undefined + + +driver_LTLIBRARIES = \ + libdriver.la \ + $(NULL) + + +libdriver_la_VALASOURCES = \ + initializerbuilder.vala \ + symbolresolver.vala \ + treebuilder.vala \ + driver.vala \ + $(NULL) + + +libdriver_la_SOURCES = \ + libdriver.vala.stamp \ + $(libdriver_la_VALASOURCES:.vala=.c) \ + $(NULL) + + +libdriver.vala.stamp: $(libdriver_la_VALASOURCES) + $(VALAC) $(VALA_FLAGS) -C --vapidir $(top_srcdir)/src/vapi --vapidir $(top_srcdir)/src/libvaladoc --pkg libvala-0.14 --pkg gee-1.0 --pkg valadoc-1.0 --basedir . $^ + touch $@ + + +libdriver_la_LIBADD = \ + ../../libvaladoc/libvaladoc.la \ + $(GLIB_LIBS) \ + $(LIBVALA_0_14_X_LIBS) \ + $(LIBGEE_LIBS) \ + $(NULL) + + +EXTRA_DIST = $(libdriver_la_VALASOURCES) libdriver.vala.stamp + + +MAINTAINERCLEANFILES = \ + $(libdriver_la_VALASOURCES:.vala=.c) \ + $(NULL) + + diff --git a/src/driver/0.14.x/driver.vala b/src/driver/0.14.x/driver.vala new file mode 100755 index 0000000000..6fc87d97a3 --- /dev/null +++ b/src/driver/0.14.x/driver.vala @@ -0,0 +1,51 @@ +/* driver.vala + * + * Copyright (C) 2011 Florian Brosch + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Author: + * Florian Brosch <[email protected]> + */ + +using Valadoc.Api; +using Gee; + + + +/** + * Creates an simpler, minimized, more abstract AST for valacs AST. + */ +public class Valadoc.Drivers.Driver : Object, Valadoc.Driver { + + public Api.Tree? build (Settings settings, ErrorReporter reporter) { + TreeBuilder builder = new TreeBuilder (); + Api.Tree? tree = builder.build (settings, reporter); + if (reporter.errors > 0) { + return null; + } + + SymbolResolver resolver = new SymbolResolver (builder); + tree.accept (resolver); + + return tree; + } +} + + +public Type register_plugin (Valadoc.ModuleLoader module_loader) { + return typeof (Valadoc.Drivers.Driver); +} + diff --git a/src/driver/0.14.x/initializerbuilder.vala b/src/driver/0.14.x/initializerbuilder.vala new file mode 100644 index 0000000000..70fd1d6bb9 --- /dev/null +++ b/src/driver/0.14.x/initializerbuilder.vala @@ -0,0 +1,676 @@ +/* initializerbuilder.vala + * + * Copyright (C) 2011 Florian Brosch + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Author: + * Florian Brosch <[email protected]> + */ + + +using Valadoc.Content; +using Gee; + + +private class Valadoc.Api.InitializerBuilder : Vala.CodeVisitor { + private HashMap<Vala.Symbol, Symbol> symbol_map; + private SignatureBuilder signature; + + private Symbol? resolve (Vala.Symbol symbol) { + return symbol_map.get (symbol); + } + + private void write_node (Vala.Symbol vsymbol) { + signature.append_symbol (resolve (vsymbol)); + } + + private void write_type (Vala.DataType vsymbol) { + if (vsymbol.data_type != null) { + write_node (vsymbol.data_type); + } else { + signature.append_literal ("null"); + } + + var type_args = vsymbol.get_type_arguments (); + if (type_args.size > 0) { + signature.append ("<"); + bool first = true; + foreach (Vala.DataType type_arg in type_args) { + if (!first) { + signature.append (","); + } else { + first = false; + } + if (!type_arg.value_owned) { + signature.append_keyword ("weak"); + } + signature.append (type_arg.to_qualified_string (null)); + } + signature.append (">"); + } + + if (vsymbol.nullable) { + signature.append ("?"); + } + } + + /** + * {@inheritDoc} + */ + public override void visit_array_creation_expression (Vala.ArrayCreationExpression expr) { + signature.append_keyword ("new"); + write_type (expr.element_type); + signature.append ("[", false); + + bool first = true; + foreach (Vala.Expression size in expr.get_sizes ()) { + if (!first) { + signature.append (", ", false); + } + size.accept (this); + first = false; + } + + signature.append ("]", false); + + if (expr.initializer_list != null) { + signature.append (" ", false); + expr.initializer_list.accept (this); + } + } + + public InitializerBuilder (SignatureBuilder signature, HashMap<Vala.Symbol, Symbol> symbol_map) { + this.symbol_map = symbol_map; + this.signature = signature; + } + + /** + * {@inheritDoc} + */ + public override void visit_binary_expression (Vala.BinaryExpression expr) { + expr.left.accept (this); + + switch (expr.operator) { + case Vala.BinaryOperator.PLUS: + signature.append ("+ "); + break; + + case Vala.BinaryOperator.MINUS: + signature.append ("- "); + break; + + case Vala.BinaryOperator.MUL: + signature.append ("* "); + break; + + case Vala.BinaryOperator.DIV: + signature.append ("/ "); + break; + + case Vala.BinaryOperator.MOD: + signature.append ("% "); + break; + + case Vala.BinaryOperator.SHIFT_LEFT: + signature.append ("<< "); + break; + + case Vala.BinaryOperator.SHIFT_RIGHT: + signature.append (">> "); + break; + + case Vala.BinaryOperator.LESS_THAN: + signature.append ("< "); + break; + + case Vala.BinaryOperator.GREATER_THAN: + signature.append ("> "); + break; + + case Vala.BinaryOperator.LESS_THAN_OR_EQUAL: + signature.append ("<= "); + break; + + case Vala.BinaryOperator.GREATER_THAN_OR_EQUAL: + signature.append (">= "); + break; + + case Vala.BinaryOperator.EQUALITY: + signature.append ("== "); + break; + + case Vala.BinaryOperator.INEQUALITY: + signature.append ("!= "); + break; + + case Vala.BinaryOperator.BITWISE_AND: + signature.append ("& "); + break; + + case Vala.BinaryOperator.BITWISE_OR: + signature.append ("| "); + break; + + case Vala.BinaryOperator.BITWISE_XOR: + signature.append ("^ "); + break; + + case Vala.BinaryOperator.AND: + signature.append ("&& "); + break; + + case Vala.BinaryOperator.OR: + signature.append ("|| "); + break; + + case Vala.BinaryOperator.IN: + signature.append_keyword ("in"); + signature.append (" "); + break; + + case Vala.BinaryOperator.COALESCE: + signature.append ("?? "); + break; + + default: + assert_not_reached (); + } + + expr.right.accept (this); + } + + /** + * {@inheritDoc} + */ + public override void visit_unary_expression (Vala.UnaryExpression expr) { + switch (expr.operator) { + case Vala.UnaryOperator.PLUS: + signature.append ("+"); + break; + + case Vala.UnaryOperator.MINUS: + signature.append ("-"); + break; + + case Vala.UnaryOperator.LOGICAL_NEGATION: + signature.append ("!"); + break; + + case Vala.UnaryOperator.BITWISE_COMPLEMENT: + signature.append ("~"); + break; + + case Vala.UnaryOperator.INCREMENT: + signature.append ("++"); + break; + + case Vala.UnaryOperator.DECREMENT: + signature.append ("--"); + break; + + case Vala.UnaryOperator.REF: + signature.append_keyword ("ref"); + break; + + case Vala.UnaryOperator.OUT: + signature.append_keyword ("out"); + break; + + default: + assert_not_reached (); + } + expr.inner.accept (this); + } + + /** + * {@inheritDoc} + */ + public override void visit_assignment (Vala.Assignment a) { + a.left.accept (this); + + switch (a.operator) { + case Vala.AssignmentOperator.SIMPLE: + signature.append ("="); + break; + + case Vala.AssignmentOperator.BITWISE_OR: + signature.append ("|"); + break; + + case Vala.AssignmentOperator.BITWISE_AND: + signature.append ("&"); + break; + + case Vala.AssignmentOperator.BITWISE_XOR: + signature.append ("^"); + break; + + case Vala.AssignmentOperator.ADD: + signature.append ("+"); + break; + + case Vala.AssignmentOperator.SUB: + signature.append ("-"); + break; + + case Vala.AssignmentOperator.MUL: + signature.append ("*"); + break; + + case Vala.AssignmentOperator.DIV: + signature.append ("/"); + break; + + case Vala.AssignmentOperator.PERCENT: + signature.append ("%"); + break; + + case Vala.AssignmentOperator.SHIFT_LEFT: + signature.append ("<<"); + break; + + case Vala.AssignmentOperator.SHIFT_RIGHT: + signature.append (">>"); + break; + + default: + assert_not_reached (); + } + + a.right.accept (this); + } + + /** + * {@inheritDoc} + */ + public override void visit_cast_expression (Vala.CastExpression expr) { + if (expr.is_non_null_cast) { + signature.append ("(!)"); + expr.inner.accept (this); + return; + } + + if (!expr.is_silent_cast) { + signature.append ("(", false); + write_type (expr.type_reference); + signature.append (")", false); + } + + expr.inner.accept (this); + + if (expr.is_silent_cast) { + signature.append_keyword ("as"); + write_type (expr.type_reference); + } + } + + /** + * {@inheritDoc} + */ + public override void visit_initializer_list (Vala.InitializerList list) { + signature.append ("{", false); + + bool first = true; + foreach (Vala.Expression initializer in list.get_initializers ()) { + if (!first) { + signature.append (", ", false); + } + first = false; + initializer.accept (this); + } + + signature.append ("}", false); + } + + /** + * {@inheritDoc} + */ + public override void visit_member_access (Vala.MemberAccess expr) { + if (expr.symbol_reference != null) { + expr.symbol_reference.accept (this); + } else { + signature.append (expr.member_name); + } + } + + /** + * {@inheritDoc} + */ + public override void visit_element_access (Vala.ElementAccess expr) { + expr.container.accept (this); + signature.append ("[", false); + + bool first = true; + foreach (Vala.Expression index in expr.get_indices ()) { + if (!first) { + signature.append (", ", false); + } + first = false; + + index.accept (this); + } + + signature.append ("]", false); + } + + /** + * {@inheritDoc} + */ + public override void visit_pointer_indirection (Vala.PointerIndirection expr) { + signature.append ("*", false); + expr.inner.accept (this); + } + + /** + * {@inheritDoc} + */ + public override void visit_addressof_expression (Vala.AddressofExpression expr) { + signature.append ("&", false); + expr.inner.accept (this); + } + + /** + * {@inheritDoc} + */ + public override void visit_reference_transfer_expression (Vala.ReferenceTransferExpression expr) { + signature.append ("(", false).append_keyword ("owned", false).append (")", false); + expr.inner.accept (this); + } + + /** + * {@inheritDoc} + */ + public override void visit_type_check (Vala.TypeCheck expr) { + expr.expression.accept (this); + signature.append_keyword ("is"); + write_type (expr.type_reference); + } + + /** + * {@inheritDoc} + */ + public override void visit_method_call (Vala.MethodCall expr) { + // symbol-name: + expr.call.symbol_reference.accept (this); + + // parameters: + signature.append (" (", false); + bool first = true; + foreach (Vala.Expression literal in expr.get_argument_list ()) { + if (!first) { + signature.append (", ", false); + } + + literal.accept (this); + first = false; + } + signature.append (")", false); + } + + /** + * {@inheritDoc} + */ + public override void visit_slice_expression (Vala.SliceExpression expr) { + expr.container.accept (this); + signature.append ("[", false); + expr.start.accept (this); + signature.append (":", false); + expr.stop.accept (this); + signature.append ("]", false); + } + + /** + * {@inheritDoc} + */ + public override void visit_base_access (Vala.BaseAccess expr) { + signature.append_keyword ("base", false); + } + + /** + * {@inheritDoc} + */ + public override void visit_postfix_expression (Vala.PostfixExpression expr) { + expr.inner.accept (this); + if (expr.increment) { + signature.append ("++", false); + } else { + signature.append ("--", false); + } + } + + /** + * {@inheritDoc} + */ + public override void visit_object_creation_expression (Vala.ObjectCreationExpression expr) { + if (!expr.struct_creation) { + signature.append_keyword ("new"); + } + + signature.append_symbol (resolve (expr.symbol_reference)); + + signature.append (" (", false); + + //TODO: rm conditional space + bool first = true; + foreach (Vala.Expression arg in expr.get_argument_list ()) { + if (!first) { + signature.append (", ", false); + } + arg.accept (this); + first = false; + } + + signature.append (")", false); + } + + /** + * {@inheritDoc} + */ + public override void visit_sizeof_expression (Vala.SizeofExpression expr) { + signature.append_keyword ("sizeof", false).append (" (", false); + write_type (expr.type_reference); + signature.append (")", false); + } + + /** + * {@inheritDoc} + */ + public override void visit_typeof_expression (Vala.TypeofExpression expr) { + signature.append_keyword ("typeof", false).append (" (", false); + write_type (expr.type_reference); + signature.append (")", false); + } + + /** + * {@inheritDoc} + */ + public override void visit_lambda_expression (Vala.LambdaExpression expr) { + signature.append ("(", false); + + bool first = true; + foreach (Vala.Parameter param in expr.get_parameters ()) { + if (!first) { + signature.append (", ", false); + } + signature.append (param.name, false); + first = false; + } + + + signature.append (") => {", false); + signature.append_highlighted (" [...] ", false); + signature.append ("}", false); + } + + + + /** + * {@inheritDoc} + */ + public override void visit_boolean_literal (Vala.BooleanLiteral lit) { + signature.append_literal (lit.to_string (), false); + } + + /** + * {@inheritDoc} + */ + public override void visit_character_literal (Vala.CharacterLiteral lit) { + signature.append_literal (lit.to_string (), false); + } + + /** + * {@inheritDoc} + */ + public override void visit_integer_literal (Vala.IntegerLiteral lit) { + signature.append_literal (lit.to_string (), false); + } + + /** + * {@inheritDoc} + */ + public override void visit_real_literal (Vala.RealLiteral lit) { + signature.append_literal (lit.to_string (), false); + } + + /** + * {@inheritDoc} + */ + public override void visit_regex_literal (Vala.RegexLiteral lit) { + signature.append_literal (lit.to_string (), false); + } + + /** + * {@inheritDoc} + */ + public override void visit_string_literal (Vala.StringLiteral lit) { + signature.append_literal (lit.to_string (), false); + } + + /** + * {@inheritDoc} + */ + public override void visit_list_literal (Vala.ListLiteral lit) { + signature.append_literal (lit.to_string (), false); + } + + /** + * {@inheritDoc} + */ + public override void visit_null_literal (Vala.NullLiteral lit) { + signature.append_literal (lit.to_string (), false); + } + + + + /** + * {@inheritDoc} + */ + public override void visit_field (Vala.Field field) { + write_node (field); + } + + /** + * {@inheritDoc} + */ + public override void visit_constant (Vala.Constant constant) { + write_node (constant); + } + + /** + * {@inheritDoc} + */ + public override void visit_enum_value (Vala.EnumValue ev) { + write_node (ev); + } + + /** + * {@inheritDoc} + */ + public override void visit_error_code (Vala.ErrorCode ec) { + write_node (ec); + } + + /** + * {@inheritDoc} + */ + public override void visit_delegate (Vala.Delegate d) { + write_node (d); + } + + /** + * {@inheritDoc} + */ + public override void visit_method (Vala.Method m) { + write_node (m); + } + + /** + * {@inheritDoc} + */ + public override void visit_creation_method (Vala.CreationMethod m) { + write_node (m); + } + + /** + * {@inheritDoc} + */ + public override void visit_signal (Vala.Signal sig) { + write_node (sig); + } + + /** + * {@inheritDoc} + */ + public override void visit_class (Vala.Class c) { + write_node (c); + } + + /** + * {@inheritDoc} + */ + public override void visit_struct (Vala.Struct s) { + write_node (s); + } + + /** + * {@inheritDoc} + */ + public override void visit_interface (Vala.Interface i) { + write_node (i); + } + + /** + * {@inheritDoc} + */ + public override void visit_enum (Vala.Enum en) { + write_node (en); + } + + /** + * {@inheritDoc} + */ + public override void visit_error_domain (Vala.ErrorDomain ed) { + write_node (ed); + } + + /** + * {@inheritDoc} + */ + public override void visit_property (Vala.Property prop) { + write_node (prop); + } +} + diff --git a/src/driver/0.14.x/symbolresolver.vala b/src/driver/0.14.x/symbolresolver.vala new file mode 100644 index 0000000000..ad47b3b46f --- /dev/null +++ b/src/driver/0.14.x/symbolresolver.vala @@ -0,0 +1,307 @@ +/* symbolresolver.vala + * + * Copyright (C) 2011 Florian Brosch + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Author: + * Florian Brosch <[email protected]> + */ + +using Valadoc.Api; +using Gee; + + +public class Valadoc.Drivers.SymbolResolver : Visitor { + private HashMap<Vala.Symbol, Symbol> symbol_map; + private Valadoc.Api.Class glib_error; + private Api.Tree root; + + public SymbolResolver (TreeBuilder builder) { + this.symbol_map = builder.get_symbol_map (); + this.glib_error = builder.get_glib_error (); + } + + private Symbol? resolve (Vala.Symbol symbol) { + return symbol_map.get (symbol); + } + + private void resolve_array_type_references (Api.Array ptr) { + Api.Item data_type = ptr.data_type; + if (data_type == null) { + // void + } else if (data_type is Api.Array) { + resolve_array_type_references ((Api.Array) data_type); + } else if (data_type is Pointer) { + resolve_pointer_type_references ((Api.Pointer) data_type); + } else { + resolve_type_reference ((TypeReference) data_type); + } + } + + private void resolve_pointer_type_references (Pointer ptr) { + Api.Item type = ptr.data_type; + if (type == null) { + // void + } else if (type is Api.Array) { + resolve_array_type_references ((Api.Array) type); + } else if (type is Pointer) { + resolve_pointer_type_references ((Pointer) type); + } else { + resolve_type_reference ((TypeReference) type); + } + } + + private void resolve_type_reference (TypeReference reference) { + Vala.DataType vtyperef = (Vala.DataType) reference.data; + if (vtyperef is Vala.ErrorType) { + Vala.ErrorDomain verrdom = ((Vala.ErrorType) vtyperef).error_domain; + if (verrdom != null) { + reference.data_type = resolve (verrdom); + } else { + reference.data_type = glib_error; + } + } else if (vtyperef is Vala.DelegateType) { + reference.data_type = resolve (((Vala.DelegateType) vtyperef).delegate_symbol); + } else if (vtyperef.data_type != null) { + reference.data_type = resolve (vtyperef.data_type); + } + + // Type parameters: + foreach (TypeReference type_param_ref in reference.get_type_arguments ()) { + resolve_type_reference (type_param_ref); + } + + if (reference.data_type is Pointer) { + resolve_pointer_type_references ((Pointer)reference.data_type); + } else if (reference.data_type is Api.Array) { + resolve_array_type_references ((Api.Array)reference.data_type); + } + } + + /** + * {@inheritDoc} + */ + public override void visit_tree (Api.Tree item) { + this.root = item; + item.accept_children (this); + this.root = null; + } + + /** + * {@inheritDoc} + */ + public override void visit_package (Package item) { + item.accept_all_children (this, false); + } + + /** + * {@inheritDoc} + */ + public override void visit_namespace (Namespace item) { + item.accept_all_children (this, false); + } + + /** + * {@inheritDoc} + */ + public override void visit_interface (Interface item) { + Collection<TypeReference> interfaces = item.get_implemented_interface_list (); + foreach (var type_ref in interfaces) { + resolve_type_reference (type_ref); + } + + if (item.base_type != null) { + resolve_type_reference (item.base_type); + } + + item.accept_all_children (this, false); + } + + /** + * {@inheritDoc} + */ + public override void visit_class (Class item) { + Collection<TypeReference> interfaces = item.get_implemented_interface_list (); + foreach (TypeReference type_ref in interfaces) { + resolve_type_reference (type_ref); + } + + if (item.base_type != null) { + resolve_type_reference (item.base_type); + } + + item.accept_all_children (this, false); + } + + /** + * {@inheritDoc} + */ + public override void visit_struct (Struct item) { + if (item.base_type != null) { + resolve_type_reference (item.base_type); + } + + item.accept_all_children (this, false); + } + + /** + * {@inheritDoc} + */ + public override void visit_property (Property item) { + Vala.Property vala_property = item.data as Vala.Property; + Vala.Property? base_vala_property = null; + + if (vala_property.base_property != null) { + base_vala_property = vala_property.base_property; + } else if (vala_property.base_interface_property != null) { + base_vala_property = vala_property.base_interface_property; + } + if (base_vala_property == vala_property && vala_property.base_interface_property != null) { + base_vala_property = vala_property.base_interface_property; + } + if (base_vala_property != null) { + item.base_property = (Property?) resolve (base_vala_property); + } + + resolve_type_reference (item.property_type); + + item.accept_all_children (this, false); + } + + /** + * {@inheritDoc} + */ + public override void visit_field (Field item) { + resolve_type_reference (item.field_type); + + item.accept_all_children (this, false); + } + + /** + * {@inheritDoc} + */ + public override void visit_constant (Constant item) { + resolve_type_reference (item.constant_type); + + item.accept_all_children (this, false); + } + + /** + * {@inheritDoc} + */ + public override void visit_delegate (Delegate item) { + resolve_type_reference (item.return_type); + + item.accept_all_children (this, false); + } + + /** + * {@inheritDoc} + */ + public override void visit_signal (Api.Signal item) { + resolve_type_reference (item.return_type); + + item.accept_all_children (this, false); + } + + /** + * {@inheritDoc} + */ + public override void visit_method (Method item) { + Vala.Method vala_method = item.data as Vala.Method; + Vala.Method? base_vala_method = null; + if (vala_method.base_method != null) { + base_vala_method = vala_method.base_method; + } else if (vala_method.base_interface_method != null) { + base_vala_method = vala_method.base_interface_method; + } + if (base_vala_method == vala_method && vala_method.base_interface_method != null) { + base_vala_method = vala_method.base_interface_method; + } + if (base_vala_method != null) { + item.base_method = (Method?) resolve (base_vala_method); + } + + resolve_type_reference (item.return_type); + + item.accept_all_children (this, false); + } + + /** + * {@inheritDoc} + */ + public override void visit_type_parameter (TypeParameter item) { + item.accept_all_children (this, false); + } + + /** + * {@inheritDoc} + */ + public override void visit_formal_parameter (FormalParameter item) { + if (item.ellipsis) { + return; + } + + if (((Vala.Parameter) item.data).initializer != null) { + SignatureBuilder signature = new SignatureBuilder (); + InitializerBuilder ibuilder = new InitializerBuilder (signature, symbol_map); + ((Vala.Parameter) item.data).initializer.accept (ibuilder); + item.default_value = signature.get (); + } + + resolve_type_reference (item.parameter_type); + item.accept_all_children (this, false); + } + + /** + * {@inheritDoc} + */ + public override void visit_error_domain (ErrorDomain item) { + item.accept_all_children (this, false); + } + + /** + * {@inheritDoc} + */ + public override void visit_error_code (ErrorCode item) { + item.accept_all_children (this, false); + } + + /** + * {@inheritDoc} + */ + public override void visit_enum (Enum item) { + item.accept_all_children (this, false); + } + + /** + * {@inheritDoc} + */ + public override void visit_enum_value (Api.EnumValue item) { + + if (((Vala.EnumValue) item.data).value != null) { + SignatureBuilder signature = new SignatureBuilder (); + InitializerBuilder ibuilder = new InitializerBuilder (signature, symbol_map); + ((Vala.EnumValue) item.data).value.accept (ibuilder); + item.default_value = signature.get (); + } + + item.accept_all_children (this, false); + } +} + + + diff --git a/src/driver/0.14.x/treebuilder.vala b/src/driver/0.14.x/treebuilder.vala new file mode 100644 index 0000000000..691faddd4d --- /dev/null +++ b/src/driver/0.14.x/treebuilder.vala @@ -0,0 +1,1135 @@ +/* treebuilder.vala + * + * Copyright (C) 2011 Florian Brosch + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Author: + * Florian Brosch <[email protected]> + */ + + +using Valadoc.Api; +using Gee; + + +/** + * Creates an simpler, minimized, more abstract AST for valacs AST. + */ +public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { + private ArrayList<PackageMetaData> packages = new ArrayList<PackageMetaData> (); + private PackageMetaData source_package; + + private HashMap<Vala.SourceFile, SourceFile> files = new HashMap<Vala.SourceFile, SourceFile> (); + private HashMap<Vala.Symbol, Symbol> symbol_map = new HashMap<Vala.Symbol, Symbol> (); + + private ErrorReporter reporter; + private Settings settings; + + private Api.Node current_node; + private Api.Tree tree; + + private Valadoc.Api.Class glib_error = null; + + + // + // Accessors + // + + public Api.Class get_glib_error () { + return glib_error; + } + + public HashMap<Vala.Symbol, Symbol> get_symbol_map () { + return symbol_map; + } + + + // + // + // + + private class PackageMetaData { + public Package package; + public HashMap<Vala.Namespace, Namespace> namespaces = new HashMap<Vala.Namespace, Namespace> (); + public ArrayList<Vala.SourceFile> files = new ArrayList<Vala.SourceFile> (); + + public PackageMetaData (Package package) { + this.package = package; + } + + public Namespace get_namespace (Vala.Namespace vns, SourceFile? file) { + Namespace? ns = namespaces.get (vns); + if (ns != null) { + return ns; + } + + // find documentation comment if existing: + SourceComment? comment = null; + if (vns.source_reference != null) { + foreach (Vala.Comment c in vns.get_comments()) { + if (c.source_reference.file == vns.source_reference.file) { + Vala.SourceReference pos = c.source_reference; + comment = new SourceComment (c.content, file, pos.first_line, pos.first_column, pos.last_line, pos.last_column); + break; + } + } + } + + // find parent if existing + var parent_vns = vns.parent_symbol; + + if (parent_vns == null) { + ns = new Namespace (package, file, vns.name, comment, vns); + package.add_child (ns); + } else { + Namespace parent_ns = get_namespace ((Vala.Namespace) parent_vns, file); + ns = new Namespace (parent_ns, file, vns.name, comment, vns); + parent_ns.add_child (ns); + } + + namespaces.set (vns, ns); + return ns; + } + + public void register_source_file (Vala.SourceFile file) { + files.add (file); + } + + public bool is_package_for_file (Vala.SourceFile source_file) { + if (source_file.file_type == Vala.SourceFileType.SOURCE && !package.is_package) { + return true; + } + + return files.contains (source_file); + } + } + + + // + // Type constructor translation helpers: + // + + private Pointer create_pointer (Vala.PointerType vtyperef, Item parent, Api.Node caller) { + Pointer ptr = new Pointer (parent, vtyperef); + + Vala.DataType vntype = vtyperef.base_type; + if (vntype is Vala.PointerType) { + ptr.data_type = create_pointer ((Vala.PointerType) vntype, ptr, caller); + } else if (vntype is Vala.ArrayType) { + ptr.data_type = create_array ((Vala.ArrayType) vntype, ptr, caller); + } else { + ptr.data_type = create_type_reference (vntype, ptr, caller); + } + + return ptr; + } + + private Api.Array create_array (Vala.ArrayType vtyperef, Item parent, Api.Node caller) { + Api.Array arr = new Api.Array (parent, vtyperef); + + Vala.DataType vntype = vtyperef.element_type; + if (vntype is Vala.ArrayType) { + arr.data_type = create_array ((Vala.ArrayType) vntype, arr, caller); + } else { + arr.data_type = create_type_reference (vntype, arr, caller); + } + + return arr; + } + + private TypeReference create_type_reference (Vala.DataType? vtyperef, Item parent, Api.Node caller) { + bool is_nullable = vtyperef != null && vtyperef.nullable && !(vtyperef is Vala.GenericType) && !(vtyperef is Vala.PointerType); + string? signature = (vtyperef != null && vtyperef.data_type != null)? Vala.GVariantModule.get_dbus_signature (vtyperef.data_type) : null; + bool pass_ownership = type_reference_pass_ownership (vtyperef); + Ownership ownership = get_type_reference_ownership (vtyperef); + bool is_dynamic = vtyperef != null && vtyperef.is_dynamic; + + TypeReference type_ref = new TypeReference (parent, ownership, pass_ownership, is_dynamic, is_nullable, signature, vtyperef); + + if (vtyperef is Vala.PointerType) { + type_ref.data_type = create_pointer ((Vala.PointerType) vtyperef, type_ref, caller); + } else if (vtyperef is Vala.ArrayType) { + type_ref.data_type = create_array ((Vala.ArrayType) vtyperef, type_ref, caller); + } else if (vtyperef is Vala.GenericType) { + type_ref.data_type = new TypeParameter (caller, caller.get_source_file (), ((Vala.GenericType) vtyperef).type_parameter.name, vtyperef); + } + + // type parameters: + if (vtyperef != null) { + foreach (Vala.DataType vdtype in vtyperef.get_type_arguments ()) { + var type_param = create_type_reference (vdtype, type_ref, caller); + type_ref.add_type_argument (type_param); + } + } + + return type_ref; + } + + + + // + // Translation helpers: + // + + private void process_attributes (Api.Symbol parent, GLib.List<Vala.Attribute> lst) { + // attributes wihtout arguments: + string[] attributes = { + "ReturnsModifiedPointer", + "DestroysInstance", + "NoAccessorMethod", + "NoArrayLength", + "Experimental", + "Diagnostics", + "PrintfFormat", + "PointerType", + "ScanfFormat", + "ThreadLocal", + "SimpleType", + "HasEmitter", + "ModuleInit", + "NoWrapper", + "Immutable", + "ErrorBase", + "NoReturn", + "NoThrow", + "Assert", + "Flags" + }; + + string? tmp = ""; + + foreach (Vala.Attribute att in lst) { + if (att.name == "CCode" && (tmp = att.args.get ("has_target")) != null && tmp == "false") { + Attribute new_attribute = new Attribute (parent, parent.get_source_file (), att.name, att); + new_attribute.add_boolean ("has_target", false, att); + parent.add_attribute (new_attribute); + } else if (att.name == "Deprecated") { + Attribute new_attribute = new Attribute (parent, parent.get_source_file (), att.name, att); + parent.add_attribute (new_attribute); + if ((tmp = att.args.get ("since")) != null) { + new_attribute.add_string ("since", tmp, att); + } + + if ((tmp = att.args.get ("replacement")) != null) { + new_attribute.add_string ("replacement", tmp, att); + } + } else if (att.name in attributes) { + Attribute new_attribute = new Attribute (parent, parent.get_source_file (), att.name, att); + parent.add_attribute (new_attribute); + } + } + } + + private string get_ccode_type_id (Vala.Class node) { + return Vala.CCodeBaseModule.get_ccode_type_id (node); + } + + private bool is_reference_counting (Vala.TypeSymbol sym) { + return Vala.CCodeBaseModule.is_reference_counting (sym); + } + + private string get_ref_function (Vala.Class sym) { + return Vala.CCodeBaseModule.get_ccode_ref_function (sym); + } + + private string get_unref_function (Vala.Class sym) { + return Vala.CCodeBaseModule.get_ccode_unref_function (sym); + } + + private string get_finish_name (Vala.Method m) { + return Vala.CCodeBaseModule.get_ccode_finish_name (m); + } + + private string get_take_value_function (Vala.Class sym) { + return Vala.CCodeBaseModule.get_ccode_take_value_function (sym); + } + + private string get_get_value_function (Vala.Class sym) { + return Vala.CCodeBaseModule.get_ccode_get_value_function (sym); + } + + private string get_set_value_function (Vala.Class sym) { + return Vala.CCodeBaseModule.get_ccode_set_value_function (sym); + } + + + private string get_param_spec_function (Vala.CodeNode sym) { + return Vala.CCodeBaseModule.get_ccode_param_spec_function (sym); + } + + private string? get_dup_function (Vala.TypeSymbol sym) { + return Vala.CCodeBaseModule.get_ccode_dup_function (sym); + } + + private string get_free_function (Vala.TypeSymbol sym) { + return Vala.CCodeBaseModule.get_ccode_free_function (sym); + } + + private string get_nick (Vala.Property prop) { + return Vala.CCodeBaseModule.get_ccode_nick (prop); + } + + private string? get_cname (Vala.Symbol symbol) { + return Vala.CCodeBaseModule.get_ccode_name (symbol); + } + + private SourceComment? create_comment (Vala.Comment? comment) { + if (comment != null) { + Vala.SourceReference pos = comment.source_reference; + SourceFile file = files.get (pos.file); + return new SourceComment (comment.content, file, pos.first_line, pos.first_column, pos.last_line, pos.last_column); + } + + return null; + } + + private string get_method_name (Vala.Method element) { + if (element is Vala.CreationMethod) { + if (element.name == ".new") { + return element.parent_symbol.name; + } else { + return element.parent_symbol.name + "." + element.name; + } + } + + return element.name; + } + + private PackageMetaData? get_package_meta_data (Package pkg) { + foreach (PackageMetaData data in packages) { + if (data.package == pkg) { + return data; + } + } + + return null; + } + + private PackageMetaData register_package (Package package) { + PackageMetaData meta_data = new PackageMetaData (package); + tree.add_package (package); + packages.add (meta_data); + return meta_data; + } + + private SourceFile register_source_file (PackageMetaData meta_data, Vala.SourceFile source_file) { + SourceFile file = new SourceFile (source_file.get_relative_filename (), source_file.get_csource_filename ()); + files.set (source_file, file); + + meta_data.register_source_file (source_file); + return file; + } + + private SourceFile? get_source_file (Vala.Symbol symbol) { + Vala.SourceReference source_ref = symbol.source_reference; + if (source_ref == null) { + return null; + } + + SourceFile? file = files.get (source_ref.file); + + assert (file != null); + return file; + } + + private Package? find_package_for_file (Vala.SourceFile source_file) { + foreach (PackageMetaData pkg in this.packages) { + if (pkg.is_package_for_file (source_file)) { + return pkg.package; + } + } + + return null; + } + + + private Namespace get_namespace (Package pkg, Vala.Symbol symbol, SourceFile? file) { + // Find the closest namespace in our vala-tree + Vala.Symbol namespace_symbol = symbol; + while (!(namespace_symbol is Vala.Namespace)) { + namespace_symbol = namespace_symbol.parent_symbol; + } + + PackageMetaData? meta_data = get_package_meta_data (pkg); + assert (meta_data != null); + + return meta_data.get_namespace ((Vala.Namespace) namespace_symbol, file); + } + + private MethodBindingType get_method_binding_type (Vala.Method element) { + if (element.is_inline) { + return MethodBindingType.INLINE; + } else if (element.is_abstract) { + return MethodBindingType.ABSTRACT; + } else if (element.is_virtual) { + return MethodBindingType.VIRTUAL; + } else if (element.overrides) { + return MethodBindingType.OVERRIDE; + } else if (element.is_inline) { + return MethodBindingType.INLINE; + } else if (element.binding != Vala.MemberBinding.INSTANCE) { + return MethodBindingType.STATIC; + } + return MethodBindingType.UNMODIFIED; + } + + + private SymbolAccessibility get_access_modifier(Vala.Symbol symbol) { + switch (symbol.access) { + case Vala.SymbolAccessibility.PROTECTED: + return SymbolAccessibility.PROTECTED; + + case Vala.SymbolAccessibility.INTERNAL: + return SymbolAccessibility.INTERNAL; + + case Vala.SymbolAccessibility.PRIVATE: + return SymbolAccessibility.PRIVATE; + + case Vala.SymbolAccessibility.PUBLIC: + return SymbolAccessibility.PUBLIC; + + default: + error ("Unknown symbol accessibility modifier found"); + } + } + + private PropertyAccessorType get_property_accessor_type (Vala.PropertyAccessor element) { + if (element.construction) { + return PropertyAccessorType.CONSTRUCT; + } else if (element.writable) { + return PropertyAccessorType.SET; + } else if (element.readable) { + return PropertyAccessorType.GET; + } + + error ("Unknown symbol accessibility type"); + } + + private bool type_reference_pass_ownership (Vala.DataType? element) { + if (element == null) { + return false; + } + + weak Vala.CodeNode? node = element.parent_node; + if (node == null) { + return false; + } + if (node is Vala.Parameter) { + return (((Vala.Parameter)node).direction == Vala.ParameterDirection.IN && + ((Vala.Parameter)node).variable_type.value_owned); + } + if (node is Vala.Property) { + return ((Vala.Property)node).property_type.value_owned; + } + + return false; + } + + private bool is_type_reference_unowned (Vala.DataType? element) { + if (element == null) { + return false; + } + + // non ref counted types are weak, not unowned + if (element.data_type is Vala.TypeSymbol && is_reference_counting ((Vala.TypeSymbol) element.data_type) == true) { + return false; + } + + // FormalParameters are weak by default + return (element.parent_node is Vala.Parameter == false)? element.is_weak () : false; + } + + private bool is_type_reference_owned (Vala.DataType? element) { + if (element == null) { + return false; + } + + weak Vala.CodeNode parent = element.parent_node; + + // parameter: + if (parent is Vala.Parameter) { + if (((Vala.Parameter)parent).direction != Vala.ParameterDirection.IN) { + return false; + } + return ((Vala.Parameter)parent).variable_type.value_owned; + } + + return false; + } + + private bool is_type_reference_weak (Vala.DataType? element) { + if (element == null) { + return false; + } + + // non ref counted types are unowned, not weak + if (element.data_type is Vala.TypeSymbol && is_reference_counting ((Vala.TypeSymbol) element.data_type) == false) { + return false; + } + + // FormalParameters are weak by default + return (element.parent_node is Vala.Parameter == false)? element.is_weak () : false; + } + + private Ownership get_type_reference_ownership (Vala.DataType? element) { + if (is_type_reference_owned (element)) { + return Ownership.OWNED; + } else if (is_type_reference_weak (element)) { + return Ownership.WEAK; + } else if (is_type_reference_unowned (element)) { + return Ownership.UNOWNED; + } + + return Ownership.DEFAULT; + } + + private Ownership get_property_ownership (Vala.PropertyAccessor element) { + if (element.value_type.value_owned) { + return Ownership.OWNED; + } + + // the exact type (weak, unowned) does not matter + return Ownership.UNOWNED; + } + + private PropertyBindingType get_property_binding_type (Vala.Property element) { + if (element.is_abstract) { + return PropertyBindingType.ABSTRACT; + } else if (element.is_virtual) { + return PropertyBindingType.VIRTUAL; + } else if (element.overrides) { + return PropertyBindingType.OVERRIDE; + } + + return PropertyBindingType.UNMODIFIED; + } + + private FormalParameterType get_formal_parameter_type (Vala.Parameter element) { + if (element.direction == Vala.ParameterDirection.OUT) { + return FormalParameterType.OUT; + } else if (element.direction == Vala.ParameterDirection.REF) { + return FormalParameterType.REF; + } else if (element.direction == Vala.ParameterDirection.IN) { + return FormalParameterType.IN; + } + + error ("Unknown formal parameter type"); + } + + + // + // Vala tree creation: + // + + private bool add_package (Vala.CodeContext context, string pkg) { + // ignore multiple occurences of the same package + if (context.has_package (pkg)) { + return true; + } + + string vapi_name = pkg + ".vapi"; + string gir_name = pkg + ".gir"; + foreach (string source_file in settings.source_files) { + string basename = Path.get_basename (source_file); + if (basename == vapi_name || basename == gir_name) { + return true; + } + } + + + var package_path = context.get_vapi_path (pkg) ?? context.get_gir_path (pkg); + if (package_path == null) { + Vala.Report.error (null, "Package `%s' not found in specified Vala API directories or GObject-Introspection GIR directories".printf (pkg)); + return false; + } + + context.add_package (pkg); + + var vfile = new Vala.SourceFile (context, Vala.SourceFileType.PACKAGE, package_path); + context.add_source_file (vfile); + Package vdpkg = new Package (pkg, true, null); + register_source_file (register_package (vdpkg), vfile); + + add_deps (context, Path.build_filename (Path.get_dirname (package_path), "%s.deps".printf (pkg)), pkg); + return true; + } + + private void add_deps (Vala.CodeContext context, string file_path, string pkg_name) { + if (FileUtils.test (file_path, FileTest.EXISTS)) { + try { + string deps_content; + ulong deps_len; + FileUtils.get_contents (file_path, out deps_content, out deps_len); + foreach (string dep in deps_content.split ("\n")) { + dep.strip (); + if (dep != "") { + if (!add_package (context, dep)) { + Vala.Report.error (null, "%s, dependency of %s, not found in specified Vala API directories".printf (dep, pkg_name)); + } + } + } + } catch (FileError e) { + Vala.Report.error (null, "Unable to read dependency file: %s".printf (e.message)); + } + } + } + + /** + * Adds the specified packages to the list of used packages. + * + * @param context The code context + * @param packages a list of package names + */ + private void add_depencies (Vala.CodeContext context, string[] packages) { + foreach (string package in packages) { + if (!add_package (context, package)) { + Vala.Report.error (null, "Package `%s' not found in specified Vala API directories or GObject-Introspection GIR directories".printf (package)); + } + } + } + + /** + * Add the specified source file to the context. Only .vala, .vapi, .gs, + * and .c files are supported. + */ + private void add_documented_files (Vala.CodeContext context, string[] sources) { + if (sources == null) { + return; + } + + foreach (string source in sources) { + if (FileUtils.test (source, FileTest.EXISTS)) { + var rpath = realpath (source); + if (source.has_suffix (".vala") || source.has_suffix (".gs")) { + var source_file = new Vala.SourceFile (context, Vala.SourceFileType.SOURCE, rpath); + + if (source_package == null) { + source_package = register_package (new Package (settings.pkg_name, false, null)); + } + + register_source_file (source_package, source_file); + + if (context.profile == Vala.Profile.POSIX) { + // import the Posix namespace by default (namespace of backend-specific standard library) + var ns_ref = new Vala.UsingDirective (new Vala.UnresolvedSymbol (null, "Posix", null)); + source_file.add_using_directive (ns_ref); + context.root.add_using_directive (ns_ref); + } else if (context.profile == Vala.Profile.GOBJECT) { + // import the GLib namespace by default (namespace of backend-specific standard library) + var ns_ref = new Vala.UsingDirective (new Vala.UnresolvedSymbol (null, "GLib", null)); + source_file.add_using_directive (ns_ref); + context.root.add_using_directive (ns_ref); + } + + context.add_source_file (source_file); + } else if (source.has_suffix (".vapi") || source.has_suffix (".gir")) { + string file_name = Path.get_basename (source); + file_name = file_name.substring (0, file_name.last_index_of_char ('.')); + + var vfile = new Vala.SourceFile (context, Vala.SourceFileType.PACKAGE, rpath); + context.add_source_file (vfile); + + if (source_package == null) { + source_package = register_package (new Package (settings.pkg_name, false, null)); + } + + register_source_file (source_package, vfile); + + add_deps (context, Path.build_filename (Path.get_dirname (source), "%s.deps".printf (file_name)), file_name); + } else if (source.has_suffix (".c")) { + context.add_c_source_file (rpath); + tree.add_external_c_files (rpath); + } else { + Vala.Report.error (null, "%s is not a supported source file type. Only .vala, .vapi, .gs, and .c files are supported.".printf (source)); + } + } else { + Vala.Report.error (null, "%s not found".printf (source)); + } + } + } + + private Vala.CodeContext create_valac_tree (Settings settings) { + // init context: + var context = new Vala.CodeContext (); + Vala.CodeContext.push (context); + + + // settings: + context.experimental = settings.experimental; + context.experimental_non_null = settings.experimental || settings.experimental_non_null; + context.vapi_directories = settings.vapi_directories; + context.report.enable_warnings = settings.verbose; + context.metadata_directories = settings.metadata_directories; + context.gir_directories = settings.gir_directories; + + if (settings.basedir == null) { + context.basedir = realpath ("."); + } else { + context.basedir = realpath (settings.basedir); + } + + if (settings.directory != null) { + context.directory = realpath (settings.directory); + } else { + context.directory = context.basedir; + } + + + // add default packages: + if (settings.profile == "gobject-2.0" || settings.profile == "gobject" || settings.profile == null) { + context.profile = Vala.Profile.GOBJECT; + context.add_define ("GOBJECT"); + } + + + if (settings.defines != null) { + foreach (string define in settings.defines) { + context.add_define (define); + } + } + + if (context.profile == Vala.Profile.POSIX) { + // default package + if (!add_package (context, "posix")) { + Vala.Report.error (null, "posix not found in specified Vala API directories"); + } + } else if (context.profile == Vala.Profile.GOBJECT) { + int glib_major = 2; + int glib_minor = 12; + + context.target_glib_major = glib_major; + context.target_glib_minor = glib_minor; + if (context.target_glib_major != 2) { + Vala.Report.error (null, "This version of valac only supports GLib 2"); + } + + // default packages + if (!this.add_package (context, "glib-2.0")) { // + Vala.Report.error (null, "glib-2.0 not found in specified Vala API directories"); + } + + if (!this.add_package (context, "gobject-2.0")) { // + Vala.Report.error (null, "gobject-2.0 not found in specified Vala API directories"); + } + } + + + // add user defined files: + add_depencies (context, settings.packages); + if (reporter.errors > 0) { + return context; + } + + add_documented_files (context, settings.source_files); + if (reporter.errors > 0) { + return context; + } + + + // parse vala-code: + Vala.Parser parser = new Vala.Parser (); + + parser.parse (context); + if (context.report.get_errors () > 0) { + return context; + } + + // parse gir: + Vala.GirParser gir_parser = new Vala.GirParser (); + + gir_parser.parse (context); + if (context.report.get_errors () > 0) { + return context; + } + + + + // check context: + context.check (); + if (context.report.get_errors () > 0) { + return context; + } + + return context; + } + + + + // + // Valadoc tree creation: + // + + private void process_children (Api.Node node, Vala.CodeNode element) { + Api.Node old_node = current_node; + current_node = node; + element.accept_children (this); + current_node = old_node; + } + + private Api.Node get_parent_node_for (Vala.Symbol element) { + if (current_node != null) { + return current_node; + } + + Vala.SourceFile vala_source_file = element.source_reference.file; + Package package = find_package_for_file (vala_source_file); + SourceFile? source_file = get_source_file (element); + + return get_namespace (package, element, source_file); + } + + /** + * {@inheritDoc} + */ + public override void visit_namespace (Vala.Namespace element) { + element.accept_children (this); + } + + /** + * {@inheritDoc} + */ + public override void visit_class (Vala.Class element) { + Api.Node parent = get_parent_node_for (element); + SourceFile? file = get_source_file (element); + SourceComment? comment = create_comment (element.comment); + + bool is_basic_type = element.base_class == null && element.name == "string"; + + Class node = new Class (parent, file, element.name, get_access_modifier(element), comment, get_cname (element), Vala.GDBusModule.get_dbus_name (element), get_param_spec_function (element), get_ccode_type_id (element), get_ref_function (element), get_unref_function (element), get_take_value_function (element), get_get_value_function (element), get_set_value_function (element), element.is_fundamental (), element.is_abstract, is_basic_type, element); + symbol_map.set (element, node); + parent.add_child (node); + + // relations + foreach (Vala.DataType vala_type_ref in element.get_base_types ()) { + var type_ref = create_type_reference (vala_type_ref, node, node); + + if (vala_type_ref.data_type is Vala.Interface) { + node.add_interface (type_ref); + } else if (vala_type_ref.data_type is Vala.Class) { + node.base_type = type_ref; + } + } + + process_attributes (node, element.attributes); + process_children (node, element); + + // save GLib.Error + if (glib_error == null && node.get_full_name () == "GLib.Error") { + glib_error = node; + } + } + + /** + * {@inheritDoc} + */ + public override void visit_interface (Vala.Interface element) { + Api.Node parent = get_parent_node_for (element); + SourceFile? file = get_source_file (element); + SourceComment? comment = create_comment (element.comment); + + Interface node = new Interface (parent, file, element.name, get_access_modifier(element), comment, get_cname (element), Vala.GDBusModule.get_dbus_name (element), element); + symbol_map.set (element, node); + parent.add_child (node); + + // prerequisites: + foreach (Vala.DataType vala_type_ref in element.get_prerequisites ()) { + TypeReference type_ref = create_type_reference (vala_type_ref, node, node); + if (vala_type_ref.data_type is Vala.Interface) { + node.add_interface (type_ref); + } else { + node.base_type = type_ref; + } + } + + process_attributes (node, element.attributes); + process_children (node, element); + } + + /** + * {@inheritDoc} + */ + public override void visit_struct (Vala.Struct element) { + Api.Node parent = get_parent_node_for (element); + SourceFile? file = get_source_file (element); + SourceComment? comment = create_comment (element.comment); + + bool is_basic_type = element.base_type == null && (element.is_boolean_type () || element.is_floating_type () || element.is_integer_type ()); + + Struct node = new Struct (parent, file, element.name, get_access_modifier(element), comment, get_cname(element), get_dup_function (element), get_free_function (element), is_basic_type, element); + symbol_map.set (element, node); + parent.add_child (node); + + // parent type: + Vala.ValueType? basetype = element.base_type as Vala.ValueType; + if (basetype != null) { + node.base_type = create_type_reference (basetype, node, node); + } + + process_attributes (node, element.attributes); + process_children (node, element); + } + + /** + * {@inheritDoc} + */ + public override void visit_field (Vala.Field element) { + Api.Node parent = get_parent_node_for (element); + SourceFile? file = get_source_file (element); + SourceComment? comment = create_comment (element.comment); + + Field node = new Field (parent, file, element.name, get_access_modifier(element), comment, get_cname (element), element.binding == Vala.MemberBinding.STATIC, element.is_volatile, element); + node.field_type = create_type_reference (element.variable_type, node, node); + symbol_map.set (element, node); + parent.add_child (node); + + process_attributes (node, element.attributes); + process_children (node, element); + } + + /** + * {@inheritDoc} + */ + public override void visit_property (Vala.Property element) { + Api.Node parent = get_parent_node_for (element); + SourceFile? file = get_source_file (element); + SourceComment? comment = create_comment (element.comment); + + Property node = new Property (parent, file, element.name, get_access_modifier(element), comment, get_nick (element), Vala.GDBusModule.get_dbus_name_for_member (element), Vala.GDBusServerModule.is_dbus_visible (element), get_property_binding_type (element), element); + node.property_type = create_type_reference (element.property_type, node, node); + symbol_map.set (element, node); + parent.add_child (node); + + // Process property type + if (element.get_accessor != null) { + var accessor = element.get_accessor; + node.getter = new PropertyAccessor (node, file, element.name, get_access_modifier(element), get_cname (element), get_property_accessor_type (accessor), get_property_ownership (accessor), accessor); + } + + if (element.set_accessor != null) { + var accessor = element.set_accessor; + node.setter = new PropertyAccessor (node, file, element.name, get_access_modifier(element), get_cname (element), get_property_accessor_type (accessor), get_property_ownership (accessor), accessor); + } + + process_attributes (node, element.attributes); + process_children (node, element); + } + + /** + * {@inheritDoc} + */ + public override void visit_creation_method (Vala.CreationMethod element) { + Api.Node parent = get_parent_node_for (element); + SourceFile? file = get_source_file (element); + SourceComment? comment = create_comment (element.comment); + + Method node = new Method (parent, file, get_method_name (element), get_access_modifier(element), comment, get_cname (element), Vala.GDBusModule.get_dbus_name_for_member (element), Vala.GDBusServerModule.dbus_result_name (element), (element.coroutine)? get_finish_name (element) : null, get_method_binding_type (element), element.coroutine, Vala.GDBusServerModule.is_dbus_visible (element), element is Vala.CreationMethod, element); + node.return_type = create_type_reference (element.return_type, node, node); + symbol_map.set (element, node); + parent.add_child (node); + + process_attributes (node, element.attributes); + process_children (node, element); + } + + /** + * {@inheritDoc} + */ + public override void visit_method (Vala.Method element) { + Api.Node parent = get_parent_node_for (element); + SourceFile? file = get_source_file (element); + SourceComment? comment = create_comment (element.comment); + + Method node = new Method (parent, file, get_method_name (element), get_access_modifier(element), comment, get_cname (element), Vala.GDBusModule.get_dbus_name_for_member (element), Vala.GDBusServerModule.dbus_result_name (element), (element.coroutine)? get_finish_name (element) : null, get_method_binding_type (element), element.coroutine, Vala.GDBusServerModule.is_dbus_visible (element), element is Vala.CreationMethod, element); + node.return_type = create_type_reference (element.return_type, node, node); + symbol_map.set (element, node); + parent.add_child (node); + + process_attributes (node, element.attributes); + process_children (node, element); + } + + /** + * {@inheritDoc} + */ + public override void visit_signal (Vala.Signal element) { + Api.Node parent = get_parent_node_for (element); + SourceFile? file = get_source_file (element); + SourceComment? comment = create_comment (element.comment); + + Api.Signal node = new Api.Signal (parent, file, element.name, get_access_modifier(element), comment, get_cname (element), Vala.GDBusModule.get_dbus_name_for_member (element), Vala.GDBusServerModule.is_dbus_visible (element), element.is_virtual, element); + node.return_type = create_type_reference (element.return_type, node, node); + symbol_map.set (element, node); + parent.add_child (node); + + process_attributes (node, element.attributes); + process_children (node, element); + } + + /** + * {@inheritDoc} + */ + public override void visit_delegate (Vala.Delegate element) { + Api.Node parent = get_parent_node_for (element); + SourceFile? file = get_source_file (element); + SourceComment? comment = create_comment (element.comment); + + Delegate node = new Delegate (parent, file, element.name, get_access_modifier(element), comment, get_cname (element), element.has_target, element); + node.return_type = create_type_reference (element.return_type, node, node); + symbol_map.set (element, node); + parent.add_child (node); + + process_attributes (node, element.attributes); + process_children (node, element); + } + + /** + * {@inheritDoc} + */ + public override void visit_enum (Vala.Enum element) { + Api.Node parent = get_parent_node_for (element); + SourceFile? file = get_source_file (element); + SourceComment? comment = create_comment (element.comment); + + Symbol node = new Enum (parent, file, element.name, get_access_modifier(element), comment, get_cname (element), element); + symbol_map.set (element, node); + parent.add_child (node); + + process_attributes (node, element.attributes); + process_children (node, element); + } + + /** + * {@inheritDoc} + */ + public override void visit_enum_value (Vala.EnumValue element) { + Api.Enum parent = (Enum) get_parent_node_for (element); + SourceFile? file = get_source_file (element); + SourceComment? comment = create_comment (element.comment); + + Symbol node = new Api.EnumValue (parent, file, element.name, comment, get_cname (element), element); + symbol_map.set (element, node); + parent.add_child (node); + + process_attributes (node, element.attributes); + process_children (node, element); + } + + /** + * {@inheritDoc} + */ + public override void visit_constant (Vala.Constant element) { + Api.Node parent = get_parent_node_for (element); + SourceFile? file = get_source_file (element); + SourceComment? comment = create_comment (element.comment); + + Constant node = new Constant (parent, file, element.name, get_access_modifier(element), comment, get_cname (element), element); + node.constant_type = create_type_reference (element.type_reference, node, node); + symbol_map.set (element, node); + parent.add_child (node); + + process_attributes (node, element.attributes); + process_children (node, element); + } + + /** + * {@inheritDoc} + */ + public override void visit_error_domain (Vala.ErrorDomain element) { + Api.Node parent = get_parent_node_for (element); + SourceFile? file = get_source_file (element); + SourceComment? comment = create_comment (element.comment); + + Symbol node = new ErrorDomain (parent, file, element.name, get_access_modifier(element), comment, get_cname(element), Vala.GDBusModule.get_dbus_name (element), element); + symbol_map.set (element, node); + parent.add_child (node); + + process_attributes (node, element.attributes); + process_children (node, element); + } + + /** + * {@inheritDoc} + */ + public override void visit_error_code (Vala.ErrorCode element) { + Api.ErrorDomain parent = (ErrorDomain) get_parent_node_for (element); + SourceFile? file = get_source_file (element); + if (file == null) { + file = parent.get_source_file (); + } + + SourceComment? comment = create_comment (element.comment); + + Symbol node = new Api.ErrorCode (parent, file, element.name, comment, get_cname (element), Vala.GDBusModule.get_dbus_name_for_member (element), element); + symbol_map.set (element, node); + parent.add_child (node); + + process_attributes (node, element.attributes); + process_children (node, element); + } + + /** + * {@inheritDoc} + */ + public override void visit_type_parameter (Vala.TypeParameter element) { + Api.Node parent = get_parent_node_for (element); + SourceFile? file = get_source_file (element); + + Symbol node = new TypeParameter (parent, file, element.name, element); + parent.add_child (node); + + process_children (node, element); + } + + /** + * {@inheritDoc} + */ + public override void visit_formal_parameter (Vala.Parameter element) { + Api.Node parent = get_parent_node_for (element); + SourceFile? file = get_source_file (element); + + FormalParameter node = new FormalParameter (parent, file, element.name, get_access_modifier(element), get_formal_parameter_type (element), element.ellipsis, element); + node.parameter_type = create_type_reference (element.variable_type, node, node); + parent.add_child (node); + + process_children (node, element); + } + + + // + // startpoint: + // + + public Api.Tree? build (Settings settings, ErrorReporter reporter) { + this.tree = new Api.Tree (reporter, settings); + this.settings = settings; + this.reporter = reporter; + + var context = create_valac_tree (settings); + + reporter.warnings_offset = context.report.get_warnings (); + reporter.errors_offset = context.report.get_errors (); + + if (context == null) { + return null; + } + + context.accept(this); + + return (reporter.errors == 0)? tree : null; + } +} + + diff --git a/src/driver/Makefile.am b/src/driver/Makefile.am index aced67d5e6..f431d4b949 100755 --- a/src/driver/Makefile.am +++ b/src/driver/Makefile.am @@ -26,12 +26,17 @@ if HAVE_LIBVALA_0_13_X DRIVER_0_13_X_DIR = 0.13.x endif +if HAVE_LIBVALA_0_14_X +DRIVER_0_14_X_DIR = 0.14.x +endif + SUBDIRS = \ $(DRIVER_0_10_X_DIR) \ $(DRIVER_0_11_0_DIR) \ $(DRIVER_0_11_X_DIR) \ $(DRIVER_0_12_X_DIR) \ $(DRIVER_0_13_X_DIR) \ + $(DRIVER_0_14_X_DIR) \ $(NULL) diff --git a/src/libvaladoc/settings.vala b/src/libvaladoc/settings.vala index 1a4a4ba191..5237fabc43 100755 --- a/src/libvaladoc/settings.vala +++ b/src/libvaladoc/settings.vala @@ -125,6 +125,17 @@ public class Valadoc.Settings : Object { * A list of all source files. */ public string[] source_files; + + + /** + * A list of all metadata directories + */ + public string[] metadata_directories; + + /** + * A list of all gir directories. + */ + public string[] gir_directories; } diff --git a/src/valadoc/valadoc.vala b/src/valadoc/valadoc.vala index 1697c9e0ce..71ac6b6056 100755 --- a/src/valadoc/valadoc.vala +++ b/src/valadoc/valadoc.vala @@ -61,6 +61,10 @@ public class ValaDoc : Object { [CCode (array_length = false, array_null_terminated = true)] private static string[] vapi_directories; [CCode (array_length = false, array_null_terminated = true)] + private static string[] metadata_directories; + [CCode (array_length = false, array_null_terminated = true)] + private static string[] gir_directories; + [CCode (array_length = false, array_null_terminated = true)] private static string[] tsources; [CCode (array_length = false, array_null_terminated = true)] private static string[] packages; @@ -75,6 +79,8 @@ public class ValaDoc : Object { { "enable-experimental", 0, 0, OptionArg.NONE, ref experimental, "Enable experimental features", null }, { "enable-experimental-non-null", 0, 0, OptionArg.NONE, ref experimental_non_null, "Enable experimental enhancements for non-null types", null }, + { "metadatadir", 0, 0, OptionArg.FILENAME_ARRAY, ref metadata_directories, "Look for GIR .metadata files in DIRECTORY", "DIRECTORY..." }, + { "girdir", 0, 0, OptionArg.FILENAME_ARRAY, ref gir_directories, "Look for .gir files in DIRECTORY", "DIRECTORY..." }, { "vapidir", 0, 0, OptionArg.FILENAME_ARRAY, ref vapi_directories, "Look for package bindings in DIRECTORY", "DIRECTORY..." }, { "pkg", 0, 0, OptionArg.STRING_ARRAY, ref packages, "Include binding for PACKAGE", "PACKAGE..." }, @@ -243,7 +249,8 @@ public class ValaDoc : Object { DriverMetaData (LibvalaVersion (0, 11, 0), LibvalaVersion (0, 11, 0), "0.11.0"), DriverMetaData (LibvalaVersion (0, 11, 1), LibvalaVersion (0, 11, -1), "0.11.x"), DriverMetaData (LibvalaVersion (0, 12, 0), LibvalaVersion (0, 12, -1), "0.12.x"), - DriverMetaData (LibvalaVersion (0, 13, 0), LibvalaVersion (0, 13, -1), "0.13.x") + DriverMetaData (LibvalaVersion (0, 13, 0), LibvalaVersion (0, 13, -1), "0.13.x"), + DriverMetaData (LibvalaVersion (0, 14, 0), LibvalaVersion (0, 14, -1), "0.14.x") }; for (int i = 0; i < lut.length ; i++) { @@ -314,6 +321,8 @@ public class ValaDoc : Object { settings.basedir = basedir; settings.directory = directory; settings.vapi_directories = vapi_directories; + settings.metadata_directories = metadata_directories; + settings.gir_directories = gir_directories; settings.source_files = tsources; settings.packages = packages;
935b63527dacf2c380a53ce83ca5b1d06aadca75
ReactiveX-RxJava
Baseline Performance Tests--Start of suite of general performance tests for comparing overall changes.-
p
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/perf/java/rx/usecases/PerfBaseline.java b/rxjava-core/src/perf/java/rx/usecases/PerfBaseline.java new file mode 100644 index 0000000000..c349253f84 --- /dev/null +++ b/rxjava-core/src/perf/java/rx/usecases/PerfBaseline.java @@ -0,0 +1,36 @@ +package rx.usecases; + +import java.util.Iterator; + +import org.openjdk.jmh.annotations.GenerateMicroBenchmark; + +public class PerfBaseline { + + @GenerateMicroBenchmark + public void forLoopConsumption(UseCaseInput input) throws InterruptedException { + for (int i = 0; i < input.size; i++) { + input.observer.onNext(i); + } + } + + @GenerateMicroBenchmark + public void observableConsumption(UseCaseInput input) throws InterruptedException { + input.observable.subscribe(input.observer); + input.awaitCompletion(); + } + + @GenerateMicroBenchmark + public void iterableViaForLoopConsumption(UseCaseInput input) throws InterruptedException { + for (int i : input.iterable) { + input.observer.onNext(i); + } + } + + @GenerateMicroBenchmark + public void iterableViaHasNextConsumption(UseCaseInput input) throws InterruptedException { + Iterator<Integer> iterator = input.iterable.iterator(); + while (iterator.hasNext()) { + input.observer.onNext(iterator.next()); + } + } +} diff --git a/rxjava-core/src/perf/java/rx/usecases/PerfObserveOn.java b/rxjava-core/src/perf/java/rx/usecases/PerfObserveOn.java index 3b6aa1d2ea..6200cae9d4 100644 --- a/rxjava-core/src/perf/java/rx/usecases/PerfObserveOn.java +++ b/rxjava-core/src/perf/java/rx/usecases/PerfObserveOn.java @@ -22,9 +22,21 @@ public class PerfObserveOn { @GenerateMicroBenchmark - public void observeOn(UseCaseInput input) throws InterruptedException { + public void observeOnComputation(UseCaseInput input) throws InterruptedException { input.observable.observeOn(Schedulers.computation()).subscribe(input.observer); input.awaitCompletion(); } + @GenerateMicroBenchmark + public void observeOnNewThread(UseCaseInput input) throws InterruptedException { + input.observable.observeOn(Schedulers.newThread()).subscribe(input.observer); + input.awaitCompletion(); + } + + @GenerateMicroBenchmark + public void observeOnImmediate(UseCaseInput input) throws InterruptedException { + input.observable.observeOn(Schedulers.immediate()).subscribe(input.observer); + input.awaitCompletion(); + } + } diff --git a/rxjava-core/src/perf/java/rx/usecases/PerfTransforms.java b/rxjava-core/src/perf/java/rx/usecases/PerfTransforms.java index 8b56734e5d..ee8150c3d0 100644 --- a/rxjava-core/src/perf/java/rx/usecases/PerfTransforms.java +++ b/rxjava-core/src/perf/java/rx/usecases/PerfTransforms.java @@ -19,12 +19,24 @@ import rx.Observable; import rx.functions.Func1; -import rx.schedulers.Schedulers; public class PerfTransforms { @GenerateMicroBenchmark - public void mapTransformation(UseCaseInput input) throws InterruptedException { + public void mapPassThru(UseCaseInput input) throws InterruptedException { + input.observable.map(new Func1<Integer, Integer>() { + + @Override + public Integer call(Integer i) { + return i; + } + + }).subscribe(input.observer); + input.awaitCompletion(); + } + + @GenerateMicroBenchmark + public void mapIntStringInt(UseCaseInput input) throws InterruptedException { input.observable.map(new Func1<Integer, String>() { @Override @@ -44,7 +56,7 @@ public Integer call(String i) { } @GenerateMicroBenchmark - public void flatMapTransforms(UseCaseInput input) throws InterruptedException { + public void flatMapInt(UseCaseInput input) throws InterruptedException { input.observable.flatMap(new Func1<Integer, Observable<Integer>>() { @Override diff --git a/rxjava-core/src/perf/java/rx/usecases/UseCaseInput.java b/rxjava-core/src/perf/java/rx/usecases/UseCaseInput.java index c18bfcc0ed..b3b7958118 100644 --- a/rxjava-core/src/perf/java/rx/usecases/UseCaseInput.java +++ b/rxjava-core/src/perf/java/rx/usecases/UseCaseInput.java @@ -15,6 +15,7 @@ */ package rx.usecases; +import java.util.Iterator; import java.util.concurrent.CountDownLatch; import org.openjdk.jmh.annotations.Param; @@ -36,6 +37,7 @@ public class UseCaseInput { @Param({ "1", "1024" }) public int size; + public Iterable<Integer> iterable; public Observable<Integer> observable; public Observer<Integer> observer; @@ -52,6 +54,34 @@ public void call(Subscriber<? super Integer> o) { o.onCompleted(); } }); + + iterable = new Iterable<Integer>() { + + @Override + public Iterator<Integer> iterator() { + return new Iterator<Integer>() { + + int i=0; + + @Override + public boolean hasNext() { + return i < size; + } + + @Override + public Integer next() { + return i++; + } + + @Override + public void remove() { + + } + + }; + } + + }; latch = new CountDownLatch(1);
4997182d07c7b7efdcd17b8deccf73fd23a3671b
camel
CAMEL-3240 Fixed camel-core build error.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1058911 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java index d6068c338e057..90ea447bfa569 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java @@ -740,7 +740,8 @@ public synchronized boolean stopRoute(String routeId, long timeout, TimeUnit tim stopRouteService(routeService); } return completed; - } + } + return false; } public synchronized void stopRoute(String routeId) throws Exception {
f091f6e436fcef1f083c8f61de8dcdde67b11780
qos-ch$logback
* made AbstrackSocketAppender not lose events when socket connections gets lost (now uses LinkedBlockingDeque) * extracted aspects of deque creation and output stream creation to factories in order to improve testability * ecapsulated automatic flushing of output stream into a separate class in order to make this functionality testable * slightly refactored internal structure of AbstrackSocketAppender to improve maintainability
p
https://github.com/qos-ch/logback
diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/AbstractSocketAppender.java b/logback-core/src/main/java/ch/qos/logback/core/net/AbstractSocketAppender.java index 319fce0854..2940f473f1 100755 --- a/logback-core/src/main/java/ch/qos/logback/core/net/AbstractSocketAppender.java +++ b/logback-core/src/main/java/ch/qos/logback/core/net/AbstractSocketAppender.java @@ -15,25 +15,20 @@ package ch.qos.logback.core.net; import java.io.IOException; -import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.ConnectException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; +import java.util.concurrent.BlockingDeque; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.SynchronousQueue; import java.util.concurrent.TimeUnit; - import javax.net.SocketFactory; import ch.qos.logback.core.AppenderBase; -import ch.qos.logback.core.CoreConstants; import ch.qos.logback.core.spi.PreSerializationTransformer; import ch.qos.logback.core.util.CloseUtil; import ch.qos.logback.core.util.Duration; @@ -45,10 +40,11 @@ * @author Ceki G&uuml;lc&uuml; * @author S&eacute;bastien Pennec * @author Carl Harris + * @author Sebastian Gr&ouml;bler */ public abstract class AbstractSocketAppender<E> extends AppenderBase<E> - implements Runnable, SocketConnector.ExceptionHandler { + implements SocketConnector.ExceptionHandler { /** * The default port number of remote logging server (4560). @@ -61,7 +57,7 @@ public abstract class AbstractSocketAppender<E> extends AppenderBase<E> public static final int DEFAULT_RECONNECTION_DELAY = 30000; /** - * Default size of the queue used to hold logging events that are destined + * Default size of the deque used to hold logging events that are destined * for the remote peer. */ public static final int DEFAULT_QUEUE_SIZE = 128; @@ -78,6 +74,9 @@ public abstract class AbstractSocketAppender<E> extends AppenderBase<E> */ private static final int DEFAULT_EVENT_DELAY_TIMEOUT = 100; + private final ObjectWriterFactory objectWriterFactory; + private final QueueFactory queueFactory; + private String remoteHost; private int port = DEFAULT_PORT; private InetAddress address; @@ -86,7 +85,7 @@ public abstract class AbstractSocketAppender<E> extends AppenderBase<E> private int acceptConnectionTimeout = DEFAULT_ACCEPT_CONNECTION_DELAY; private Duration eventDelayLimit = new Duration(DEFAULT_EVENT_DELAY_TIMEOUT); - private BlockingQueue<E> queue; + private BlockingDeque<E> deque; private String peerId; private Future<?> task; private Future<Socket> connectorTask; @@ -97,8 +96,17 @@ public abstract class AbstractSocketAppender<E> extends AppenderBase<E> * Constructs a new appender. */ protected AbstractSocketAppender() { + this(new QueueFactory(), new ObjectWriterFactory()); } + /** + * Constructs a new appender using the given {@link QueueFactory} and {@link ObjectWriterFactory}. + */ + AbstractSocketAppender(QueueFactory queueFactory, ObjectWriterFactory objectWriterFactory) { + this.objectWriterFactory = objectWriterFactory; + this.queueFactory = queueFactory; + } + /** * {@inheritDoc} */ @@ -119,9 +127,13 @@ public void start() { + " For more information, please visit http://logback.qos.ch/codes.html#socket_no_host"); } + if (queueSize == 0) { + addWarn("Queue size of zero is deprecated, use a size of one to indicate synchronous processing"); + } + if (queueSize < 0) { errorCount++; - addError("Queue size must be non-negative"); + addError("Queue size must be greater than zero"); } if (errorCount == 0) { @@ -134,9 +146,14 @@ public void start() { } if (errorCount == 0) { - queue = newBlockingQueue(queueSize); + deque = queueFactory.newLinkedBlockingDeque(queueSize); peerId = "remote peer " + remoteHost + ":" + port + ": "; - task = getContext().getExecutorService().submit(this); + task = getContext().getExecutorService().submit(new Runnable() { + @Override + public void run() { + connectSocketAndDispatchEvents(); + } + }); super.start(); } } @@ -162,21 +179,16 @@ protected void append(E event) { if (event == null || !isStarted()) return; try { - final boolean inserted = queue.offer(event, eventDelayLimit.getMilliseconds(), TimeUnit.MILLISECONDS); + final boolean inserted = deque.offer(event, eventDelayLimit.getMilliseconds(), TimeUnit.MILLISECONDS); if (!inserted) { - addInfo("Dropping event due to timeout limit of [" + eventDelayLimit + - "] milliseconds being exceeded"); + addInfo("Dropping event due to timeout limit of [" + eventDelayLimit + "] being exceeded"); } } catch (InterruptedException e) { addError("Interrupted while appending event to SocketAppender", e); } } - /** - * {@inheritDoc} - */ - public final void run() { - signalEntryInRunMethod(); + private void connectSocketAndDispatchEvents() { try { while (!Thread.currentThread().isInterrupted()) { SocketConnector connector = createConnector(address, port, 0, @@ -186,22 +198,37 @@ public final void run() { if(connectorTask == null) break; - socket = waitForConnectorToReturnASocket(); + socket = waitForConnectorToReturnSocket(); if(socket == null) break; - dispatchEvents(); + + try { + ObjectWriter objectWriter = createObjectWriterForSocket(); + addInfo(peerId + "connection established"); + dispatchEvents(objectWriter); + } catch (IOException ex) { + addInfo(peerId + "connection failed: " + ex); + } finally { + CloseUtil.closeQuietly(socket); + socket = null; + addInfo(peerId + "connection closed"); + } } } catch (InterruptedException ex) { assert true; // ok... we'll exit now } + // TODO I guess the appender should also be stopped at this point addInfo("shutting down"); } - protected void signalEntryInRunMethod() { - // do nothing by default - } + private ObjectWriter createObjectWriterForSocket() throws IOException { + socket.setSoTimeout(acceptConnectionTimeout); + ObjectWriter objectWriter = objectWriterFactory.newAutoFlushingObjectWriter(socket.getOutputStream()); + socket.setSoTimeout(0); + return objectWriter; + } - private SocketConnector createConnector(InetAddress address, int port, + private SocketConnector createConnector(InetAddress address, int port, int initialDelay, long retryDelay) { SocketConnector connector = newConnector(address, port, initialDelay, retryDelay); @@ -218,9 +245,9 @@ private Future<Socket> activateConnector(SocketConnector connector) { } } - private Socket waitForConnectorToReturnASocket() throws InterruptedException { + private Socket waitForConnectorToReturnSocket() throws InterruptedException { try { - Socket s = connectorTask.get(); + Socket s = connectorTask.get(); connectorTask = null; return s; } catch (ExecutionException e) { @@ -228,35 +255,27 @@ private Socket waitForConnectorToReturnASocket() throws InterruptedException { } } - private void dispatchEvents() throws InterruptedException { - try { - socket.setSoTimeout(acceptConnectionTimeout); - ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); - socket.setSoTimeout(0); - addInfo(peerId + "connection established"); - int counter = 0; - while (true) { - E event = queue.take(); - postProcessEvent(event); - Serializable serEvent = getPST().transform(event); - oos.writeObject(serEvent); - oos.flush(); - if (++counter >= CoreConstants.OOS_RESET_FREQUENCY) { - // Failing to reset the object output stream every now and - // then creates a serious memory leak. - oos.reset(); - counter = 0; - } + private void dispatchEvents(ObjectWriter objectWriter) throws InterruptedException, IOException { + while (true) { + E event = deque.takeFirst(); + postProcessEvent(event); + Serializable serializableEvent = getPST().transform(event); + try { + objectWriter.write(serializableEvent); + } catch (IOException e) { + tryReAddingEventToFrontOfQueue(event); + throw e; } - } catch (IOException ex) { - addInfo(peerId + "connection failed: " + ex); - } finally { - CloseUtil.closeQuietly(socket); - socket = null; - addInfo(peerId + "connection closed"); } - } - + } + + private void tryReAddingEventToFrontOfQueue(E event) { + final boolean wasInserted = deque.offerFirst(event); + if (!wasInserted) { + addInfo("Dropping event due to socket connection error and maxed out deque capacity"); + } + } + /** * {@inheritDoc} */ @@ -270,8 +289,6 @@ public void connectionFailed(SocketConnector connector, Exception ex) { } } - - /** * Creates a new {@link SocketConnector}. * <p> @@ -299,24 +316,6 @@ protected SocketFactory getSocketFactory() { return SocketFactory.getDefault(); } - /** - * Creates a blocking queue that will be used to hold logging events until - * they can be delivered to the remote receiver. - * <p> - * The default implementation creates a (bounded) {@link ArrayBlockingQueue} - * for positive queue sizes. Otherwise it creates a {@link SynchronousQueue}. - * <p> - * This method is exposed primarily to support instrumentation for unit - * testing. - * - * @param queueSize size of the queue - * @return - */ - BlockingQueue<E> newBlockingQueue(int queueSize) { - return queueSize <= 0 ? - new SynchronousQueue<E>() : new ArrayBlockingQueue<E>(queueSize); - } - /** * Post-processes an event before it is serialized for delivery to the * remote receiver. @@ -332,20 +331,6 @@ BlockingQueue<E> newBlockingQueue(int queueSize) { */ protected abstract PreSerializationTransformer<E> getPST(); - /* - * This method is used by logback modules only in the now deprecated - * convenience constructors for SocketAppender - */ - @Deprecated - protected static InetAddress getAddressByName(String host) { - try { - return InetAddress.getByName(host); - } catch (Exception e) { - // addError("Could not find address of [" + host + "].", e); - return null; - } - } - /** * The <b>RemoteHost</b> property takes the name of of the host where a corresponding server is running. */ @@ -397,14 +382,14 @@ public Duration getReconnectionDelay() { /** * The <b>queueSize</b> property takes a non-negative integer representing * the number of logging events to retain for delivery to the remote receiver. - * When the queue size is zero, event delivery to the remote receiver is - * synchronous. When the queue size is greater than zero, the + * When the deque size is zero, event delivery to the remote receiver is + * synchronous. When the deque size is greater than zero, the * {@link #append(Object)} method returns immediately after enqueing the - * event, assuming that there is space available in the queue. Using a - * non-zero queue length can improve performance by eliminating delays + * event, assuming that there is space available in the deque. Using a + * non-zero deque length can improve performance by eliminating delays * caused by transient network delays. * - * @param queueSize the queue size to set. + * @param queueSize the deque size to set. */ public void setQueueSize(int queueSize) { this.queueSize = queueSize; diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/AutoFlushingObjectWriter.java b/logback-core/src/main/java/ch/qos/logback/core/net/AutoFlushingObjectWriter.java new file mode 100644 index 0000000000..6a5c07ca37 --- /dev/null +++ b/logback-core/src/main/java/ch/qos/logback/core/net/AutoFlushingObjectWriter.java @@ -0,0 +1,61 @@ +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * under the terms of the GNU Lesser General Public License version 2.1 + * as published by the Free Software Foundation. + */ + +package ch.qos.logback.core.net; + +import java.io.IOException; +import java.io.ObjectOutputStream; + +/** + * Automatically flushes the underlying {@link java.io.ObjectOutputStream} immediately after calling + * it's {@link java.io.ObjectOutputStream#writeObject(Object)} method. + * + * @author Sebastian Gr&ouml;bler + */ +public class AutoFlushingObjectWriter implements ObjectWriter { + + private final ObjectOutputStream objectOutputStream; + private final int resetFrequency; + private int writeCounter = 0; + + /** + * Creates a new instance for the given {@link java.io.ObjectOutputStream}. + * + * @param objectOutputStream the stream to write to + * @param resetFrequency the frequency with which the given stream will be + * automatically reset to prevent a memory leak + */ + public AutoFlushingObjectWriter(ObjectOutputStream objectOutputStream, int resetFrequency) { + this.objectOutputStream = objectOutputStream; + this.resetFrequency = resetFrequency; + } + + @Override + public void write(Object object) throws IOException { + objectOutputStream.writeObject(object); + objectOutputStream.flush(); + preventMemoryLeak(); + } + + /** + * Failing to reset the object output stream every now and then creates a serious memory leak which + * is why the underlying stream will be reset according to the {@code resetFrequency}. + */ + private void preventMemoryLeak() throws IOException { + if (++writeCounter >= resetFrequency) { + objectOutputStream.reset(); + writeCounter = 0; + } + } +} diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriter.java b/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriter.java new file mode 100644 index 0000000000..dbd528b158 --- /dev/null +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriter.java @@ -0,0 +1,33 @@ +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * under the terms of the GNU Lesser General Public License version 2.1 + * as published by the Free Software Foundation. + */ +package ch.qos.logback.core.net; + +import java.io.IOException; + +/** + * Writes objects to an output. + * + * @author Sebastian Gr&ouml;bler + */ +public interface ObjectWriter { + + /** + * Writes an object to an output. + * + * @param object the {@link Object} to write + * @throws IOException in case input/output fails, details are defined by the implementation + */ + void write(Object object) throws IOException; + +} diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriterFactory.java b/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriterFactory.java new file mode 100644 index 0000000000..eca1405131 --- /dev/null +++ b/logback-core/src/main/java/ch/qos/logback/core/net/ObjectWriterFactory.java @@ -0,0 +1,39 @@ +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * under the terms of the GNU Lesser General Public License version 2.1 + * as published by the Free Software Foundation. + */ +package ch.qos.logback.core.net; + +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.io.OutputStream; + +import ch.qos.logback.core.CoreConstants; + +/** + * Factory for {@link ch.qos.logback.core.net.ObjectWriter} instances. + * + * @author Sebastian Gr&ouml;bler + */ +public class ObjectWriterFactory { + + /** + * Creates a new {@link ch.qos.logback.core.net.AutoFlushingObjectWriter} instance. + * + * @param outputStream the underlying {@link java.io.OutputStream} to write to + * @return a new {@link ch.qos.logback.core.net.AutoFlushingObjectWriter} instance + * @throws IOException if an I/O error occurs while writing stream header + */ + public AutoFlushingObjectWriter newAutoFlushingObjectWriter(OutputStream outputStream) throws IOException { + return new AutoFlushingObjectWriter(new ObjectOutputStream(outputStream), CoreConstants.OOS_RESET_FREQUENCY); + } +} diff --git a/logback-core/src/main/java/ch/qos/logback/core/net/QueueFactory.java b/logback-core/src/main/java/ch/qos/logback/core/net/QueueFactory.java new file mode 100644 index 0000000000..d9f17ff3a3 --- /dev/null +++ b/logback-core/src/main/java/ch/qos/logback/core/net/QueueFactory.java @@ -0,0 +1,39 @@ +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2013, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * under the terms of the GNU Lesser General Public License version 2.1 + * as published by the Free Software Foundation. + */ +package ch.qos.logback.core.net; + +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.LinkedBlockingDeque; + +/** + * Factory for {@link java.util.Queue} instances. + * + * @author Sebastian Gr&ouml;bler + */ +public class QueueFactory { + + /** + * Creates a new {@link LinkedBlockingDeque} with the given {@code capacity}. + * In case the given capacity is smaller than one it will automatically be + * converted to one. + * + * @param capacity the capacity to use for the queue + * @param <E> the type of elements held in the queue + * @return a new instance of {@link ArrayBlockingQueue} + */ + public <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(int capacity) { + final int actualCapacity = capacity < 1 ? 1 : capacity; + return new LinkedBlockingDeque<E>(actualCapacity); + } +} diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderIntegrationTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderIntegrationTest.java new file mode 100755 index 0000000000..7d16ed5a2e --- /dev/null +++ b/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderIntegrationTest.java @@ -0,0 +1,129 @@ +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2011, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * under the terms of the GNU Lesser General Public License version 2.1 + * as published by the Free Software Foundation. + */ + +package ch.qos.logback.core.net; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.OutputStream; +import java.io.Serializable; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import ch.qos.logback.core.net.mock.MockContext; +import ch.qos.logback.core.net.server.ServerSocketUtil; +import ch.qos.logback.core.spi.PreSerializationTransformer; +import org.junit.After; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import org.junit.Before; +import org.junit.Test; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Integration tests for {@link ch.qos.logback.core.net.AbstractSocketAppender}. + * + * @author Carl Harris + * @author Sebastian Gr&ouml;bler + */ +public class AbstractSocketAppenderIntegrationTest { + + private static final int TIMEOUT = 2000; + + private ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newCachedThreadPool(); + private MockContext mockContext = new MockContext(executorService); + private AutoFlushingObjectWriter objectWriter; + private ObjectWriterFactory objectWriterFactory = new SpyProducingObjectWriterFactory(); + private LinkedBlockingDeque<String> deque = spy(new LinkedBlockingDeque<String>(1)); + private QueueFactory queueFactory = mock(QueueFactory.class); + private InstrumentedSocketAppender instrumentedAppender = new InstrumentedSocketAppender(queueFactory, objectWriterFactory); + + @Before + public void setUp() throws Exception { + when(queueFactory.<String>newLinkedBlockingDeque(anyInt())).thenReturn(deque); + instrumentedAppender.setContext(mockContext); + } + + @After + public void tearDown() throws Exception { + instrumentedAppender.stop(); + assertFalse(instrumentedAppender.isStarted()); + executorService.shutdownNow(); + assertTrue(executorService.awaitTermination(TIMEOUT, TimeUnit.MILLISECONDS)); + } + + @Test + public void dispatchesEvents() throws Exception { + + // given + ServerSocket serverSocket = ServerSocketUtil.createServerSocket(); + instrumentedAppender.setRemoteHost(serverSocket.getInetAddress().getHostAddress()); + instrumentedAppender.setPort(serverSocket.getLocalPort()); + instrumentedAppender.start(); + + Socket appenderSocket = serverSocket.accept(); + serverSocket.close(); + + // when + instrumentedAppender.append("some event"); + + // wait for event to be taken from deque and being written into the stream + verify(deque, timeout(TIMEOUT)).takeFirst(); + verify(objectWriter, timeout(TIMEOUT)).write("some event"); + + // then + ObjectInputStream ois = new ObjectInputStream(appenderSocket.getInputStream()); + assertEquals("some event", ois.readObject()); + appenderSocket.close(); + } + + private static class InstrumentedSocketAppender extends AbstractSocketAppender<String> { + + public InstrumentedSocketAppender(QueueFactory queueFactory, ObjectWriterFactory objectWriterFactory) { + super(queueFactory, objectWriterFactory); + } + + @Override + protected void postProcessEvent(String event) { + } + + @Override + protected PreSerializationTransformer<String> getPST() { + return new PreSerializationTransformer<String>() { + public Serializable transform(String event) { + return event; + } + }; + } + } + + private class SpyProducingObjectWriterFactory extends ObjectWriterFactory { + + @Override + public AutoFlushingObjectWriter newAutoFlushingObjectWriter(OutputStream outputStream) throws IOException { + objectWriter = spy(super.newAutoFlushingObjectWriter(outputStream)); + return objectWriter; + } + } +} diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderTest.java index 8efd80c5c2..371981afa0 100755 --- a/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderTest.java +++ b/logback-core/src/test/java/ch/qos/logback/core/net/AbstractSocketAppenderTest.java @@ -14,242 +14,467 @@ package ch.qos.logback.core.net; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.ObjectInputStream; +import java.io.IOException; +import java.io.OutputStream; import java.io.Serializable; -import java.net.ServerSocket; +import java.net.InetAddress; import java.net.Socket; -import java.util.List; -import java.util.concurrent.*; - -import ch.qos.logback.core.BasicStatusManager; -import ch.qos.logback.core.status.Status; -import ch.qos.logback.core.status.StatusListener; -import ch.qos.logback.core.status.StatusManager; -import ch.qos.logback.core.util.StatusPrinter; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; import ch.qos.logback.core.net.mock.MockContext; -import ch.qos.logback.core.net.server.ServerSocketUtil; import ch.qos.logback.core.spi.PreSerializationTransformer; +import ch.qos.logback.core.util.Duration; +import org.junit.After; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InOrder; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Matchers.anyLong; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.contains; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; /** * Unit tests for {@link AbstractSocketAppender}. * * @author Carl Harris + * @author Sebastian Gr&ouml;bler */ public class AbstractSocketAppenderTest { - private static final int DELAY = 10000; + /** + * Timeout used for all blocking operations in multi-threading contexts. + */ + private static final int TIMEOUT = 1000; - private ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newCachedThreadPool(); + private ThreadPoolExecutor executorService = spy((ThreadPoolExecutor) Executors.newCachedThreadPool()); private MockContext mockContext = new MockContext(executorService); - private InstrumentedSocketAppender instrumentedAppender = new InstrumentedSocketAppender(); + private PreSerializationTransformer<String> preSerializationTransformer = spy(new StringPreSerializationTransformer()); + private Socket socket = mock(Socket.class); + private SocketConnector socketConnector = mock(SocketConnector.class); + private AutoFlushingObjectWriter objectWriter = mock(AutoFlushingObjectWriter.class); + private ObjectWriterFactory objectWriterFactory = mock(ObjectWriterFactory.class); + private LinkedBlockingDeque<String> deque = spy(new LinkedBlockingDeque<String>(1)); + private QueueFactory queueFactory = mock(QueueFactory.class); + private InstrumentedSocketAppender appender = spy(new InstrumentedSocketAppender(preSerializationTransformer, queueFactory, objectWriterFactory, socketConnector)); @Before public void setUp() throws Exception { - instrumentedAppender.setContext(mockContext); + // setup valid appender with mock dependencies + when(socketConnector.call()).thenReturn(socket); + when(objectWriterFactory.newAutoFlushingObjectWriter(any(OutputStream.class))).thenReturn(objectWriter); + when(queueFactory.<String>newLinkedBlockingDeque(anyInt())).thenReturn(deque); + + appender.setContext(mockContext); + appender.setRemoteHost("localhost"); } @After public void tearDown() throws Exception { - instrumentedAppender.stop(); - assertFalse(instrumentedAppender.isStarted()); + appender.stop(); + assertFalse(appender.isStarted()); executorService.shutdownNow(); - assertTrue(executorService.awaitTermination(DELAY, TimeUnit.MILLISECONDS)); + assertTrue(executorService.awaitTermination(TIMEOUT, TimeUnit.MILLISECONDS)); } @Test - public void appenderShouldFailToStartWithoutValidPort() throws Exception { - instrumentedAppender.setPort(-1); - instrumentedAppender.setRemoteHost("localhost"); - instrumentedAppender.setQueueSize(0); - instrumentedAppender.start(); - assertFalse(instrumentedAppender.isStarted()); - assertTrue(mockContext.getLastStatus().getMessage().contains("port")); + public void failsToStartWithoutValidPort() throws Exception { + + // given + appender.setPort(-1); + + // when + appender.start(); + + // then + assertFalse(appender.isStarted()); + verify(appender).addError(contains("port")); } @Test - public void appenderShouldFailToStartWithoutValidRemoteHost() throws Exception { - instrumentedAppender.setPort(1); - instrumentedAppender.setRemoteHost(null); - instrumentedAppender.setQueueSize(0); - instrumentedAppender.start(); - assertFalse(instrumentedAppender.isStarted()); - assertTrue(mockContext.getLastStatus().getMessage().contains("remote host")); + public void failsToStartWithoutValidRemoteHost() throws Exception { + + // given + appender.setRemoteHost(null); + + // when + appender.start(); + + // then + assertFalse(appender.isStarted()); + verify(appender).addError(contains("remote host")); } @Test - public void appenderShouldFailToStartWithNegativeQueueSize() throws Exception { - instrumentedAppender.setPort(1); - instrumentedAppender.setRemoteHost("localhost"); - instrumentedAppender.setQueueSize(-1); - instrumentedAppender.start(); - assertFalse(instrumentedAppender.isStarted()); - assertTrue(mockContext.getLastStatus().getMessage().contains("Queue")); + public void failsToStartWithNegativeQueueSize() throws Exception { + + // given + appender.setQueueSize(-1); + + // when + appender.start(); + + // then + assertFalse(appender.isStarted()); + verify(appender).addError(contains("Queue size must be greater than zero")); } @Test - public void appenderShouldFailToStartWithUnresolvableRemoteHost() throws Exception { - instrumentedAppender.setPort(1); - instrumentedAppender.setRemoteHost("NOT.A.VALID.REMOTE.HOST.NAME"); - instrumentedAppender.setQueueSize(0); - instrumentedAppender.start(); - assertFalse(instrumentedAppender.isStarted()); - assertTrue(mockContext.getLastStatus().getMessage().contains("unknown host")); + public void failsToStartWithUnresolvableRemoteHost() throws Exception { + + // given + appender.setRemoteHost("NOT.A.VALID.REMOTE.HOST.NAME"); + + // when + appender.start(); + + // then + assertFalse(appender.isStarted()); + verify(appender).addError(contains("unknown host")); } @Test - public void appenderShouldFailToStartWithZeroQueueLength() throws Exception { - instrumentedAppender.setPort(1); - instrumentedAppender.setRemoteHost("localhost"); - instrumentedAppender.setQueueSize(0); - instrumentedAppender.start(); - assertTrue(instrumentedAppender.isStarted()); - assertTrue(instrumentedAppender.lastQueue instanceof SynchronousQueue); + public void startsButOutputsWarningWhenQueueSizeIsZero() throws Exception { + + // given + appender.setQueueSize(0); + + // when + appender.start(); + + // then + assertTrue(appender.isStarted()); + verify(appender).addWarn("Queue size of zero is deprecated, use a size of one to indicate synchronous processing"); } @Test - public void appenderShouldStartWithValidParameters() throws Exception { - instrumentedAppender.setPort(1); - instrumentedAppender.setRemoteHost("localhost"); - instrumentedAppender.setQueueSize(1); - instrumentedAppender.start(); - assertTrue(instrumentedAppender.isStarted()); - assertTrue(instrumentedAppender.lastQueue instanceof ArrayBlockingQueue); - assertEquals(1, instrumentedAppender.lastQueue.remainingCapacity()); + public void startsWithValidParameters() throws Exception { + + // when + appender.start(); + + // then + assertTrue(appender.isStarted()); } - // this test takes 1 second and is deemed too long - @Ignore - @Test(timeout = 2000) - public void appenderShouldCleanupTasksWhenStopped() throws Exception { - mockContext.setStatusManager(new BasicStatusManager()); - instrumentedAppender.setPort(1); - instrumentedAppender.setRemoteHost("localhost"); - instrumentedAppender.setQueueSize(1); - instrumentedAppender.start(); - assertTrue(instrumentedAppender.isStarted()); + @Test + public void createsSocketConnectorWithConfiguredParameters() throws Exception { + + // given + appender.setReconnectionDelay(new Duration(42)); + appender.setRemoteHost("localhost"); + appender.setPort(21); - waitForActiveCountToEqual(executorService, 2); - instrumentedAppender.stop(); - waitForActiveCountToEqual(executorService, 0); - StatusPrinter.print(mockContext); - assertEquals(0, executorService.getActiveCount()); + // when + appender.start(); + // then + verify(appender, timeout(TIMEOUT)).newConnector(InetAddress.getByName("localhost"), 21, 0, 42); } - private void waitForActiveCountToEqual(ThreadPoolExecutor executorService, int i) { - while (executorService.getActiveCount() != i) { - try { - Thread.yield(); - Thread.sleep(1); - System.out.print("."); - } catch (InterruptedException e) { - } - } + @Test + public void addsInfoMessageWhenSocketConnectionWasEstablished() { + + // when + appender.start(); + + // then + verify(appender, timeout(TIMEOUT)).addInfo(contains("connection established")); } + @Test + public void addsInfoMessageWhenSocketConnectionFailed() throws Exception { + + // given + doThrow(new IOException()).when(objectWriterFactory).newAutoFlushingObjectWriter(any(OutputStream.class)); + appender.start(); + + // when + appender.append("some event"); + + // then + verify(appender, timeout(TIMEOUT).atLeastOnce()).addInfo(contains("connection failed")); + } @Test - public void testAppendWhenNotStarted() throws Exception { - instrumentedAppender.setRemoteHost("localhost"); - instrumentedAppender.start(); - instrumentedAppender.stop(); + public void closesSocketOnException() throws Exception { - // make sure the appender task has stopped - executorService.shutdownNow(); - assertTrue(executorService.awaitTermination(DELAY, TimeUnit.MILLISECONDS)); + // given + doThrow(new IOException()).when(objectWriterFactory).newAutoFlushingObjectWriter(any(OutputStream.class)); + appender.start(); - instrumentedAppender.append("some event"); - assertTrue(instrumentedAppender.lastQueue.isEmpty()); + // when + appender.append("some event"); + + // then + verify(socket, timeout(TIMEOUT).atLeastOnce()).close(); } - @Test(timeout = 1000) - public void testAppendSingleEvent() throws Exception { - instrumentedAppender.setRemoteHost("localhost"); - instrumentedAppender.start(); + @Test + public void addsInfoMessageWhenSocketConnectionClosed() throws Exception { - instrumentedAppender.latch.await(); - instrumentedAppender.append("some event"); - assertTrue(instrumentedAppender.lastQueue.size() == 1); + // given + doThrow(new IOException()).when(objectWriterFactory).newAutoFlushingObjectWriter(any(OutputStream.class)); + appender.start(); + + // when + appender.append("some event"); + + // then + verify(appender, timeout(TIMEOUT).atLeastOnce()).addInfo(contains("connection closed")); } @Test - public void testAppendEvent() throws Exception { - instrumentedAppender.setRemoteHost("localhost"); - instrumentedAppender.setQueueSize(1); - instrumentedAppender.start(); + public void shutsDownWhenConnectorTaskCouldNotBeActivated() { - // stop the appender task, but don't stop the appender - executorService.shutdownNow(); - assertTrue(executorService.awaitTermination(DELAY, TimeUnit.MILLISECONDS)); + // given + doThrow(new RejectedExecutionException()).when(executorService).submit(socketConnector); - instrumentedAppender.append("some event"); - assertEquals("some event", instrumentedAppender.lastQueue.poll()); + // when + appender.start(); + + // then + verify(appender, timeout(TIMEOUT)).addInfo("shutting down"); } @Test - public void testDispatchEvent() throws Exception { - ServerSocket serverSocket = ServerSocketUtil.createServerSocket(); - instrumentedAppender.setRemoteHost(serverSocket.getInetAddress().getHostAddress()); - instrumentedAppender.setPort(serverSocket.getLocalPort()); - instrumentedAppender.setQueueSize(1); - instrumentedAppender.start(); + public void shutsDownWhenConnectorTaskThrewAnException() throws Exception { - Socket appenderSocket = serverSocket.accept(); - serverSocket.close(); + // given + doThrow(new IllegalStateException()).when(socketConnector).call(); - instrumentedAppender.append("some event"); + // when + appender.start(); - final int shortDelay = 100; - for (int i = 0, retries = DELAY / shortDelay; - !instrumentedAppender.lastQueue.isEmpty() && i < retries; - i++) { - Thread.sleep(shortDelay); - } - assertTrue(instrumentedAppender.lastQueue.isEmpty()); + // then + verify(appender, timeout(TIMEOUT)).addInfo("shutting down"); + } + + @Test + public void offersEventsToTheEndOfTheDeque() throws Exception { + + // given + appender.start(); + + // when + appender.append("some event"); + + // then + verify(deque).offer(eq("some event"), anyLong(), any(TimeUnit.class)); + } + + @Test + public void doesNotQueueAnyEventsWhenStopped() throws Exception { + + // given + appender.start(); + appender.stop(); + + // when + appender.append("some event"); + + // then + verifyZeroInteractions(deque); + } - ObjectInputStream ois = new ObjectInputStream(appenderSocket.getInputStream()); - assertEquals("some event", ois.readObject()); - appenderSocket.close(); + @Test + public void addsInfoMessageWhenEventCouldNotBeQueuedInConfiguredTimeoutDueToQueueSizeLimitation() throws Exception { + + // given + long eventDelayLimit = 42; + doReturn(false).when(deque).offer("some event", eventDelayLimit, TimeUnit.MILLISECONDS); + appender.setEventDelayLimit(new Duration(eventDelayLimit)); + appender.start(); + + // when + appender.append("some event"); + + // then + verify(appender).addInfo("Dropping event due to timeout limit of [" + eventDelayLimit + " milliseconds] being exceeded"); + } + + @Test + public void takesEventsFromTheFrontOfTheDeque() throws Exception { + + // given + appender.start(); + awaitStartOfEventDispatching(); + // when + appender.append("some event"); + + // then + verify(deque, timeout(TIMEOUT).atLeastOnce()).takeFirst(); + } + + @Test + public void reAddsEventAtTheFrontOfTheDequeWhenTransmissionFails() throws Exception { + + // given + doThrow(new IOException()).when(objectWriter).write(anyObject()); + appender.start(); + awaitStartOfEventDispatching(); + + // when + appender.append("some event"); + + // then + verify(deque, timeout(TIMEOUT).atLeastOnce()).offerFirst("some event"); + } + + @Test + public void addsErrorMessageWhenAppendingIsInterruptedWhileWaitingForTheQueueToAcceptTheEvent() throws Exception { + + // given + final InterruptedException interruptedException = new InterruptedException(); + doThrow(interruptedException).when(deque).offer(eq("some event"), anyLong(), any(TimeUnit.class)); + appender.start(); + + // when + appender.append("some event"); + + // then + verify(appender).addError("Interrupted while appending event to SocketAppender", interruptedException); + } + + @Test + public void postProcessesEventsBeforeTransformingItToASerializable() throws Exception { + + // given + appender.start(); + awaitStartOfEventDispatching(); + + // when + appender.append("some event"); + awaitAtLeastOneEventToBeDispatched(); + + // then + InOrder inOrder = inOrder(appender, preSerializationTransformer); + inOrder.verify(appender).postProcessEvent("some event"); + inOrder.verify(preSerializationTransformer).transform("some event"); + } + + @Test + public void writesSerializedEventToStream() throws Exception { + + // given + when(preSerializationTransformer.transform("some event")).thenReturn("some serialized event"); + appender.start(); + awaitStartOfEventDispatching(); + + // when + appender.append("some event"); + + // then + verify(objectWriter, timeout(TIMEOUT)).write("some serialized event"); + } + + @Test + public void addsInfoMessageWhenEventIsBeingDroppedBecauseOfConnectionProblemAndDequeCapacityLimitReached() throws Exception { + + // given + doThrow(new IOException()).when(objectWriter).write(anyObject()); + doThrow(new IllegalStateException()).when(deque).offerFirst("some event"); + appender.start(); + awaitStartOfEventDispatching(); + reset(appender); + + // when + appender.append("some event"); + + // then + verify(appender, timeout(TIMEOUT)).addInfo("Dropping event due to socket connection error and maxed out deque capacity"); + } + + @Test + public void reEstablishesSocketConnectionOnConnectionDrop() throws Exception { + + // given + doThrow(new IOException()).when(objectWriter).write(anyObject()); + appender.start(); + awaitStartOfEventDispatching(); + + // when + appender.append("some event"); + + // then + verify(objectWriterFactory, timeout(TIMEOUT).atLeast(2)).newAutoFlushingObjectWriter(any(OutputStream.class)); + } + + @Test + public void usesConfiguredAcceptConnectionTimeoutAndResetsSocketTimeoutAfterSuccessfulConnection() throws Exception { + + // when + appender.setAcceptConnectionTimeout(42); + appender.start(); + awaitStartOfEventDispatching(); + + // then + InOrder inOrder = inOrder(socket); + inOrder.verify(socket).setSoTimeout(42); + inOrder.verify(socket).setSoTimeout(0); + } + + private void awaitAtLeastOneEventToBeDispatched() throws IOException { + verify(objectWriter, timeout(TIMEOUT)).write(anyString()); + } + + private void awaitStartOfEventDispatching() throws InterruptedException { + verify(deque, timeout(TIMEOUT)).takeFirst(); } private static class InstrumentedSocketAppender extends AbstractSocketAppender<String> { - private BlockingQueue<String> lastQueue; - CountDownLatch latch = new CountDownLatch(1); + private PreSerializationTransformer<String> preSerializationTransformer; + private SocketConnector socketConnector; + + public InstrumentedSocketAppender(PreSerializationTransformer<String> preSerializationTransformer, + QueueFactory queueFactory, + ObjectWriterFactory objectWriterFactory, + SocketConnector socketConnector) { + super(queueFactory, objectWriterFactory); + this.preSerializationTransformer = preSerializationTransformer; + this.socketConnector = socketConnector; + } + @Override protected void postProcessEvent(String event) { } @Override protected PreSerializationTransformer<String> getPST() { - return new PreSerializationTransformer<String>() { - public Serializable transform(String event) { - return event; - } - }; + return preSerializationTransformer; } @Override - protected void signalEntryInRunMethod() { - latch.countDown(); + protected SocketConnector newConnector(InetAddress address, int port, long initialDelay, long retryDelay) { + return socketConnector; } + } + + private static class StringPreSerializationTransformer implements PreSerializationTransformer<String> { @Override - BlockingQueue<String> newBlockingQueue(int queueSize) { - lastQueue = super.newBlockingQueue(queueSize); - return lastQueue; + public Serializable transform(String event) { + return event; } - } - } diff --git a/logback-core/src/test/java/ch/qos/logback/core/net/AutoFlushingObjectWriterTest.java b/logback-core/src/test/java/ch/qos/logback/core/net/AutoFlushingObjectWriterTest.java new file mode 100644 index 0000000000..1a4672703a --- /dev/null +++ b/logback-core/src/test/java/ch/qos/logback/core/net/AutoFlushingObjectWriterTest.java @@ -0,0 +1,114 @@ +/** + * Logback: the reliable, generic, fast and flexible logging framework. + * Copyright (C) 1999-2011, QOS.ch. All rights reserved. + * + * This program and the accompanying materials are dual-licensed under + * either the terms of the Eclipse Public License v1.0 as published by + * the Eclipse Foundation + * + * or (per the licensee's choosing) + * + * under the terms of the GNU Lesser General Public License version 2.1 + * as published by the Free Software Foundation. + */ + +package ch.qos.logback.core.net; + +import java.io.IOException; +import java.io.ObjectOutputStream; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InOrder; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +/** + * Unit tests for {@link ch.qos.logback.core.net.AutoFlushingObjectWriter}. + * + * @author Sebastian Gr&ouml;bler + */ +public class AutoFlushingObjectWriterTest { + + private InstrumentedObjectOutputStream objectOutputStream; + + @Before + public void beforeEachTest() throws IOException { + objectOutputStream = spy(new InstrumentedObjectOutputStream()); + } + + @Test + public void writesToUnderlyingObjectOutputStream() throws IOException { + + // given + ObjectWriter objectWriter = new AutoFlushingObjectWriter(objectOutputStream, 2); + String object = "foo"; + + // when + objectWriter.write(object); + + // then + verify(objectOutputStream).writeObjectOverride(object); + } + + @Test + public void flushesAfterWrite() throws IOException { + + // given + ObjectWriter objectWriter = new AutoFlushingObjectWriter(objectOutputStream, 2); + String object = "foo"; + + // when + objectWriter.write(object); + + // then + InOrder inOrder = inOrder(objectOutputStream); + inOrder.verify(objectOutputStream).writeObjectOverride(object); + inOrder.verify(objectOutputStream).flush(); + } + + @Test + public void resetsObjectOutputStreamAccordingToGivenResetFrequency() throws IOException { + + // given + ObjectWriter objectWriter = new AutoFlushingObjectWriter(objectOutputStream, 2); + String object = "foo"; + + // when + objectWriter.write(object); + objectWriter.write(object); + objectWriter.write(object); + objectWriter.write(object); + + // then + InOrder inOrder = inOrder(objectOutputStream); + inOrder.verify(objectOutputStream).writeObjectOverride(object); + inOrder.verify(objectOutputStream).writeObjectOverride(object); + inOrder.verify(objectOutputStream).reset(); + inOrder.verify(objectOutputStream).writeObjectOverride(object); + inOrder.verify(objectOutputStream).writeObjectOverride(object); + inOrder.verify(objectOutputStream).reset(); + } + + private static class InstrumentedObjectOutputStream extends ObjectOutputStream { + + protected InstrumentedObjectOutputStream() throws IOException, SecurityException { + } + + @Override + protected void writeObjectOverride(final Object obj) throws IOException { + // nop + } + + @Override + public void flush() throws IOException { + // nop + } + + @Override + public void reset() throws IOException { + // nop + } + } +}
382bd64cdd015fd035182785291db8122791695e
camel
CAMEL-1369: Removed @MessageDriven as its- replaced with @Consume.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@749562 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/MessageDriven.java b/camel-core/src/main/java/org/apache/camel/MessageDriven.java deleted file mode 100644 index 270d03a9d9d34..0000000000000 --- a/camel-core/src/main/java/org/apache/camel/MessageDriven.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.camel; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Used to indicate a method on a POJO which is used as a {@link Consumer} of - * {@link Exchange} instances to process {@link Message} instances. - * - * Either a <a href="http://camel.apache.org/uris.html">URI</a> for an - * endpoint should be configured, or a name of an endpoint which refers to a - * Spring bean name in your Spring ApplicationContext. - * - * @version $Revision$ - */ -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Target({ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR }) -public @interface MessageDriven { - String uri() default ""; - - String name() default ""; -} diff --git a/camel-core/src/main/java/org/apache/camel/impl/CamelPostProcessorHelper.java b/camel-core/src/main/java/org/apache/camel/impl/CamelPostProcessorHelper.java index 28e21a383a575..aa18b9cc14db3 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/CamelPostProcessorHelper.java +++ b/camel-core/src/main/java/org/apache/camel/impl/CamelPostProcessorHelper.java @@ -25,7 +25,6 @@ import org.apache.camel.Consume; import org.apache.camel.Consumer; import org.apache.camel.Endpoint; -import org.apache.camel.MessageDriven; import org.apache.camel.PollingConsumer; import org.apache.camel.Processor; import org.apache.camel.Producer; @@ -67,12 +66,6 @@ public void setCamelContext(CamelContext camelContext) { } public void consumerInjection(Method method, Object bean) { - MessageDriven annotation = method.getAnnotation(MessageDriven.class); - if (annotation != null) { - LOG.info("Creating a consumer for: " + annotation); - subscribeMethod(method, bean, annotation.uri(), annotation.name()); - } - Consume consume = method.getAnnotation(Consume.class); if (consume != null) { LOG.info("Creating a consumer for: " + consume); @@ -87,8 +80,10 @@ public void subscribeMethod(Method method, Object bean, String endpointUri, Stri if (endpoint != null) { try { Processor processor = createConsumerProcessor(bean, method, endpoint); - LOG.info("Created processor: " + processor); Consumer consumer = endpoint.createConsumer(processor); + if (LOG.isDebugEnabled()) { + LOG.debug("Created processor: " + processor + " for consumer: " + consumer); + } startService(consumer); } catch (Exception e) { throw ObjectHelper.wrapRuntimeCamelException(e); @@ -145,7 +140,8 @@ public Object getInjectionValue(Class<?> type, String endpointUri, String endpoi throw createProxyInstantiationRuntimeException(type, endpoint, e); } } else { - throw new IllegalArgumentException("Invalid type: " + type.getName() + " which cannot be injected via @EndpointInject for " + endpoint); + throw new IllegalArgumentException("Invalid type: " + type.getName() + + " which cannot be injected via @EndpointInject/@Produce for: " + endpoint); } } return null; @@ -157,8 +153,7 @@ protected RuntimeException createProxyInstantiationRuntimeException(Class<?> typ } /** - * Factory method to create a started {@link org.apache.camel.PollingConsumer} to be injected - * into a POJO + * Factory method to create a started {@link org.apache.camel.PollingConsumer} to be injected into a POJO */ protected PollingConsumer createInjectionPollingConsumer(Endpoint endpoint) { try { @@ -171,8 +166,7 @@ protected PollingConsumer createInjectionPollingConsumer(Endpoint endpoint) { } /** - * A Factory method to create a started {@link org.apache.camel.Producer} to be injected into - * a POJO + * A Factory method to create a started {@link org.apache.camel.Producer} to be injected into a POJO */ protected Producer createInjectionProducer(Endpoint endpoint) { try { diff --git a/components/camel-guice/src/main/java/org/apache/camel/guice/CamelModule.java b/components/camel-guice/src/main/java/org/apache/camel/guice/CamelModule.java index 193a40126e18c..63ffa9dc058e7 100644 --- a/components/camel-guice/src/main/java/org/apache/camel/guice/CamelModule.java +++ b/components/camel-guice/src/main/java/org/apache/camel/guice/CamelModule.java @@ -20,7 +20,6 @@ import com.google.inject.matcher.Matchers; import org.apache.camel.CamelContext; import org.apache.camel.Consume; -import org.apache.camel.MessageDriven; import org.apache.camel.Routes; import org.apache.camel.guice.impl.ConsumerInjection; import org.apache.camel.guice.impl.EndpointInjector; @@ -58,8 +57,6 @@ protected void configure() { ConsumerInjection consumerInjection = new ConsumerInjection(); requestInjection(consumerInjection); - - bindConstructorInterceptor(Matchers.methodAnnotatedWith(MessageDriven.class), consumerInjection); bindConstructorInterceptor(Matchers.methodAnnotatedWith(Consume.class), consumerInjection); } diff --git a/components/camel-jms/src/test/java/org/apache/camel/component/jms/bind/MyBean.java b/components/camel-jms/src/test/java/org/apache/camel/component/jms/bind/MyBean.java index 4fb9058c4784b..4008039b44618 100644 --- a/components/camel-jms/src/test/java/org/apache/camel/component/jms/bind/MyBean.java +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/bind/MyBean.java @@ -18,9 +18,9 @@ import java.util.Map; +import org.apache.camel.Consume; import org.apache.camel.EndpointInject; import org.apache.camel.Headers; -import org.apache.camel.MessageDriven; import org.apache.camel.ProducerTemplate; /** @@ -32,7 +32,7 @@ public class MyBean { @EndpointInject(uri = "mock:result") private ProducerTemplate producer; - @MessageDriven(uri = "activemq:Test.BindingQueue") + @Consume(uri = "activemq:Test.BindingQueue") public void myMethod(@Headers Map headers, String body) { this.headers = headers; this.body = body; diff --git a/components/camel-spring/src/main/java/org/apache/camel/spring/CamelBeanPostProcessor.java b/components/camel-spring/src/main/java/org/apache/camel/spring/CamelBeanPostProcessor.java index 241e261139578..59f421a419efa 100644 --- a/components/camel-spring/src/main/java/org/apache/camel/spring/CamelBeanPostProcessor.java +++ b/components/camel-spring/src/main/java/org/apache/camel/spring/CamelBeanPostProcessor.java @@ -43,11 +43,11 @@ /** * A bean post processor which implements the <a href="http://camel.apache.org/bean-integration.html">Bean Integration</a> - * features in Camel such as the <a href="http://camel.apache.org/bean-injection.html">Bean Injection</a> of objects like + * features in Camel. Features such as the <a href="http://camel.apache.org/bean-injection.html">Bean Injection</a> of objects like * {@link Endpoint} and * {@link org.apache.camel.ProducerTemplate} together with support for * <a href="http://camel.apache.org/pojo-consuming.html">POJO Consuming</a> via the - * {@link org.apache.camel.Consume} and {@link org.apache.camel.MessageDriven} annotations along with + * {@link org.apache.camel.Consume} annotation along with * <a href="http://camel.apache.org/pojo-producing.html">POJO Producing</a> via the * {@link org.apache.camel.Produce} annotation along with other annotations such as * {@link org.apache.camel.RecipientList} for creating <a href="http://camel.apache.org/recipientlist-annotation.html">a Recipient List router via annotations</a>. @@ -177,32 +177,6 @@ protected void setterInjection(Method method, Object bean, String endpointUri, S } } - - protected void consumerInjection(final Object bean) { - org.springframework.util.ReflectionUtils.doWithMethods(bean.getClass(), new org.springframework.util.ReflectionUtils.MethodCallback() { - @SuppressWarnings("unchecked") - public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { - /* - * TODO support callbacks? if - * (method.getAnnotation(Callback.class) != null) { try { - * Expression e = ExpressionFactory.createExpression( - * method.getAnnotation(Callback.class).condition()); - * JexlContext jc = JexlHelper.createContext(); - * jc.getVars().put("this", obj); Object r = e.evaluate(jc); if - * (!(r instanceof Boolean)) { throw new - * RuntimeException("Expression did not returned a boolean value - * but: " + r); } Boolean oldVal = - * req.getCallbacks().get(method); Boolean newVal = (Boolean) r; - * if ((oldVal == null || !oldVal) && newVal) { - * req.getCallbacks().put(method, newVal); method.invoke(obj, - * new Object[0]); // TODO: handle return value and sent it as - * the answer } } catch (Exception e) { throw new - * RuntimeException("Unable to invoke callback", e); } } - */ - } - }); - } - public CamelPostProcessorHelper getPostProcessor() { ObjectHelper.notNull(postProcessor, "postProcessor"); return postProcessor; diff --git a/components/camel-spring/src/test/java/org/apache/camel/component/bean/MyBeanBindingConsumer.java b/components/camel-spring/src/test/java/org/apache/camel/component/bean/MyBeanBindingConsumer.java index e9739e5e66061..a93911f7ffe98 100644 --- a/components/camel-spring/src/test/java/org/apache/camel/component/bean/MyBeanBindingConsumer.java +++ b/components/camel-spring/src/test/java/org/apache/camel/component/bean/MyBeanBindingConsumer.java @@ -16,8 +16,8 @@ */ package org.apache.camel.component.bean; +import org.apache.camel.Consume; import org.apache.camel.Header; -import org.apache.camel.MessageDriven; import org.apache.camel.ProducerTemplate; import org.apache.camel.language.Bean; import org.apache.camel.language.Constant; @@ -29,22 +29,22 @@ public class MyBeanBindingConsumer { private ProducerTemplate template; - @MessageDriven(uri = "direct:startBeanExpression") + @Consume(uri = "direct:startBeanExpression") public void doSomethingBeanExpression(String payload, @Bean("myCounter") int count) { template.sendBodyAndHeader("mock:result", "Bye " + payload, "count", count); } - @MessageDriven(uri = "direct:startConstantExpression") + @Consume(uri = "direct:startConstantExpression") public void doSomethingConstantExpression(String payload, @Constant("5") int count) { template.sendBodyAndHeader("mock:result", "Bye " + payload, "count", count); } - @MessageDriven(uri = "direct:startHeaderExpression") + @Consume(uri = "direct:startHeaderExpression") public void doSomethingHeaderExpression(String payload, @Header("number") int count) { template.sendBodyAndHeader("mock:result", "Bye " + payload, "count", count); } - @MessageDriven(uri = "direct:startMany") + @Consume(uri = "direct:startMany") public void doSomethingManyExpression(String payload, @Constant("5") int count, @Header("number") int number) { template.sendBodyAndHeader("mock:result", "Bye " + payload, "count", count * number); } diff --git a/components/camel-spring/src/test/java/org/apache/camel/component/bean/RouterBean.java b/components/camel-spring/src/test/java/org/apache/camel/component/bean/RouterBean.java index 0272105a6c13e..1f41b930206c8 100644 --- a/components/camel-spring/src/test/java/org/apache/camel/component/bean/RouterBean.java +++ b/components/camel-spring/src/test/java/org/apache/camel/component/bean/RouterBean.java @@ -16,7 +16,7 @@ */ package org.apache.camel.component.bean; -import org.apache.camel.MessageDriven; +import org.apache.camel.Consume; import org.apache.camel.RecipientList; /** @@ -27,7 +27,7 @@ */ public class RouterBean { - @MessageDriven(uri = "direct:start") + @Consume(uri = "direct:start") @RecipientList public String[] route(String body) { System.out.println("RouteBean called with body: " + body); diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/example/MyConsumer.java b/components/camel-spring/src/test/java/org/apache/camel/spring/example/MyConsumer.java index b6e101a92d8bf..103043609a220 100644 --- a/components/camel-spring/src/test/java/org/apache/camel/spring/example/MyConsumer.java +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/example/MyConsumer.java @@ -16,8 +16,8 @@ */ package org.apache.camel.spring.example; +import org.apache.camel.Consume; import org.apache.camel.EndpointInject; -import org.apache.camel.MessageDriven; import org.apache.camel.ProducerTemplate; import org.apache.camel.util.ObjectHelper; import org.apache.commons.logging.Log; @@ -33,7 +33,7 @@ public class MyConsumer { @EndpointInject(uri = "mock:result") private ProducerTemplate destination; - @MessageDriven(uri = "direct:start") + @Consume(uri = "direct:start") public void doSomething(String body) { ObjectHelper.notNull(destination, "destination");
3c95d97b0eb464b6788466769919deea219ce24a
tapiji
Provide target platform for building rcp translator
a
https://github.com/tapiji/tapiji
diff --git a/org.eclipselabs.tapiji.translator.rcp.target/.project b/org.eclipselabs.tapiji.translator.rcp.target/.project new file mode 100644 index 00000000..281cb64f --- /dev/null +++ b/org.eclipselabs.tapiji.translator.rcp.target/.project @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipselabs.tapiji.translator.rcp.target</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.m2e.core.maven2Builder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.m2e.core.maven2Nature</nature> + </natures> +</projectDescription> diff --git a/org.eclipselabs.tapiji.translator.rcp.target/org.eclipselabs.tapiji.translator.rcp.target.target b/org.eclipselabs.tapiji.translator.rcp.target/org.eclipselabs.tapiji.translator.rcp.target.target new file mode 100644 index 00000000..0fd162de --- /dev/null +++ b/org.eclipselabs.tapiji.translator.rcp.target/org.eclipselabs.tapiji.translator.rcp.target.target @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<?pde version="3.6"?> + +<target name="org.eclipselabs.tapiji.translator.rcp.target.target" sequenceNumber="11"> +<locations> +<location includeAllPlatforms="false" includeMode="planner" includeSource="true" type="InstallableUnit"> +<unit id="org.eclipse.jdt.feature.group" version="3.7.2.v20120120-1414-7z8gFcuFMP7BW5XTz0jLTnz0l9B1"/> +<repository location="http://download.eclipse.org/releases/indigo"/> +</location> +<location includeAllPlatforms="false" includeMode="planner" includeSource="true" type="InstallableUnit"> +<unit id="org.eclipse.swt.tools.feature.feature.group" version="1.0.1.201103231601"/> +<repository location="http://www.eclipse.org/swt/updates/3.6"/> +</location> +<location path="${project_loc}/plugins" type="Directory"/> +</locations> +</target> diff --git a/org.eclipselabs.tapiji.translator.rcp.target/plugins/org.eclipse.swt.gtk.linux.x86_64.source_3.100.0.v4233d.jar b/org.eclipselabs.tapiji.translator.rcp.target/plugins/org.eclipse.swt.gtk.linux.x86_64.source_3.100.0.v4233d.jar new file mode 100644 index 00000000..b430d16c Binary files /dev/null and b/org.eclipselabs.tapiji.translator.rcp.target/plugins/org.eclipse.swt.gtk.linux.x86_64.source_3.100.0.v4233d.jar differ diff --git a/org.eclipselabs.tapiji.translator.rcp.target/pom.xml b/org.eclipselabs.tapiji.translator.rcp.target/pom.xml new file mode 100644 index 00000000..511c89e0 --- /dev/null +++ b/org.eclipselabs.tapiji.translator.rcp.target/pom.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> + +<!-- + +Copyright (c) 2012 Martin Reiterer + +All rights reserved. This program and the accompanying materials +are made available under the terms of the Eclipse Public License +v1.0 which accompanies this distribution, and is available at +http://www.eclipse.org/legal/epl-v10.html + +Contributors: Martin Reiterer - setup of tycho build for babel tools + +--> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <artifactId>org.eclipselabs.tapiji.translator.rcp.target</artifactId> + <packaging>eclipse-target-definition</packaging> + + <parent> + <groupId>org.eclipselabs.tapiji</groupId> + <artifactId>org.eclipselabs.tapiji.translator.parent</artifactId> + <version>0.9.0.B1</version> + <relativePath>..</relativePath> + </parent> +</project> \ No newline at end of file diff --git a/org.eclipselabs.tapiji.translator.swt.product/.classpath b/org.eclipselabs.tapiji.translator.rcp/.classpath similarity index 100% rename from org.eclipselabs.tapiji.translator.swt.product/.classpath rename to org.eclipselabs.tapiji.translator.rcp/.classpath diff --git a/org.eclipselabs.tapiji.translator.rcp/.project b/org.eclipselabs.tapiji.translator.rcp/.project new file mode 100644 index 00000000..00875724 --- /dev/null +++ b/org.eclipselabs.tapiji.translator.rcp/.project @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipselabs.tapiji.translator.rcp.product</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + </buildSpec> + <natures> + </natures> +</projectDescription> diff --git a/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_128.png b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_128.png similarity index 100% rename from org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_128.png rename to org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_128.png diff --git a/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_16.png b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_16.png similarity index 100% rename from org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_16.png rename to org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_16.png diff --git a/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_32.png b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_32.png similarity index 100% rename from org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_32.png rename to org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_32.png diff --git a/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_48.png b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_48.png similarity index 100% rename from org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_48.png rename to org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_48.png diff --git a/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_64.png b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_64.png similarity index 100% rename from org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_64.png rename to org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_64.png diff --git a/org.eclipselabs.tapiji.translator.swt.product/org.eclipselabs.tapiji.translator.swt.product.product b/org.eclipselabs.tapiji.translator.rcp/org.eclipselabs.tapiji.translator.rcp.product similarity index 98% rename from org.eclipselabs.tapiji.translator.swt.product/org.eclipselabs.tapiji.translator.swt.product.product rename to org.eclipselabs.tapiji.translator.rcp/org.eclipselabs.tapiji.translator.rcp.product index c30539e2..c68c448d 100644 --- a/org.eclipselabs.tapiji.translator.swt.product/org.eclipselabs.tapiji.translator.swt.product.product +++ b/org.eclipselabs.tapiji.translator.rcp/org.eclipselabs.tapiji.translator.rcp.product @@ -1,7 +1,7 @@ <?xml version="1.0" encoding="UTF-8"?> <?pde version="3.5"?> -<product name="TapiJI Translator" uid="org.eclipselabs.tapiji.translator.swt.product" id="org.eclipselabs.tapiji.translator.app" application="org.eclipselabs.tapiji.translator.application" version="0.9.0.B1" useFeatures="false" includeLaunchers="true"> +<product name="TapiJI Translator" uid="org.eclipselabs.tapiji.translator.product" id="org.eclipselabs.tapiji.translator.app" application="org.eclipselabs.tapiji.translator.application" version="0.9.0.B1" useFeatures="false" includeLaunchers="true"> <aboutInfo> <image path="/org.eclipselabs.tapiji.translator/icons/TapiJI_128.png"/> @@ -295,7 +295,7 @@ litigation. <plugin id="org.eclipse.pde.build"/> <plugin id="org.eclipse.pde.core"/> <plugin id="org.eclipse.swt"/> - <plugin id="org.eclipse.swt.gtk.linux.x86_64" fragment="true"/> + <plugin id="org.eclipse.swt.gtk.linux.x86_64" fragment="true" os="linux" ws="gtk" arch="x86_64"/> <plugin id="org.eclipse.team.core"/> <plugin id="org.eclipse.team.ui"/> <plugin id="org.eclipse.text"/> diff --git a/org.eclipselabs.tapiji.translator.swt.product/pom.xml b/org.eclipselabs.tapiji.translator.rcp/pom.xml similarity index 95% rename from org.eclipselabs.tapiji.translator.swt.product/pom.xml rename to org.eclipselabs.tapiji.translator.rcp/pom.xml index 5fa8fc8c..879e64b4 100644 --- a/org.eclipselabs.tapiji.translator.swt.product/pom.xml +++ b/org.eclipselabs.tapiji.translator.rcp/pom.xml @@ -9,7 +9,7 @@ <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> - <artifactId>org.eclipselabs.tapiji.translator.swt.product</artifactId> + <artifactId>org.eclipselabs.tapiji.translator.rcp</artifactId> <packaging>eclipse-application</packaging> <parent> diff --git a/org.eclipselabs.tapiji.translator.swt.product/splash.bmp b/org.eclipselabs.tapiji.translator.rcp/splash.bmp similarity index 100% rename from org.eclipselabs.tapiji.translator.swt.product/splash.bmp rename to org.eclipselabs.tapiji.translator.rcp/splash.bmp diff --git a/org.eclipselabs.tapiji.translator.swt.product/.project b/org.eclipselabs.tapiji.translator.swt.product/.project index 650df245..00875724 100644 --- a/org.eclipselabs.tapiji.translator.swt.product/.project +++ b/org.eclipselabs.tapiji.translator.swt.product/.project @@ -1,7 +1,11 @@ <?xml version="1.0" encoding="UTF-8"?> <projectDescription> - <name>org.eclipselabs.tapiji.translator.swt.parent</name> + <name>org.eclipselabs.tapiji.translator.rcp.product</name> <comment></comment> <projects> </projects> + <buildSpec> + </buildSpec> + <natures> + </natures> </projectDescription> diff --git a/org.eclipselabs.tapiji.translator.swt/fragment.xml b/org.eclipselabs.tapiji.translator.swt/fragment.xml index bfa8380e..b766f829 100644 --- a/org.eclipselabs.tapiji.translator.swt/fragment.xml +++ b/org.eclipselabs.tapiji.translator.swt/fragment.xml @@ -6,11 +6,11 @@ id="app" point="org.eclipse.core.runtime.products"> <product - application="org.eclipselabs.tapiji.translator.application" + application="org.eclipselabs.tapiji.translator.swt.application" name="TapiJI Translator"> <property name="windowImages" - value="icons/TapiJI_16.png,icons/TapiJI_32.png,icons/TapiJI_48.png,icons/TapiJI_64.png,icons/TapiJI_128.png"> + value="platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_16.png,platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_32.png,platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_48.png,platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_64.png,platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_128.png"> </property> <property name="aboutText" @@ -18,7 +18,7 @@ </property> <property name="aboutImage" - value="icons/TapiJI_128.png"> + value="platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_128.png"> </property> <property name="appName" diff --git a/org.eclipselabs.tapiji.translator/plugin.xml b/org.eclipselabs.tapiji.translator/plugin.xml index a70c870f..ab2c7385 100644 --- a/org.eclipselabs.tapiji.translator/plugin.xml +++ b/org.eclipselabs.tapiji.translator/plugin.xml @@ -1,6 +1,41 @@ <?xml version="1.0" encoding="UTF-8"?> <?eclipse version="3.4"?> <plugin> +<extension + id="app" + point="org.eclipse.core.runtime.products"> + <product + application="org.eclipselabs.tapiji.translator.application" + name="TapiJI Translator"> + <property + name="windowImages" + value="icons/TapiJI_16.png,icons/TapiJI_32.png,icons/TapiJI_48.png,icons/TapiJI_64.png,icons/TapiJI_128.png"> + </property> + <property + name="aboutText" + value="TapiJI - Translator &#x0A;Version 1.0.0&#x0A;by Stefan Strobl &amp; Martin Reiterer"> + </property> + <property + name="aboutImage" + value="icons/TapiJI_128.png"> + </property> + <property + name="appName" + value="TapiJI Translator"> + </property> + </product> + </extension> + <extension + id="application" + point="org.eclipse.core.runtime.applications"> + <application> + <run + class="org.eclipselabs.tapiji.translator.rcp.compat.Application"> + </run> + </application> + </extension> + + <extension point="org.eclipse.ui.bindings"> <key @@ -60,7 +95,7 @@ id="app" point="org.eclipse.core.runtime.products"> <product - application="org.eclipselabs.tapiji.translator.application" + application="org.eclipse.ant.core.antRunner" name="TapiJI Translator"> <property name="windowImages" @@ -74,6 +109,10 @@ name="aboutImage" value="icons/TapiJI_128.png"> </property> + <property + name="appName" + value="TapiJI Translator"> + </property> </product> </extension> </plugin> diff --git a/pom.xml b/pom.xml index d4ce706f..d275de02 100644 --- a/pom.xml +++ b/pom.xml @@ -8,187 +8,195 @@ eclipse signing plugin, babel p2 repository --> <project - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" - xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - <modelVersion>4.0.0</modelVersion> - <groupId>org.eclipselabs.tapiji</groupId> - <artifactId>org.eclipselabs.tapiji.translator.parent</artifactId> - <version>0.9.0.B1</version> - <packaging>pom</packaging> + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + <groupId>org.eclipselabs.tapiji</groupId> + <artifactId>org.eclipselabs.tapiji.translator.parent</artifactId> + <version>0.9.0.B1</version> + <packaging>pom</packaging> - <modules> - <module>org.eclipselabs.tapiji.translator.swt.compat</module> - <module>org.eclipselabs.tapiji.translator</module> - <module>org.eclipselabs.tapiji.translator.swt.product</module> - </modules> + <modules> + <module>org.eclipselabs.tapiji.translator.rcp.target</module> + <module>org.eclipselabs.tapiji.translator.swt</module> + <module>org.eclipselabs.tapiji.translator.swt.compat</module> + <module>org.eclipselabs.tapiji.translator</module> + <module>org.eclipselabs.tapiji.translator.rcp</module> + </modules> - <properties> - <tycho-version>0.16.0</tycho-version> - <eclipse-repository-url>http://download.eclipse.org/eclipse/updates/3.6</eclipse-repository-url> - <babel-plugins-url>http://build.eclipse.org/technology/babel/tools-updates-nightly</babel-plugins-url> - </properties> + <properties> + <tycho-version>0.16.0</tycho-version> + <eclipse-repository-url>http://download.eclipse.org/eclipse/updates/3.6</eclipse-repository-url> + <babel-plugins-url>http://build.eclipse.org/technology/babel/tools-updates-nightly</babel-plugins-url> + </properties> - <profiles> - <profile> - <id>indigo rcp</id> - <properties> - <eclipse-repository-url>http://download.eclipse.org/releases/indigo</eclipse-repository-url> - <babel-plugins-url>http://build.eclipse.org/technology/babel/tools-updates-nightly</babel-plugins-url> - </properties> - <activation> - <activeByDefault>true</activeByDefault> - <property> - <name>maven.profile</name> - <value>swt-editor</value> - </property> - </activation> - <build> - <plugins> - <plugin> - <groupId>org.eclipse.tycho</groupId> - <artifactId>target-platform-configuration</artifactId> - <version>${tycho-version}</version> - <configuration> - <!-- disable resolving of optional dependencies, but define the extra - dependencies --> - <dependency-resolution> - <optionalDependencies>ignore</optionalDependencies> - <extraRequirements> - <requirement> - <type>eclipse-plugin</type> - <id>org.eclipselabs.tapiji.translator.swt.compat</id> - <versionRange>0.0.0</versionRange> - </requirement> - <requirement> - <type>eclipse-plugin</type> - <id>org.eclipse.babel.editor.swt.compat</id> - <versionRange>0.9.0</versionRange> - </requirement> - <requirement> - <type>eclipse-plugin</type> - <id>org.eclipse.ui</id> - <versionRange>0.0.0</versionRange> - </requirement> - <requirement> - <type>eclipse-plugin</type> - <id>org.eclipse.jface.text</id> - <versionRange>0.0.0</versionRange> - </requirement> - <requirement> - <type>eclipse-plugin</type> - <id>org.eclipse.ui.editors</id> - <versionRange>0.0.0</versionRange> - </requirement> - <requirement> - <type>eclipse-plugin</type> - <id>org.eclipse.ui.ide</id> - <versionRange>0.0.0</versionRange> - </requirement> - <requirement> - <type>eclipse-plugin</type> - <id>org.eclipse.ui.workbench.texteditor</id> - <versionRange>0.0.0</versionRange> - </requirement> - <requirement> - <type>eclipse-plugin</type> - <id>org.eclipse.ui.forms</id> - <versionRange>0.0.0</versionRange> - </requirement> - <requirement> - <type>eclipse-plugin</type> - <id>org.eclipse.ltk.core.refactoring</id> - <versionRange>0.0.0</versionRange> - </requirement> - <requirement> - <type>eclipse-plugin</type> - <id>org.eclipse.ltk.ui.refactoring</id> - <versionRange>0.0.0</versionRange> - </requirement> - <requirement> - <type>eclipse-plugin</type> - <id>org.junit</id> - <versionRange>0.0.0</versionRange> - </requirement> - <requirement> - <type>eclipse-plugin</type> - <id>org.eclipse.ui.forms</id> - <versionRange>3.5.101</versionRange> - </requirement> - </extraRequirements> - </dependency-resolution> - </configuration> - </plugin> - </plugins> - </build> - </profile> - </profiles> + <profiles> + <profile> + <id>indigo rcp</id> + <properties> + <eclipse-repository-url>http://download.eclipse.org/releases/indigo</eclipse-repository-url> + <babel-plugins-url>http://build.eclipse.org/technology/babel/tools-updates-nightly</babel-plugins-url> + </properties> + <activation> + <activeByDefault>true</activeByDefault> + <property> + <name>maven.profile</name> + <value>swt-editor</value> + </property> + </activation> + <build> - <repositories> - <repository> - <id>eclipse-repository</id> - <url>${eclipse-repository-url}</url> - <layout>p2</layout> - </repository> - <repository> - <id>babel-extension-plugins</id> - <url>${babel-plugins-url}</url> - <layout>p2</layout> - </repository> - </repositories> + <plugins> + <plugin> + <groupId>org.eclipse.tycho</groupId> + <artifactId>target-platform-configuration</artifactId> + <version>${tycho-version}</version> + <configuration> + <target> + <artifact> + <groupId>${project.groupId}</groupId> + <artifactId>org.eclipselabs.tapiji.translator.rcp.target</artifactId> + <version>${project.version}</version> + </artifact> + </target> + <dependency-resolution> + <optionalDependencies>ignore</optionalDependencies> + <extraRequirements> + <requirement> + <type>eclipse-plugin</type> + <id>org.eclipselabs.tapiji.translator.swt.compat</id> + <versionRange>0.0.0</versionRange> + </requirement> + <requirement> + <type>eclipse-plugin</type> + <id>org.eclipse.babel.editor.swt.compat</id> + <versionRange>0.9.0</versionRange> + </requirement> + <requirement> + <type>eclipse-plugin</type> + <id>org.eclipse.ui</id> + <versionRange>0.0.0</versionRange> + </requirement> + <requirement> + <type>eclipse-plugin</type> + <id>org.eclipse.jface.text</id> + <versionRange>0.0.0</versionRange> + </requirement> + <requirement> + <type>eclipse-plugin</type> + <id>org.eclipse.ui.editors</id> + <versionRange>0.0.0</versionRange> + </requirement> + <requirement> + <type>eclipse-plugin</type> + <id>org.eclipse.ui.ide</id> + <versionRange>0.0.0</versionRange> + </requirement> + <requirement> + <type>eclipse-plugin</type> + <id>org.eclipse.ui.workbench.texteditor</id> + <versionRange>0.0.0</versionRange> + </requirement> + <requirement> + <type>eclipse-plugin</type> + <id>org.eclipse.ui.forms</id> + <versionRange>0.0.0</versionRange> + </requirement> + <requirement> + <type>eclipse-plugin</type> + <id>org.eclipse.ltk.core.refactoring</id> + <versionRange>0.0.0</versionRange> + </requirement> + <requirement> + <type>eclipse-plugin</type> + <id>org.eclipse.ltk.ui.refactoring</id> + <versionRange>0.0.0</versionRange> + </requirement> + <requirement> + <type>eclipse-plugin</type> + <id>org.junit</id> + <versionRange>0.0.0</versionRange> + </requirement> + <requirement> + <type>eclipse-plugin</type> + <id>org.eclipse.ui.forms</id> + <versionRange>3.5.101</versionRange> + </requirement> + </extraRequirements> + </dependency-resolution> + </configuration> + </plugin> + </plugins> + </build> + </profile> + </profiles> - <build> - <plugins> - <plugin> - <groupId>org.eclipse.tycho</groupId> - <artifactId>tycho-maven-plugin</artifactId> - <version>${tycho-version}</version> - <extensions>true</extensions> - </plugin> - <plugin> - <groupId>org.eclipse.tycho</groupId> - <artifactId>target-platform-configuration</artifactId> - <version>${tycho-version}</version> - <configuration> - <environments> - <environment> - <os>linux</os> - <ws>gtk</ws> - <arch>x86_64</arch> - </environment> - <environment> - <os>linux</os> - <ws>gtk</ws> - <arch>x86</arch> - </environment> - <environment> - <os>macosx</os> - <ws>carbon</ws> - <arch>x86</arch> - </environment> - <environment> - <os>macosx</os> - <ws>cocoa</ws> - <arch>x86</arch> - </environment> - <environment> - <os>macosx</os> - <ws>cocoa</ws> - <arch>x86_64</arch> - </environment> - <environment> - <os>win32</os> - <ws>win32</ws> - <arch>x86</arch> - </environment> - <environment> - <os>win32</os> - <ws>win32</ws> - <arch>x86_64</arch> - </environment> - </environments> - </configuration> - </plugin> - </plugins> - </build> + <repositories> + <repository> + <id>eclipse-repository</id> + <url>${eclipse-repository-url}</url> + <layout>p2</layout> + </repository> + <repository> + <id>babel-extension-plugins</id> + <url>${babel-plugins-url}</url> + <layout>p2</layout> + </repository> + </repositories> + + <build> + <plugins> + <plugin> + <groupId>org.eclipse.tycho</groupId> + <artifactId>tycho-maven-plugin</artifactId> + <version>${tycho-version}</version> + <extensions>true</extensions> + </plugin> + <plugin> + <groupId>org.eclipse.tycho</groupId> + <artifactId>target-platform-configuration</artifactId> + <version>${tycho-version}</version> + <configuration> + <environments> + <environment> + <os>linux</os> + <ws>gtk</ws> + <arch>x86_64</arch> + </environment> + <environment> + <os>linux</os> + <ws>gtk</ws> + <arch>x86</arch> + </environment> + <environment> + <os>macosx</os> + <ws>carbon</ws> + <arch>x86</arch> + </environment> + <environment> + <os>macosx</os> + <ws>cocoa</ws> + <arch>x86</arch> + </environment> + <environment> + <os>macosx</os> + <ws>cocoa</ws> + <arch>x86_64</arch> + </environment> + <environment> + <os>win32</os> + <ws>win32</ws> + <arch>x86</arch> + </environment> + <environment> + <os>win32</os> + <ws>win32</ws> + <arch>x86_64</arch> + </environment> + </environments> + </configuration> + </plugin> + </plugins> + </build> </project>
164090e9d548d8cc58c7a1d701f52ae2ea77be11
mitreid-connect$openid-connect-java-spring-server
added jwt string stability to several places, fixed jwe parser
p
https://github.com/mitreid-connect/openid-connect-java-spring-server
diff --git a/openid-connect-common/src/main/java/org/mitre/jwe/model/Jwe.java b/openid-connect-common/src/main/java/org/mitre/jwe/model/Jwe.java index e240cd3a45..331ac877f7 100644 --- a/openid-connect-common/src/main/java/org/mitre/jwe/model/Jwe.java +++ b/openid-connect-common/src/main/java/org/mitre/jwe/model/Jwe.java @@ -40,6 +40,7 @@ public Jwe(JweHeader header, byte[] encryptedKey, byte[] ciphertext, String inte this.ciphertext = ciphertext; } + /* public Jwe(String headerBase64, String encryptedKeyBase64, String cipherTextBase64, String integrityValueBase64) { byte[] decodedEncryptedKey = Base64.decodeBase64(encryptedKeyBase64.getBytes()); byte[] decodedCipherText = Base64.decodeBase64(cipherTextBase64.getBytes()); @@ -48,6 +49,7 @@ public Jwe(String headerBase64, String encryptedKeyBase64, String cipherTextBase this.ciphertext = decodedCipherText; setSignature(integrityValueBase64); } + */ public JweHeader getHeader() { return header; @@ -75,11 +77,10 @@ public void setCiphertext(byte[] ciphertext) { @Override public String getSignatureBase() { - JsonObject h = header.getAsJsonObject(); byte[] c = ciphertext; byte[] e = encryptedKey; - String h64 = new String(Base64.encodeBase64URLSafe(h.toString().getBytes())); + String h64 = new String(Base64.encodeBase64URLSafe(header.toJsonString().getBytes())); String e64 = new String(Base64.encodeBase64URLSafe(e)); String c64 = new String(Base64.encodeBase64URLSafe(c)); @@ -106,7 +107,10 @@ public static Jwe parse(String s) { String c64 = parts.get(2); String i64 = parts.get(3); - Jwe jwe = new Jwe(h64, e64, c64, i64); + byte[] decodedEncryptedKey = Base64.decodeBase64(e64.getBytes()); + byte[] decodedCipherText = Base64.decodeBase64(c64.getBytes()); + + Jwe jwe = new Jwe(new JweHeader(h64), decodedEncryptedKey, decodedCipherText, i64); return jwe; diff --git a/openid-connect-common/src/main/java/org/mitre/jwt/model/ClaimSet.java b/openid-connect-common/src/main/java/org/mitre/jwt/model/ClaimSet.java index 9db1577000..26c1832d0a 100644 --- a/openid-connect-common/src/main/java/org/mitre/jwt/model/ClaimSet.java +++ b/openid-connect-common/src/main/java/org/mitre/jwt/model/ClaimSet.java @@ -96,7 +96,7 @@ public Date getClaimAsDate(String key) { * Set an extension claim */ public void setClaim(String key, Object value) { - jsonString = null; + invalidateString(); claims.put(key, value); } @@ -104,7 +104,7 @@ public void setClaim(String key, Object value) { * Set a primitive claim */ public void setClaim(String key, JsonPrimitive prim) { - jsonString = null; + invalidateString(); if (prim == null) { // in case we get here with a primitive null claims.put(key, prim); @@ -116,12 +116,17 @@ public void setClaim(String key, JsonPrimitive prim) { claims.put(key, prim.getAsString()); } + } + + private void invalidateString() { + jsonString = null; } /** * Remove an extension claim */ public Object removeClaim(String key) { + invalidateString(); return claims.remove(key); } @@ -131,6 +136,7 @@ public Object removeClaim(String key) { * @see java.util.Map#clear() */ public void clear() { + invalidateString(); claims.clear(); } @@ -197,7 +203,7 @@ public void loadFromJsonObject(JsonObject json) { } /** - * Load a new claims set from a Base64 encoded JSON Object string + * Load a new claims set from a Base64 encoded JSON Object string and caches the string used */ public void loadFromBase64JsonObjectString(String b64) { byte[] b64decoded = Base64.decodeBase64(b64); @@ -206,9 +212,12 @@ public void loadFromBase64JsonObjectString(String b64) { JsonObject json = parser.parse(new InputStreamReader(new ByteArrayInputStream(b64decoded))).getAsJsonObject(); loadFromJsonObject(json); + + // save the string we were passed in (decoded from base64) + jsonString = new String(b64decoded); } - public String toString() { + public String toJsonString() { if(jsonString == null) { jsonString = this.getAsJsonObject().toString(); } diff --git a/openid-connect-common/src/main/java/org/mitre/jwt/model/Jwt.java b/openid-connect-common/src/main/java/org/mitre/jwt/model/Jwt.java index e40e548232..8b85cf8805 100644 --- a/openid-connect-common/src/main/java/org/mitre/jwt/model/Jwt.java +++ b/openid-connect-common/src/main/java/org/mitre/jwt/model/Jwt.java @@ -124,8 +124,8 @@ public String toString() { */ public String getSignatureBase() { - String h64 = new String(Base64.encodeBase64URLSafe(header.toString().getBytes())); - String c64 = new String(Base64.encodeBase64URLSafe(claims.toString().getBytes())); + String h64 = new String(Base64.encodeBase64URLSafe(header.toJsonString().getBytes())); + String c64 = new String(Base64.encodeBase64URLSafe(claims.toJsonString().getBytes())); return h64 + "." + c64; }
efa7f1fccf51ef1a83266e815d124c782c2a0815
intellij-community
Typos--
p
https://github.com/JetBrains/intellij-community
diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffPanelImpl.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffPanelImpl.java index 1c706ff80a7b6..3cdc48f03a2a5 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffPanelImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/DiffPanelImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -75,7 +75,7 @@ public class DiffPanelImpl implements DiffPanelEx, ContentChangeListener, TwoSid private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.diff.impl.DiffPanelImpl"); private final DiffSplitterI mySplitter; - private final DiffPanelOutterComponent myPanel; + private final DiffPanelOuterComponent myPanel; private final Window myOwnerWindow; private final DiffPanelOptions myOptions; @@ -91,7 +91,7 @@ public class DiffPanelImpl implements DiffPanelEx, ContentChangeListener, TwoSid private final FontSizeSynchronizer myFontSizeSynchronizer = new FontSizeSynchronizer(); private DiffRequest myDiffRequest; private boolean myIsRequestFocus = true; - private boolean myIsSynchScroll; + private boolean myIsSyncScroll; private static final DiffRequest.ToolbarAddons TOOL_BAR = new DiffRequest.ToolbarAddons() { public void customize(DiffToolbar toolbar) { @@ -102,20 +102,19 @@ public void customize(DiffToolbar toolbar) { private boolean myDisposed = false; private final GenericDataProvider myDataProvider; private final Project myProject; - private final boolean myIsHorisontal; + private final boolean myIsHorizontal; private CanNotCalculateDiffPanel myNotCalculateDiffPanel; - private DiffIsApproximate myDiffIsApproximate; private final VisibleAreaListener myVisibleAreaListener; - public DiffPanelImpl(final Window owner, Project project, boolean enableToolbar, boolean horisontal) { + public DiffPanelImpl(final Window owner, Project project, boolean enableToolbar, boolean horizontal) { myProject = project; - myIsHorisontal = horisontal; + myIsHorizontal = horizontal; myOptions = new DiffPanelOptions(this); - myPanel = new DiffPanelOutterComponent(TextDiffType.DIFF_TYPES, TOOL_BAR); + myPanel = new DiffPanelOuterComponent(TextDiffType.DIFF_TYPES, TOOL_BAR); myPanel.disableToolbar(!enableToolbar); if (enableToolbar) myPanel.resetToolbar(); myOwnerWindow = owner; - myIsSynchScroll = true; + myIsSyncScroll = true; myLeftSide = new DiffSideView("", this); myRightSide = new DiffSideView("", this); myLeftSide.becomeMaster(); @@ -123,9 +122,9 @@ public DiffPanelImpl(final Window owner, Project project, boolean enableToolbar, myData = createDiffPanelState(this); - if (horisontal) { + if (horizontal) { mySplitter = new DiffSplitter(myLeftSide.getComponent(), myRightSide.getComponent(), - new DiffDividerPaint(this, FragmentSide.SIDE1), myData); + new DiffDividerPaint(this, FragmentSide.SIDE1), myData); } else { mySplitter = new HorizontalDiffSplitter(myLeftSide.getComponent(), myRightSide.getComponent()); @@ -164,7 +163,7 @@ protected DiffPanelState createDiffPanelState(@NotNull Disposable parentDisposab } public boolean isHorisontal() { - return myIsHorisontal; + return myIsHorizontal; } public DiffPanelState getDiffPanelState() { @@ -172,7 +171,7 @@ public DiffPanelState getDiffPanelState() { } public void noSynchScroll() { - myIsSynchScroll = false; + myIsSyncScroll = false; } public DiffSplitterI getSplitter() { @@ -298,8 +297,7 @@ public void setTooBigFileErrorContents() { public void setPatchAppliedApproximately() { if (myNotCalculateDiffPanel == null) { - myDiffIsApproximate = new DiffIsApproximate(); - myPanel.insertTopComponent(myDiffIsApproximate); + myPanel.insertTopComponent(new DiffIsApproximate()); } } @@ -402,7 +400,7 @@ public Rediffers getDiffUpdater() { public void onContentChangedIn(EditorSource source) { myDiffUpdater.contentRemoved(source); final EditorEx editor = source.getEditor(); - if (myIsHorisontal && source.getSide() == FragmentSide.SIDE1 && editor != null) { + if (myIsHorizontal && source.getSide() == FragmentSide.SIDE1 && editor != null) { editor.setVerticalScrollbarOrientation(EditorEx.VERTICAL_SCROLLBAR_LEFT); } DiffSideView viewSide = getSideView(source.getSide()); @@ -425,7 +423,7 @@ public void onContentChangedIn(EditorSource source) { Editor editor1 = getEditor(FragmentSide.SIDE1); Editor editor2 = getEditor(FragmentSide.SIDE2); - if (editor1 != null && editor2 != null && myIsSynchScroll) { + if (editor1 != null && editor2 != null && myIsSyncScroll) { myScrollSupport.install(new EditingSides[]{this}); } @@ -572,7 +570,7 @@ public void setRequestFocus(boolean isRequestFocus) { myIsRequestFocus = isRequestFocus; } - private class MyScrollingPanel implements DiffPanelOutterComponent.ScrollingPanel { + private class MyScrollingPanel implements DiffPanelOuterComponent.ScrollingPanel { public void scrollEditors() { getOptions().onNewContent(myCurrentSide); diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/ui/MergePanel2.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/ui/MergePanel2.java index 45694aea4256f..37bcf703b30e8 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/ui/MergePanel2.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/incrementalMerge/ui/MergePanel2.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,7 +64,7 @@ public class MergePanel2 implements DiffViewer { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.diff.impl.incrementalMerge.ui.MergePanel2"); - private final DiffPanelOutterComponent myPanel; + private final DiffPanelOuterComponent myPanel; private DiffRequest myData; private MergeList myMergeList; private boolean myDuringCreation = false; @@ -109,7 +109,7 @@ public void onEditorReleased(Editor releasedEditor) { myEditorsPanels[i].setComponent(editorPlace); } FontSizeSynchronizer.attachTo(editorPlaces); - myPanel = new DiffPanelOutterComponent(TextDiffType.MERGE_TYPES, TOOLBAR); + myPanel = new DiffPanelOuterComponent(TextDiffType.MERGE_TYPES, TOOLBAR); myPanel.insertDiffComponent(new ThreePanels(myEditorsPanels, myDividers), new MyScrollingPanel()); myProvider = new MyDataProvider(); myPanel.setDataProvider(myProvider); @@ -328,7 +328,7 @@ public LineBlocks getLineBlocks() { } } - private class MyScrollingPanel implements DiffPanelOutterComponent.ScrollingPanel { + private class MyScrollingPanel implements DiffPanelOuterComponent.ScrollingPanel { public void scrollEditors() { Editor centerEditor = getEditor(1); JComponent centerComponent = centerEditor.getContentComponent(); @@ -504,9 +504,9 @@ public void onChangeRemoved(ChangeList source) { } private static class StatusUpdater implements ChangeCounter.Listener { - private final DiffPanelOutterComponent myPanel; + private final DiffPanelOuterComponent myPanel; - private StatusUpdater(DiffPanelOutterComponent panel) { + private StatusUpdater(DiffPanelOuterComponent panel) { myPanel = panel; } @@ -527,7 +527,7 @@ public void dispose(@NotNull MergeList mergeList) { ChangeCounter.getOrCreate(mergeList).removeListener(this); } - public static StatusUpdater install(MergeList mergeList, DiffPanelOutterComponent panel) { + public static StatusUpdater install(MergeList mergeList, DiffPanelOuterComponent panel) { ChangeCounter counters = ChangeCounter.getOrCreate(mergeList); StatusUpdater updater = new StatusUpdater(panel); counters.addListener(updater); diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/util/DiffPanelOutterComponent.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/util/DiffPanelOuterComponent.java similarity index 93% rename from platform/platform-impl/src/com/intellij/openapi/diff/impl/util/DiffPanelOutterComponent.java rename to platform/platform-impl/src/com/intellij/openapi/diff/impl/util/DiffPanelOuterComponent.java index 889c5f9e84286..0e377859ca007 100644 --- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/util/DiffPanelOutterComponent.java +++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/util/DiffPanelOuterComponent.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,7 @@ import java.awt.*; import java.util.List; -public class DiffPanelOutterComponent extends JPanel implements DataProvider { +public class DiffPanelOuterComponent extends JPanel implements DataProvider { private final DiffStatusBar myStatusBar; private final DiffToolbarComponent myToolbar; private final DiffRequest.ToolbarAddons myDefaultActions; @@ -43,7 +43,7 @@ public class DiffPanelOutterComponent extends JPanel implements DataProvider { private int myPrefferedWidth; private Getter<Integer> myDefaultHeight; - public DiffPanelOutterComponent(List<TextDiffType> diffTypes, DiffRequest.ToolbarAddons defaultActions) { + public DiffPanelOuterComponent(List<TextDiffType> diffTypes, DiffRequest.ToolbarAddons defaultActions) { super(new BorderLayout()); myStatusBar = new DiffStatusBar(diffTypes); myBottomContainer = new JPanel(new BorderLayout()); @@ -203,7 +203,7 @@ public void addStatusBar() { private interface DeferScrollToFirstDiff { DeferScrollToFirstDiff scrollNow(ScrollingPanel panel, JComponent component); - void deferScroll(DiffPanelOutterComponent outter); + void deferScroll(DiffPanelOuterComponent outer); } public interface ScrollingPanel { @@ -215,7 +215,7 @@ public DeferScrollToFirstDiff scrollNow(ScrollingPanel panel, JComponent compone return NO_SCROLL_NEEDED; } - public void deferScroll(DiffPanelOutterComponent outter) { + public void deferScroll(DiffPanelOuterComponent outer) { } }; @@ -226,11 +226,11 @@ public DeferScrollToFirstDiff scrollNow(ScrollingPanel panel, JComponent compone return NO_SCROLL_NEEDED; } - public void deferScroll(final DiffPanelOutterComponent outter) { - if (!outter.isDisplayable()) return; + public void deferScroll(final DiffPanelOuterComponent outer) { + if (!outer.isDisplayable()) return; SwingUtilities.invokeLater(new Runnable() { public void run() { - outter.performScroll(); + outer.performScroll(); } }); }
e3d1a1dda22723fc896bfc96c6db57c500faf208
spring-framework
@Resource injection points support @Lazy as well--Issue: SPR-
a
https://github.com/spring-projects/spring-framework
diff --git a/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java b/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java index 592af8ef932f..ffb9b55320b6 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,6 +44,8 @@ import javax.xml.ws.WebServiceClient; import javax.xml.ws.WebServiceRef; +import org.springframework.aop.TargetSource; +import org.springframework.aop.framework.ProxyFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyValues; @@ -414,6 +416,44 @@ else if (bridgedMethod.isAnnotationPresent(Resource.class)) { return new InjectionMetadata(clazz, elements); } + /** + * Obtain a lazily resolving resource proxy for the given name and type, + * delegating to {@link #getResource} on demand once a method call comes in. + * @param element the descriptor for the annotated field/method + * @param requestingBeanName the name of the requesting bean + * @return the resource object (never {@code null}) + * @since 4.2 + * @see #getResource + * @see Lazy + */ + protected Object buildLazyResourceProxy(final LookupElement element, final String requestingBeanName) { + TargetSource ts = new TargetSource() { + @Override + public Class<?> getTargetClass() { + return element.lookupType; + } + @Override + public boolean isStatic() { + return false; + } + @Override + public Object getTarget() { + return getResource(element, requestingBeanName); + } + @Override + public void releaseTarget(Object target) { + } + }; + ProxyFactory pf = new ProxyFactory(); + pf.setTargetSource(ts); + if (element.lookupType.isInterface()) { + pf.addInterface(element.lookupType); + } + ClassLoader classLoader = (this.beanFactory instanceof ConfigurableBeanFactory ? + ((ConfigurableBeanFactory) this.beanFactory).getBeanClassLoader() : null); + return pf.getProxy(classLoader); + } + /** * Obtain the resource object for the given name and type. * @param element the descriptor for the annotated field/method @@ -527,6 +567,8 @@ public final DependencyDescriptor getDependencyDescriptor() { */ private class ResourceElement extends LookupElement { + private final boolean lazyLookup; + public ResourceElement(Member member, AnnotatedElement ae, PropertyDescriptor pd) { super(member, pd); Resource resource = ae.getAnnotation(Resource.class); @@ -552,11 +594,14 @@ else if (beanFactory instanceof ConfigurableBeanFactory){ this.name = resourceName; this.lookupType = resourceType; this.mappedName = resource.mappedName(); + Lazy lazy = ae.getAnnotation(Lazy.class); + this.lazyLookup = (lazy != null && lazy.value()); } @Override protected Object getResourceToInject(Object target, String requestingBeanName) { - return getResource(this, requestingBeanName); + return (this.lazyLookup ? buildLazyResourceProxy(this, requestingBeanName) : + getResource(this, requestingBeanName)); } } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java b/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java index c44662b418a9..92c684543feb 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -437,6 +437,60 @@ public void testExtendedEjbInjection() { assertTrue(bean.destroy2Called); } + @Test + public void testLazyResolutionWithResourceField() { + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor(); + bpp.setBeanFactory(bf); + bf.addBeanPostProcessor(bpp); + + bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(LazyResourceFieldInjectionBean.class)); + bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); + + LazyResourceFieldInjectionBean bean = (LazyResourceFieldInjectionBean) bf.getBean("annotatedBean"); + assertFalse(bf.containsSingleton("testBean")); + bean.testBean.setName("notLazyAnymore"); + assertTrue(bf.containsSingleton("testBean")); + TestBean tb = (TestBean) bf.getBean("testBean"); + assertEquals("notLazyAnymore", tb.getName()); + } + + @Test + public void testLazyResolutionWithResourceMethod() { + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor(); + bpp.setBeanFactory(bf); + bf.addBeanPostProcessor(bpp); + + bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(LazyResourceMethodInjectionBean.class)); + bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); + + LazyResourceMethodInjectionBean bean = (LazyResourceMethodInjectionBean) bf.getBean("annotatedBean"); + assertFalse(bf.containsSingleton("testBean")); + bean.testBean.setName("notLazyAnymore"); + assertTrue(bf.containsSingleton("testBean")); + TestBean tb = (TestBean) bf.getBean("testBean"); + assertEquals("notLazyAnymore", tb.getName()); + } + + @Test + public void testLazyResolutionWithCglibProxy() { + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + CommonAnnotationBeanPostProcessor bpp = new CommonAnnotationBeanPostProcessor(); + bpp.setBeanFactory(bf); + bf.addBeanPostProcessor(bpp); + + bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(LazyResourceCglibInjectionBean.class)); + bf.registerBeanDefinition("testBean", new RootBeanDefinition(TestBean.class)); + + LazyResourceCglibInjectionBean bean = (LazyResourceCglibInjectionBean) bf.getBean("annotatedBean"); + assertFalse(bf.containsSingleton("testBean")); + bean.testBean.setName("notLazyAnymore"); + assertTrue(bf.containsSingleton("testBean")); + TestBean tb = (TestBean) bf.getBean("testBean"); + assertEquals("notLazyAnymore", tb.getName()); + } + public static class AnnotatedInitDestroyBean { @@ -716,6 +770,35 @@ private static class ConvertedResourceInjectionBean { } + private static class LazyResourceFieldInjectionBean { + + @Resource @Lazy + private ITestBean testBean; + } + + + private static class LazyResourceMethodInjectionBean { + + private ITestBean testBean; + + @Resource @Lazy + public void setTestBean(ITestBean testBean) { + this.testBean = testBean; + } + } + + + private static class LazyResourceCglibInjectionBean { + + private TestBean testBean; + + @Resource @Lazy + public void setTestBean(TestBean testBean) { + this.testBean = testBean; + } + } + + @SuppressWarnings("unused") private static class NullFactory {
c9636b264a6487de1c7718f391a3c93f3a2aabf4
Vala
libnotify: Updated to 0.7.6-3-gda49c8c See https://bugzilla.gnome.org/show_bug.cgi?id=667904
a
https://github.com/GNOME/vala/
diff --git a/vapi/libnotify.vapi b/vapi/libnotify.vapi index 9c44b6bdfe..19b2967110 100644 --- a/vapi/libnotify.vapi +++ b/vapi/libnotify.vapi @@ -14,17 +14,17 @@ namespace Notify { public void set_app_name (string app_name); public void set_category (string category); public void set_hint (string key, GLib.Variant? value); - [Deprecated (since = "0.6.")] + [Deprecated] public void set_hint_byte (string key, [CCode (type = "guchar")] uchar value); - [Deprecated (since = "0.6.")] - public void set_hint_byte_array (string key, [CCode (array_length = false, type = "const guchar*")] uchar[] value, size_t len); - [Deprecated (since = "0.6.")] + [Deprecated] + public void set_hint_byte_array (string key, [CCode (array_length_cname = "len", array_length_pos = 2.1, array_length_type = "gsize")] uchar[] value); + [Deprecated] public void set_hint_double (string key, double value); - [Deprecated (since = "0.6.")] + [Deprecated] public void set_hint_int32 (string key, int value); - [Deprecated (since = "0.6.")] + [Deprecated] public void set_hint_string (string key, string value); - [Deprecated (since = "0.6.")] + [Deprecated] public void set_hint_uint32 (string key, uint value); [Deprecated] public void set_icon_from_pixbuf (Gdk.Pixbuf icon);
b3f039ae5f0b54a325cdb23f6720e5002b054cee
spring-framework
Servlet/PortletRequestDataBinder perform- unwrapping for MultipartRequest as well (SPR-7795)--
c
https://github.com/spring-projects/spring-framework
diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestDataBinder.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestDataBinder.java index 26c3a5b55fae..a63b894d17c5 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestDataBinder.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestDataBinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ import org.springframework.validation.BindException; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.multipart.MultipartRequest; +import org.springframework.web.portlet.util.PortletUtils; /** * Special {@link org.springframework.validation.DataBinder} to perform data binding @@ -105,8 +106,8 @@ public PortletRequestDataBinder(Object target, String objectName) { */ public void bind(PortletRequest request) { MutablePropertyValues mpvs = new PortletRequestParameterPropertyValues(request); - if (request instanceof MultipartRequest) { - MultipartRequest multipartRequest = (MultipartRequest) request; + MultipartRequest multipartRequest = PortletUtils.getNativeRequest(request, MultipartRequest.class); + if (multipartRequest != null) { bindMultipart(multipartRequest.getMultiFileMap(), mpvs); } doBind(mpvs); diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletWebRequest.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletWebRequest.java index 3eedfb651b60..d407f40fa9ec 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletWebRequest.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/PortletWebRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,13 +23,12 @@ import javax.portlet.PortletRequest; import javax.portlet.PortletResponse; import javax.portlet.PortletSession; -import javax.portlet.filter.PortletRequestWrapper; -import javax.portlet.filter.PortletResponseWrapper; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.portlet.util.PortletUtils; /** * {@link org.springframework.web.context.request.WebRequest} adapter @@ -79,40 +78,12 @@ public Object getNativeResponse() { @SuppressWarnings("unchecked") public <T> T getNativeRequest(Class<T> requiredType) { - if (requiredType != null) { - PortletRequest request = getRequest(); - while (request != null) { - if (requiredType.isInstance(request)) { - return (T) request; - } - else if (request instanceof PortletRequestWrapper) { - request = ((PortletRequestWrapper) request).getRequest(); - } - else { - request = null; - } - } - } - return null; + return PortletUtils.getNativeRequest(getRequest(), requiredType); } @SuppressWarnings("unchecked") public <T> T getNativeResponse(Class<T> requiredType) { - if (requiredType != null) { - PortletResponse response = getResponse(); - while (response != null) { - if (requiredType.isInstance(response)) { - return (T) response; - } - else if (response instanceof PortletResponseWrapper) { - response = ((PortletResponseWrapper) response).getResponse(); - } - else { - response = null; - } - } - } - return null; + return PortletUtils.getNativeResponse(getResponse(), requiredType); } diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/util/PortletUtils.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/util/PortletUtils.java index cd9040b1b545..968229c7538f 100644 --- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/util/PortletUtils.java +++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/util/PortletUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,9 @@ import javax.portlet.PortletSession; import javax.portlet.ResourceRequest; import javax.portlet.ResourceResponse; +import javax.portlet.PortletResponse; +import javax.portlet.filter.PortletRequestWrapper; +import javax.portlet.filter.PortletResponseWrapper; import javax.servlet.http.Cookie; import org.springframework.util.Assert; @@ -276,6 +279,48 @@ public static Object getSessionMutex(PortletSession session) { } + /** + * Return an appropriate request object of the specified type, if available, + * unwrapping the given request as far as necessary. + * @param request the portlet request to introspect + * @param requiredType the desired type of request object + * @return the matching request object, or <code>null</code> if none + * of that type is available + */ + @SuppressWarnings("unchecked") + public static <T> T getNativeRequest(PortletRequest request, Class<T> requiredType) { + if (requiredType != null) { + if (requiredType.isInstance(request)) { + return (T) request; + } + else if (request instanceof PortletRequestWrapper) { + return getNativeRequest(((PortletRequestWrapper) request).getRequest(), requiredType); + } + } + return null; + } + + /** + * Return an appropriate response object of the specified type, if available, + * unwrapping the given response as far as necessary. + * @param response the portlet response to introspect + * @param requiredType the desired type of response object + * @return the matching response object, or <code>null</code> if none + * of that type is available + */ + @SuppressWarnings("unchecked") + public static <T> T getNativeResponse(PortletResponse response, Class<T> requiredType) { + if (requiredType != null) { + if (requiredType.isInstance(response)) { + return (T) response; + } + else if (response instanceof PortletResponseWrapper) { + return getNativeResponse(((PortletResponseWrapper) response).getResponse(), requiredType); + } + } + return null; + } + /** * Expose the given Map as request attributes, using the keys as attribute names * and the values as corresponding attribute values. Keys must be Strings. @@ -293,7 +338,7 @@ public static void exposeRequestAttributes(PortletRequest request, Map<String, ? /** * Retrieve the first cookie with the given name. Note that multiple * cookies can have the same name but different paths or domains. - * @param request current servlet request + * @param request current portlet request * @param name cookie name * @return the first cookie with the given name, or <code>null</code> if none is found */ diff --git a/org.springframework.web/src/main/java/org/springframework/web/bind/ServletRequestDataBinder.java b/org.springframework.web/src/main/java/org/springframework/web/bind/ServletRequestDataBinder.java index 2edc899cfa98..f488024d9b6e 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/bind/ServletRequestDataBinder.java +++ b/org.springframework.web/src/main/java/org/springframework/web/bind/ServletRequestDataBinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import org.springframework.beans.MutablePropertyValues; import org.springframework.validation.BindException; import org.springframework.web.multipart.MultipartRequest; +import org.springframework.web.util.WebUtils; /** * Special {@link org.springframework.validation.DataBinder} to perform data binding @@ -103,8 +104,8 @@ public ServletRequestDataBinder(Object target, String objectName) { */ public void bind(ServletRequest request) { MutablePropertyValues mpvs = new ServletRequestParameterPropertyValues(request); - if (request instanceof MultipartRequest) { - MultipartRequest multipartRequest = (MultipartRequest) request; + MultipartRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartRequest.class); + if (multipartRequest != null) { bindMultipart(multipartRequest.getMultiFileMap(), mpvs); } doBind(mpvs); diff --git a/org.springframework.web/src/main/java/org/springframework/web/context/request/ServletWebRequest.java b/org.springframework.web/src/main/java/org/springframework/web/context/request/ServletWebRequest.java index 1caf21e48db4..9cb56566ed18 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/context/request/ServletWebRequest.java +++ b/org.springframework.web/src/main/java/org/springframework/web/context/request/ServletWebRequest.java @@ -20,10 +20,6 @@ import java.util.Iterator; import java.util.Locale; import java.util.Map; -import javax.servlet.ServletRequest; -import javax.servlet.ServletRequestWrapper; -import javax.servlet.ServletResponse; -import javax.servlet.ServletResponseWrapper; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @@ -31,6 +27,7 @@ import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; +import org.springframework.web.util.WebUtils; /** * {@link WebRequest} adapter for an {@link javax.servlet.http.HttpServletRequest}. @@ -92,40 +89,12 @@ public Object getNativeResponse() { @SuppressWarnings("unchecked") public <T> T getNativeRequest(Class<T> requiredType) { - if (requiredType != null) { - ServletRequest request = getRequest(); - while (request != null) { - if (requiredType.isInstance(request)) { - return (T) request; - } - else if (request instanceof ServletRequestWrapper) { - request = ((ServletRequestWrapper) request).getRequest(); - } - else { - request = null; - } - } - } - return null; + return WebUtils.getNativeRequest(getRequest(), requiredType); } @SuppressWarnings("unchecked") public <T> T getNativeResponse(Class<T> requiredType) { - if (requiredType != null) { - ServletResponse response = getResponse(); - while (response != null) { - if (requiredType.isInstance(response)) { - return (T) response; - } - else if (response instanceof ServletResponseWrapper) { - response = ((ServletResponseWrapper) response).getResponse(); - } - else { - response = null; - } - } - } - return null; + return WebUtils.getNativeResponse(getResponse(), requiredType); } diff --git a/org.springframework.web/src/main/java/org/springframework/web/util/WebUtils.java b/org.springframework.web/src/main/java/org/springframework/web/util/WebUtils.java index c11df93a05f0..8e19d7092668 100644 --- a/org.springframework.web/src/main/java/org/springframework/web/util/WebUtils.java +++ b/org.springframework.web/src/main/java/org/springframework/web/util/WebUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,9 @@ import java.util.TreeMap; import javax.servlet.ServletContext; import javax.servlet.ServletRequest; +import javax.servlet.ServletRequestWrapper; +import javax.servlet.ServletResponse; +import javax.servlet.ServletResponseWrapper; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -366,6 +369,48 @@ public static Object getSessionMutex(HttpSession session) { } + /** + * Return an appropriate request object of the specified type, if available, + * unwrapping the given request as far as necessary. + * @param request the servlet request to introspect + * @param requiredType the desired type of request object + * @return the matching request object, or <code>null</code> if none + * of that type is available + */ + @SuppressWarnings("unchecked") + public static <T> T getNativeRequest(ServletRequest request, Class<T> requiredType) { + if (requiredType != null) { + if (requiredType.isInstance(request)) { + return (T) request; + } + else if (request instanceof ServletRequestWrapper) { + return getNativeRequest(((ServletRequestWrapper) request).getRequest(), requiredType); + } + } + return null; + } + + /** + * Return an appropriate response object of the specified type, if available, + * unwrapping the given response as far as necessary. + * @param response the servlet response to introspect + * @param requiredType the desired type of response object + * @return the matching response object, or <code>null</code> if none + * of that type is available + */ + @SuppressWarnings("unchecked") + public static <T> T getNativeResponse(ServletResponse response, Class<T> requiredType) { + if (requiredType != null) { + if (requiredType.isInstance(response)) { + return (T) response; + } + else if (response instanceof ServletResponseWrapper) { + return getNativeResponse(((ServletResponseWrapper) response).getResponse(), requiredType); + } + } + return null; + } + /** * Determine whether the given request is an include request, * that is, not a top-level HTTP request coming in from the outside.
98ca257ae6255edb10a2f75c4a3f26240baee2b3
dustin$java-memcached-client
SPY-128: Adding support for CAS Delete. This changeset uses the functionality that was already there and just exposes it to the outside. It is now possible to use delete with CAS if needed. Change-Id: I72652587424297b3373bf4914a5c54799ebd6179 Reviewed-on: http://review.couchbase.org/27107 Reviewed-by: Matt Ingenthron <[email protected]> Tested-by: Michael Nitschinger <[email protected]>
p
https://github.com/dustin/java-memcached-client
diff --git a/src/main/java/net/spy/memcached/MemcachedClient.java b/src/main/java/net/spy/memcached/MemcachedClient.java index 02acce6be..627e571b1 100644 --- a/src/main/java/net/spy/memcached/MemcachedClient.java +++ b/src/main/java/net/spy/memcached/MemcachedClient.java @@ -1986,10 +1986,24 @@ public OperationFuture<Boolean> delete(String key, int hold) { * full to accept any more requests */ public OperationFuture<Boolean> delete(String key) { + return delete(key, (long) 0); + } + + /** + * Delete the given key from the cache of the given CAS value applies. + * + * @param key the key to delete + * @param cas the CAS value to apply. + * @return whether or not the operation was performed + * @throws IllegalStateException in the rare circumstance where queue is too + * full to accept any more requests + */ + public OperationFuture<Boolean> delete(String key, long cas) { final CountDownLatch latch = new CountDownLatch(1); final OperationFuture<Boolean> rv = new OperationFuture<Boolean>(key, latch, operationTimeout); - DeleteOperation op = opFact.delete(key, new DeleteOperation.Callback() { + + DeleteOperation.Callback callback = new DeleteOperation.Callback() { public void receivedStatus(OperationStatus s) { rv.set(s.isSuccess(), s); } @@ -2001,7 +2015,15 @@ public void gotData(long cas) { public void complete() { latch.countDown(); } - }); + }; + + DeleteOperation op = null; + if(cas == 0) { + op = opFact.delete(key, callback); + } else { + op = opFact.delete(key, cas, callback); + } + rv.setOperation(op); mconn.enqueueOperation(key, op); return rv; diff --git a/src/main/java/net/spy/memcached/MemcachedClientIF.java b/src/main/java/net/spy/memcached/MemcachedClientIF.java index 785cde6ca..a8078b0a6 100644 --- a/src/main/java/net/spy/memcached/MemcachedClientIF.java +++ b/src/main/java/net/spy/memcached/MemcachedClientIF.java @@ -187,6 +187,8 @@ <T> Future<Boolean> touch(final String key, final int exp, Future<Boolean> delete(String key); + Future<Boolean> delete(String key, long cas); + Future<Boolean> flush(int delay); Future<Boolean> flush(); diff --git a/src/main/java/net/spy/memcached/OperationFactory.java b/src/main/java/net/spy/memcached/OperationFactory.java index 7546590e9..f637a29e2 100644 --- a/src/main/java/net/spy/memcached/OperationFactory.java +++ b/src/main/java/net/spy/memcached/OperationFactory.java @@ -78,6 +78,17 @@ public interface OperationFactory { */ DeleteOperation delete(String key, DeleteOperation.Callback callback); + /** + * Create a deletion operation with CAS. + * + * @param key the key to delete + * @param cas the CAS value to pass along + * @param callback the status callback + * @return the new DeleteOperation + */ + DeleteOperation delete(String key, long cas, + DeleteOperation.Callback callback); + /** * Create a Unlock operation. * diff --git a/src/main/java/net/spy/memcached/protocol/ascii/AsciiOperationFactory.java b/src/main/java/net/spy/memcached/protocol/ascii/AsciiOperationFactory.java index 2adacb365..f491c58ef 100644 --- a/src/main/java/net/spy/memcached/protocol/ascii/AsciiOperationFactory.java +++ b/src/main/java/net/spy/memcached/protocol/ascii/AsciiOperationFactory.java @@ -69,6 +69,12 @@ public DeleteOperation delete(String key, DeleteOperation.Callback cb) { return new DeleteOperationImpl(key, cb); } + public DeleteOperation delete(String key, long cas, + DeleteOperation.Callback cb) { + throw new UnsupportedOperationException("Delete with CAS is not supported " + + "for ASCII protocol"); + } + public FlushOperation flush(int delay, OperationCallback cb) { return new FlushOperationImpl(delay, cb); } diff --git a/src/main/java/net/spy/memcached/protocol/binary/BinaryOperationFactory.java b/src/main/java/net/spy/memcached/protocol/binary/BinaryOperationFactory.java index 9e08f9b3e..6340d8521 100644 --- a/src/main/java/net/spy/memcached/protocol/binary/BinaryOperationFactory.java +++ b/src/main/java/net/spy/memcached/protocol/binary/BinaryOperationFactory.java @@ -71,6 +71,11 @@ public class BinaryOperationFactory extends BaseOperationFactory { return new DeleteOperationImpl(key, operationCallback); } + public DeleteOperation delete(String key, long cas, + DeleteOperation.Callback operationCallback) { + return new DeleteOperationImpl(key, cas, operationCallback); + } + public UnlockOperation unlock(String key, long casId, OperationCallback cb) { return new UnlockOperationImpl(key, casId, cb); diff --git a/src/test/java/net/spy/memcached/BinaryClientTest.java b/src/test/java/net/spy/memcached/BinaryClientTest.java index ef1353c66..a71660887 100644 --- a/src/test/java/net/spy/memcached/BinaryClientTest.java +++ b/src/test/java/net/spy/memcached/BinaryClientTest.java @@ -55,6 +55,18 @@ protected String getExpectedVersionSource() { TestConfig.PORT_NUMBER)); } + public void testDeleteWithCAS() throws Exception { + final String key = "delete.with.cas"; + final long wrongCAS = 1234; + + OperationFuture<Boolean> setFuture = client.set(key, 0, "test"); + assertTrue(setFuture.get()); + + assertFalse(client.delete(key, wrongCAS).get()); + assertTrue(client.delete(key, setFuture.getCas()).get()); + assertNull(client.get(key)); + } + public void testCASAppendFail() throws Exception { final String key = "append.key"; assertTrue(client.set(key, 5, "test").get());
b27c2ddcb46bed712c13cc5eb90b968652964d43
restlet-framework-java
Added support of the dataservices extension in- Android.--
a
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet.ext.xml/src/org/restlet/ext/xml/SaxRepresentation.java.android b/modules/org.restlet.ext.xml/src/org/restlet/ext/xml/SaxRepresentation.java.android index 3f52fdd911..c19939f9b9 100644 --- a/modules/org.restlet.ext.xml/src/org/restlet/ext/xml/SaxRepresentation.java.android +++ b/modules/org.restlet.ext.xml/src/org/restlet/ext/xml/SaxRepresentation.java.android @@ -38,7 +38,6 @@ import javax.xml.parsers.SAXParserFactory; import org.restlet.data.MediaType; import org.restlet.representation.Representation; -import org.w3c.dom.Document; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; @@ -101,6 +100,10 @@ public class SaxRepresentation extends XmlRepresentation { this.source = new InputSource(xmlRepresentation.getStream()); } + if (xmlRepresentation.getCharacterSet()!= null) { + this.source.setEncoding(xmlRepresentation.getCharacterSet().getName()); + } + if (xmlRepresentation.getIdentifier() != null) { this.source.setSystemId(xmlRepresentation.getIdentifier() .getTargetRef().toString()); diff --git a/modules/org.restlet.ext.xml/src/org/restlet/ext/xml/XmlRepresentation.java b/modules/org.restlet.ext.xml/src/org/restlet/ext/xml/XmlRepresentation.java index a2a29f226a..da0cb51ac7 100644 --- a/modules/org.restlet.ext.xml/src/org/restlet/ext/xml/XmlRepresentation.java +++ b/modules/org.restlet.ext.xml/src/org/restlet/ext/xml/XmlRepresentation.java @@ -68,6 +68,62 @@ public abstract class XmlRepresentation extends OutputRepresentation // [enddef] { + + // [ifdef android] method + /** + * Appends the text content of a given node and its descendants to the given + * buffer. + * + * @param node + * The node. + * @param sb + * The buffer. + */ + private static void appendTextContent(Node node, StringBuilder sb) { + switch (node.getNodeType()) { + case Node.TEXT_NODE: + sb.append(node.getNodeValue()); + break; + case Node.CDATA_SECTION_NODE: + sb.append(node.getNodeValue()); + break; + case Node.COMMENT_NODE: + sb.append(node.getNodeValue()); + break; + case Node.PROCESSING_INSTRUCTION_NODE: + sb.append(node.getNodeValue()); + break; + case Node.ENTITY_REFERENCE_NODE: + if (node.getNodeName().startsWith("#")) { + int ch = Integer.parseInt(node.getNodeName().substring(1)); + sb.append((char) ch); + } + break; + case Node.ELEMENT_NODE: + for (int i = 0; i < node.getChildNodes().getLength(); i++) { + appendTextContent(node.getChildNodes().item(i), sb); + } + break; + case Node.ATTRIBUTE_NODE: + for (int i = 0; i < node.getChildNodes().getLength(); i++) { + appendTextContent(node.getChildNodes().item(i), sb); + } + break; + case Node.ENTITY_NODE: + for (int i = 0; i < node.getChildNodes().getLength(); i++) { + appendTextContent(node.getChildNodes().item(i), sb); + } + break; + case Node.DOCUMENT_FRAGMENT_NODE: + for (int i = 0; i < node.getChildNodes().getLength(); i++) { + appendTextContent(node.getChildNodes().item(i), sb); + } + break; + default: + break; + } + } + // [ifndef android] method /** * Returns a SAX source. @@ -141,6 +197,20 @@ private static String getSchemaLanguageUri( return result; } + // [ifdef android] method + /** + * Returns the text content of a given node and its descendants. + * + * @param node + * The node. + * @return The text content of a given node. + */ + public static String getTextContent(Node node) { + StringBuilder sb = new StringBuilder(); + appendTextContent(node, sb); + return sb.toString(); + } + /** * A SAX {@link EntityResolver} to use when resolving external entity * references while parsing this type of XML representations. @@ -578,6 +648,19 @@ public void setNamespaceAware(boolean namespaceAware) { this.namespaceAware = namespaceAware; } + // [ifndef android] method + /** + * Set a (compiled) {@link javax.xml.validation.Schema} to use when parsing + * and validating this type of XML representations. + * + * @param schema + * The (compiled) {@link javax.xml.validation.Schema} object to + * set. + */ + public void setSchema(javax.xml.validation.Schema schema) { + this.schema = schema; + } + // [ifndef android] method /** * Set a schema representation to be compiled and used when parsing and @@ -595,19 +678,6 @@ public void setSchema(Representation schemaRepresentation) { } } - // [ifndef android] method - /** - * Set a (compiled) {@link javax.xml.validation.Schema} to use when parsing - * and validating this type of XML representations. - * - * @param schema - * The (compiled) {@link javax.xml.validation.Schema} object to - * set. - */ - public void setSchema(javax.xml.validation.Schema schema) { - this.schema = schema; - } - /** * Indicates the desire for validating this type of XML representations * against an XML schema if one is referenced within the contents. @@ -634,50 +704,50 @@ public void setXIncludeAware(boolean includeAware) { /** * Validates the XML representation against a given schema. * - * @param schemaRepresentation - * The XML schema representation to use. + * @param schema + * The XML schema to use. */ - public void validate(Representation schemaRepresentation) throws Exception { - validate(schemaRepresentation, null); + public void validate(javax.xml.validation.Schema schema) throws Exception { + validate(schema, null); } // [ifndef android] method /** * Validates the XML representation against a given schema. * - * @param schemaRepresentation - * The XML schema representation to use. + * @param schema + * The XML schema to use. * @param result * The Result object that receives (possibly augmented) XML. */ - public void validate(Representation schemaRepresentation, + public void validate(javax.xml.validation.Schema schema, javax.xml.transform.Result result) throws Exception { - validate(getSchema(schemaRepresentation), result); + schema.newValidator().validate(getSaxSource(), result); } // [ifndef android] method /** * Validates the XML representation against a given schema. * - * @param schema - * The XML schema to use. + * @param schemaRepresentation + * The XML schema representation to use. */ - public void validate(javax.xml.validation.Schema schema) throws Exception { - validate(schema, null); + public void validate(Representation schemaRepresentation) throws Exception { + validate(schemaRepresentation, null); } // [ifndef android] method /** * Validates the XML representation against a given schema. * - * @param schema - * The XML schema to use. + * @param schemaRepresentation + * The XML schema representation to use. * @param result * The Result object that receives (possibly augmented) XML. */ - public void validate(javax.xml.validation.Schema schema, + public void validate(Representation schemaRepresentation, javax.xml.transform.Result result) throws Exception { - schema.newValidator().validate(getSaxSource(), result); + validate(getSchema(schemaRepresentation), result); } }
0613ea4287dc6744bc75ebd857b5bcb24331c0a1
Valadoc
libvaladoc: Accept error codes in @throws
a
https://github.com/GNOME/vala/
diff --git a/src/libvaladoc/taglets/tagletthrows.vala b/src/libvaladoc/taglets/tagletthrows.vala index 6bc51e64ee..2ba7fa0ce5 100644 --- a/src/libvaladoc/taglets/tagletthrows.vala +++ b/src/libvaladoc/taglets/tagletthrows.vala @@ -25,7 +25,13 @@ using Gee; using Valadoc.Content; public class Valadoc.Taglets.Throws : InlineContent, Taglet, Block { + // TODO: rename public string error_domain_name { private set; get; } + + /** + * Thrown Error domain or Error code + */ + // TODO: rename public Api.Node error_domain { private set; get; } public Rule? get_parser_rule (Rule run_rule) { @@ -55,11 +61,12 @@ public class Valadoc.Taglets.Throws : InlineContent, Taglet, Block { } - // Check if the method is allowed to throw the given type: + // Check if the method is allowed to throw the given type or error code: Gee.List<Api.Node> exceptions = container.get_children_by_types ({Api.NodeType.ERROR_DOMAIN, Api.NodeType.CLASS}, false); + Api.Item expected_error_domain = (error_domain is Api.ErrorCode)? error_domain.parent : error_domain; bool report_warning = true; foreach (Api.Node exception in exceptions) { - if (exception == error_domain || exception is Api.Class) { + if (exception == expected_error_domain || (exception is Api.Class && expected_error_domain is Api.ErrorDomain)) { report_warning = false; break; }
617235b95357c5cfaf06710401d98eaee9572e6a
hbase
HBASE-10686 [WINDOWS] TestStripeStoreFileManager- fails on windows--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1575011 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestStripeStoreFileManager.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestStripeStoreFileManager.java index 0fdf5d8201ab..664653ff1760 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestStripeStoreFileManager.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestStripeStoreFileManager.java @@ -18,6 +18,13 @@ */ package org.apache.hadoop.hbase.regionserver; +import static org.apache.hadoop.hbase.regionserver.StripeStoreFileManager.OPEN_KEY; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -26,9 +33,6 @@ import java.util.Iterator; import java.util.List; -import static org.junit.Assert.*; -import static org.apache.hadoop.hbase.regionserver.StripeStoreFileManager.OPEN_KEY; - import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; @@ -551,7 +555,7 @@ private static MockStoreFile createFile( long size, long seqNum, byte[] startKey, byte[] endKey) throws Exception { FileSystem fs = TEST_UTIL.getTestFileSystem(); Path testFilePath = StoreFile.getUniqueFile(fs, CFDIR); - fs.create(testFilePath); + fs.create(testFilePath).close(); MockStoreFile sf = new MockStoreFile(TEST_UTIL, testFilePath, size, 0, false, seqNum); if (startKey != null) { sf.setMetadataValue(StripeStoreFileManager.STRIPE_START_KEY, startKey);
2ca1f557dc3220a047c5ee6a1d8c1a0584f6ca4e
orientdb
Fix by Luca Molino to close issue 619--
c
https://github.com/orientechnologies/orientdb
diff --git a/commons/src/main/java/com/orientechnologies/common/console/TTYConsoleReader.java b/commons/src/main/java/com/orientechnologies/common/console/TTYConsoleReader.java index 59339861f7e..1701bf54d79 100644 --- a/commons/src/main/java/com/orientechnologies/common/console/TTYConsoleReader.java +++ b/commons/src/main/java/com/orientechnologies/common/console/TTYConsoleReader.java @@ -70,7 +70,7 @@ public TTYConsoleReader() { } if (System.getProperty("file.encoding") != null) { inStream = new InputStreamReader(System.in, System.getProperty("file.encoding")); - outStream = new PrintStream(System.out, true, System.getProperty("file.encoding")); + outStream = new PrintStream(System.out, false, System.getProperty("file.encoding")); } else { inStream = new InputStreamReader(System.in); outStream = System.out; @@ -93,7 +93,6 @@ public String readLine() { int historyNum = history.size(); boolean hintedHistory = false; while (true) { - boolean escape = false; boolean ctrl = false; int next = inStream.read(); @@ -260,7 +259,7 @@ public String readLine() { rewriteConsole(buffer, false); currentPos = buffer.length(); } else { - if (next > UNIT_SEPARATOR_CHAR && next < BACKSPACE_CHAR) { + if ((next > UNIT_SEPARATOR_CHAR && next < BACKSPACE_CHAR) || next > BACKSPACE_CHAR) { StringBuffer cleaner = new StringBuffer(); for (int i = 0; i < buffer.length(); i++) { cleaner.append(" ");
2a590b78e4c9e814faa61457a04ec4f5f2c9a176
orientdb
Distributed: fixed issue -2008 on deploying- database--
c
https://github.com/orientechnologies/orientdb
diff --git a/distributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastDistributedDatabase.java b/distributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastDistributedDatabase.java index 693ea430372..756b5bf021b 100644 --- a/distributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastDistributedDatabase.java +++ b/distributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastDistributedDatabase.java @@ -23,7 +23,6 @@ import com.orientechnologies.orient.core.db.OScenarioThreadLocal; import com.orientechnologies.orient.core.db.OScenarioThreadLocal.RUN_MODE; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; -import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.server.config.OServerUserConfiguration; import com.orientechnologies.orient.server.distributed.*; import com.orientechnologies.orient.server.distributed.ODistributedRequest.EXECUTION_MODE; @@ -533,9 +532,7 @@ protected void checkLocalNodeInConfiguration() { } if (dirty) { - final ODocument doc = cfg.serialize(); - manager.updateCachedDatabaseConfiguration(databaseName, doc); - manager.getConfigurationMap().put(OHazelcastPlugin.CONFIG_DATABASE_PREFIX + databaseName, doc); + manager.updateCachedDatabaseConfiguration(databaseName, cfg.serialize(), true, true); } } @@ -573,9 +570,7 @@ protected void removeNodeInConfiguration(final String iNode, final boolean iForc } if (dirty) { - final ODocument doc = cfg.serialize(); - manager.updateCachedDatabaseConfiguration(databaseName, doc); - manager.getConfigurationMap().put(OHazelcastPlugin.CONFIG_DATABASE_PREFIX + databaseName, doc); + manager.updateCachedDatabaseConfiguration(databaseName, cfg.serialize(), true, true); } } diff --git a/distributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastPlugin.java b/distributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastPlugin.java index e6d399d7a38..39964738933 100755 --- a/distributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastPlugin.java +++ b/distributed/src/main/java/com/orientechnologies/orient/server/hazelcast/OHazelcastPlugin.java @@ -470,7 +470,7 @@ public void entryAdded(EntryEvent<String, Object> iEvent) { } } else if (key.startsWith(CONFIG_DATABASE_PREFIX)) { - saveDatabaseConfiguration(key.substring(CONFIG_DATABASE_PREFIX.length()), (ODocument) iEvent.getValue()); + updateCachedDatabaseConfiguration(key.substring(CONFIG_DATABASE_PREFIX.length()), (ODocument) iEvent.getValue(), true, false); OClientConnectionManager.instance().pushDistribCfg2Clients(getClusterConfiguration()); } } @@ -493,7 +493,7 @@ public void entryUpdated(EntryEvent<String, Object> iEvent) { getNodeName(iEvent.getMember())); installNewDatabases(false); - saveDatabaseConfiguration(dbName, (ODocument) iEvent.getValue()); + updateCachedDatabaseConfiguration(dbName, (ODocument) iEvent.getValue(), true, false); OClientConnectionManager.instance().pushDistribCfg2Clients(getClusterConfiguration()); } } @@ -671,15 +671,20 @@ protected void installNewDatabases(final boolean iStartup) { ODistributedDatabaseChunk chunk = (ODistributedDatabaseChunk) value; final String fileName = System.getProperty("java.io.tmpdir") + "/orientdb/install_" + databaseName + ".zip"; + + ODistributedServerLog.warn(this, getLocalNodeName(), r.getKey(), DIRECTION.NONE, + "copying remote database '%s' to: %s", databaseName, fileName); + final File file = new File(fileName); if (file.exists()) file.delete(); + FileOutputStream out = null; try { - final FileOutputStream out = new FileOutputStream(fileName, false); + out = new FileOutputStream(fileName, false); - out.write(chunk.buffer); - for (int chunkNum = 1; !chunk.last; chunkNum++) { + long fileSize = writeDatabaseChunk(1, chunk, out); + for (int chunkNum = 2; !chunk.last; chunkNum++) { distrDatabase.setWaitForTaskType(OCopyDatabaseChunkTask.class); final Map<String, Object> result = (Map<String, Object>) sendRequest(databaseName, null, @@ -691,14 +696,25 @@ protected void installNewDatabases(final boolean iStartup) { continue; else { chunk = (ODistributedDatabaseChunk) res.getValue(); - out.write(chunk.buffer); + fileSize += writeDatabaseChunk(chunkNum, chunk, out); } } } + ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE, + "database copied correctly, size=%s", OFileUtils.getSizeAsString(fileSize)); + } catch (Exception e) { ODistributedServerLog.error(this, getLocalNodeName(), null, DIRECTION.NONE, "error on transferring database '%s' to '%s'", e, databaseName, fileName); + } finally { + try { + if (out != null) { + out.flush(); + out.close(); + } + } catch (IOException e) { + } } installDatabase(distrDatabase, databaseName, dbPath, r.getKey(), fileName); @@ -720,29 +736,51 @@ protected void installNewDatabases(final boolean iStartup) { } } - private void installDatabase(final OHazelcastDistributedDatabase distrDatabase, final String databaseName, final String dbPath, + public void updateCachedDatabaseConfiguration(String iDatabaseName, ODocument cfg, boolean iSaveToDisk, boolean iDeployToCluster) { + super.updateCachedDatabaseConfiguration(iDatabaseName, cfg, iSaveToDisk); + + if (iDeployToCluster) + // DEPLOY THE CONFIGURATION TO THE CLUSTER + getConfigurationMap().put(OHazelcastPlugin.CONFIG_DATABASE_PREFIX + iDatabaseName, cfg); + } + + protected long writeDatabaseChunk(final int iChunkId, final ODistributedDatabaseChunk chunk, final FileOutputStream out) + throws IOException { + + ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE, "- writing chunk #%d offset=%d size=%s", iChunkId, + chunk.offset, OFileUtils.getSizeAsString(chunk.buffer.length)); + out.write(chunk.buffer); + + return chunk.buffer.length; + } + + protected void installDatabase(final OHazelcastDistributedDatabase distrDatabase, final String databaseName, final String dbPath, final String iNode, final String iDatabaseCompressedFile) { - ODistributedServerLog.warn(this, getLocalNodeName(), iNode, DIRECTION.IN, "installing database %s in %s...", databaseName, + ODistributedServerLog.warn(this, getLocalNodeName(), iNode, DIRECTION.IN, "installing database '%s' to: %s...", databaseName, dbPath); try { - final FileInputStream in = new FileInputStream(iDatabaseCompressedFile); + File f = new File(iDatabaseCompressedFile); new File(dbPath).mkdirs(); final ODatabaseDocumentTx db = new ODatabaseDocumentTx("local:" + dbPath); - db.restore(in, null, null); - in.close(); + final FileInputStream in = new FileInputStream(f); + try { + db.restore(in, null, null); + } finally { + in.close(); + } db.close(); Orient.instance().unregisterStorageByName(db.getName()); - ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE, - "installed database %s in %s, setting it online...", databaseName, dbPath); + ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE, "installed database '%s', setting it online...", + databaseName); distrDatabase.setOnline(); - ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE, "database %s is online", databaseName); + ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.NONE, "database '%s' is online", databaseName); } catch (IOException e) { ODistributedServerLog.warn(this, getLocalNodeName(), null, DIRECTION.IN, "error on copying database '%s' on local server", e, @@ -759,7 +797,7 @@ protected ODocument loadDatabaseConfiguration(final String iDatabaseName, final ODistributedServerLog.info(this, getLocalNodeName(), null, DIRECTION.NONE, "loaded database configuration from active cluster"); - updateCachedDatabaseConfiguration(iDatabaseName, cfg); + updateCachedDatabaseConfiguration(iDatabaseName, cfg, false, false); return cfg; } } diff --git a/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedAbstractPlugin.java b/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedAbstractPlugin.java index 3c3b2797e7b..4282649d130 100755 --- a/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedAbstractPlugin.java +++ b/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedAbstractPlugin.java @@ -15,14 +15,6 @@ */ package com.orientechnologies.orient.server.distributed; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.common.parser.OSystemVariableResolver; import com.orientechnologies.orient.core.Orient; @@ -38,6 +30,14 @@ import com.orientechnologies.orient.server.distributed.conflict.OReplicationConflictResolver; import com.orientechnologies.orient.server.plugin.OServerPluginAbstract; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + /** * Abstract plugin to manage the distributed environment. * @@ -197,7 +197,7 @@ protected ODocument loadDatabaseConfiguration(final String iDatabaseName, final f.read(buffer); final ODocument doc = (ODocument) new ODocument().fromJSON(new String(buffer), "noMap"); - updateCachedDatabaseConfiguration(iDatabaseName, doc); + updateCachedDatabaseConfiguration(iDatabaseName, doc, false); return doc; } catch (Exception e) { @@ -211,12 +211,51 @@ protected ODocument loadDatabaseConfiguration(final String iDatabaseName, final return null; } - public void updateCachedDatabaseConfiguration(final String iDatabaseName, final ODocument cfg) { + public void updateCachedDatabaseConfiguration(final String iDatabaseName, final ODocument cfg, final boolean iSaveToDisk) { synchronized (cachedDatabaseConfiguration) { + final ODocument oldCfg = cachedDatabaseConfiguration.get(iDatabaseName); + if (oldCfg != null && (oldCfg == cfg || Arrays.equals(oldCfg.toStream(), cfg.toStream()))) + // NO CHANGE, SKIP IT + return; + + // INCREMENT VERSION + Integer oldVersion = cfg.field("version"); + if (oldVersion == null) + oldVersion = 0; + cfg.field("version", oldVersion.intValue() + 1); + + // SAVE IN NODE'S LOCAL RAM cachedDatabaseConfiguration.put(iDatabaseName, cfg); + // PRINT THE NEW CONFIGURATION OLogManager.instance().info(this, "updated distributed configuration for database: %s:\n----------\n%s\n----------", iDatabaseName, cfg.toJSON("prettyPrint")); + + if (iSaveToDisk) { + // SAVE THE CONFIGURATION TO DISK + FileOutputStream f = null; + try { + File file = getDistributedConfigFile(iDatabaseName); + + OLogManager.instance().info(this, "Saving distributed configuration file for database '%s' to: %s", iDatabaseName, file); + + if (!file.exists()) + file.createNewFile(); + + f = new FileOutputStream(file); + f.write(cfg.toJSON().getBytes()); + f.flush(); + } catch (Exception e) { + OLogManager.instance().error(this, "Error on saving distributed configuration file", e); + + } finally { + if (f != null) + try { + f.close(); + } catch (IOException e) { + } + } + } } } @@ -235,42 +274,6 @@ public ODistributedConfiguration getDatabaseConfiguration(final String iDatabase } } - protected void saveDatabaseConfiguration(final String iDatabaseName, final ODocument cfg) { - synchronized (cachedDatabaseConfiguration) { - final ODocument oldCfg = cachedDatabaseConfiguration.get(iDatabaseName); - if (oldCfg != null && Arrays.equals(oldCfg.toStream(), cfg.toStream())) - // NO CHANGE, SKIP IT - return; - } - - // INCREMENT VERSION - Integer oldVersion = cfg.field("version"); - if (oldVersion == null) - oldVersion = 0; - cfg.field("version", oldVersion.intValue() + 1); - - updateCachedDatabaseConfiguration(iDatabaseName, cfg); - - FileOutputStream f = null; - try { - File file = getDistributedConfigFile(iDatabaseName); - - OLogManager.instance().config(this, "Saving distributed configuration file for database '%s' in: %s", iDatabaseName, file); - - f = new FileOutputStream(file); - f.write(cfg.toJSON().getBytes()); - } catch (Exception e) { - OLogManager.instance().error(this, "Error on saving distributed configuration file", e); - - } finally { - if (f != null) - try { - f.close(); - } catch (IOException e) { - } - } - } - public File getDistributedConfigFile(final String iDatabaseName) { return new File(serverInstance.getDatabaseDirectory() + iDatabaseName + "/" + FILE_DISTRIBUTED_DB_CONFIG); } diff --git a/server/src/main/java/com/orientechnologies/orient/server/distributed/task/ODeployDatabaseTask.java b/server/src/main/java/com/orientechnologies/orient/server/distributed/task/ODeployDatabaseTask.java index 99ead1c84eb..13b9c886960 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/distributed/task/ODeployDatabaseTask.java +++ b/server/src/main/java/com/orientechnologies/orient/server/distributed/task/ODeployDatabaseTask.java @@ -60,18 +60,28 @@ public Object execute(final OServer iServer, ODistributedServerManager iManager, ODistributedServerLog.warn(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.OUT, "deploying database %s...", databaseName); - final File f = new File(BACKUP_DIRECTORY + "/" + database.getName()); + final File f = new File(BACKUP_DIRECTORY + "/backup_" + database.getName() + ".zip"); if (f.exists()) f.delete(); + else + f.getParentFile().mkdirs(); f.createNewFile(); + ODistributedServerLog.warn(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.OUT, + "creating backup of database '%s' in directory: %s...", databaseName, f.getAbsolutePath()); + database.backup(new FileOutputStream(f), null, null); ODistributedServerLog.warn(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.OUT, "sending the compressed database '%s' over the network to node '%s', size=%s...", databaseName, getNodeSource(), OFileUtils.getSizeAsString(f.length())); - return new ODistributedDatabaseChunk(f, 0, CHUNK_MAX_SIZE); + final ODistributedDatabaseChunk chunk = new ODistributedDatabaseChunk(f, 0, CHUNK_MAX_SIZE); + + ODistributedServerLog.warn(this, iManager.getLocalNodeName(), getNodeSource(), ODistributedServerLog.DIRECTION.OUT, + "- transferring chunk #%d offset=%d size=%s...", 1, 0, OFileUtils.getSizeAsNumber(chunk.buffer.length)); + + return chunk; } finally { lock.unlock();
8b9fdf23e2196dce9c956ba9088dd9b3146be60c
camel
CAMEL-4244 Add ThreadPoolProfileBuilder and- change ThreadPoolFactory to use the ThreadPoolProfile--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1159342 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/builder/ThreadPoolProfileBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/ThreadPoolProfileBuilder.java new file mode 100644 index 0000000000000..8f3af7e1d17d9 --- /dev/null +++ b/camel-core/src/main/java/org/apache/camel/builder/ThreadPoolProfileBuilder.java @@ -0,0 +1,86 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.builder; + +import java.util.concurrent.TimeUnit; + +import org.apache.camel.ThreadPoolRejectedPolicy; +import org.apache.camel.spi.ThreadPoolProfile; + +public class ThreadPoolProfileBuilder { + private final ThreadPoolProfile profile; + + public ThreadPoolProfileBuilder(String id) { + this.profile = new ThreadPoolProfile(id); + } + + public ThreadPoolProfileBuilder(String id, ThreadPoolProfile origProfile) { + this.profile = origProfile.clone(); + this.profile.setId(id); + } + + public ThreadPoolProfileBuilder defaultProfile(Boolean defaultProfile) { + this.profile.setDefaultProfile(defaultProfile); + return this; + } + + + public ThreadPoolProfileBuilder poolSize(Integer poolSize) { + profile.setPoolSize(poolSize); + return this; + } + + public ThreadPoolProfileBuilder maxPoolSize(Integer maxPoolSize) { + profile.setMaxPoolSize(maxPoolSize); + return this; + } + + public ThreadPoolProfileBuilder keepAliveTime(Long keepAliveTime, TimeUnit timeUnit) { + profile.setKeepAliveTime(keepAliveTime); + profile.setTimeUnit(timeUnit); + return this; + } + + public ThreadPoolProfileBuilder keepAliveTime(Long keepAliveTime) { + profile.setKeepAliveTime(keepAliveTime); + return this; + } + + public ThreadPoolProfileBuilder maxQueueSize(Integer maxQueueSize) { + if (maxQueueSize != null) { + profile.setMaxQueueSize(maxQueueSize); + } + return this; + } + + public ThreadPoolProfileBuilder rejectedPolicy(ThreadPoolRejectedPolicy rejectedPolicy) { + profile.setRejectedPolicy(rejectedPolicy); + return this; + } + + /** + * Builds the new thread pool + * + * @return the created thread pool + * @throws Exception is thrown if error building the thread pool + */ + public ThreadPoolProfile build() { + return profile; + } + + +} diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultExecutorServiceManager.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultExecutorServiceManager.java index fe2f4e0907ff4..f874a7b6360c4 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultExecutorServiceManager.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultExecutorServiceManager.java @@ -22,7 +22,6 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; -import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; @@ -30,6 +29,7 @@ import org.apache.camel.CamelContext; import org.apache.camel.ThreadPoolRejectedPolicy; +import org.apache.camel.builder.ThreadPoolProfileBuilder; import org.apache.camel.model.OptionalIdentifiedDefinition; import org.apache.camel.model.ProcessorDefinition; import org.apache.camel.model.ProcessorDefinitionHelper; @@ -56,21 +56,20 @@ public class DefaultExecutorServiceManager extends ServiceSupport implements Exe private String threadNamePattern; private String defaultThreadPoolProfileId = "defaultThreadPoolProfile"; private final Map<String, ThreadPoolProfile> threadPoolProfiles = new HashMap<String, ThreadPoolProfile>(); + private ThreadPoolProfile builtIndefaultProfile; public DefaultExecutorServiceManager(CamelContext camelContext) { this.camelContext = camelContext; - // create and register the default profile - ThreadPoolProfile defaultProfile = new ThreadPoolProfile(defaultThreadPoolProfileId); - // the default profile has the following values - defaultProfile.setDefaultProfile(true); - defaultProfile.setPoolSize(10); - defaultProfile.setMaxPoolSize(20); - defaultProfile.setKeepAliveTime(60L); - defaultProfile.setTimeUnit(TimeUnit.SECONDS); - defaultProfile.setMaxQueueSize(1000); - defaultProfile.setRejectedPolicy(ThreadPoolRejectedPolicy.CallerRuns); - registerThreadPoolProfile(defaultProfile); + builtIndefaultProfile = new ThreadPoolProfileBuilder(defaultThreadPoolProfileId) + .defaultProfile(true) + .poolSize(10) + .maxPoolSize(20) + .keepAliveTime(60L, TimeUnit.SECONDS) + .maxQueueSize(1000) + .rejectedPolicy(ThreadPoolRejectedPolicy.CallerRuns) + .build(); + registerThreadPoolProfile(builtIndefaultProfile); } @Override @@ -102,46 +101,12 @@ public ThreadPoolProfile getDefaultThreadPoolProfile() { @Override public void setDefaultThreadPoolProfile(ThreadPoolProfile defaultThreadPoolProfile) { - ThreadPoolProfile oldProfile = threadPoolProfiles.remove(defaultThreadPoolProfileId); - if (oldProfile != null) { - // the old is no longer default - oldProfile.setDefaultProfile(false); - - // fallback and use old default values for new default profile if absent (convention over configuration) - if (defaultThreadPoolProfile.getKeepAliveTime() == null) { - defaultThreadPoolProfile.setKeepAliveTime(oldProfile.getKeepAliveTime()); - } - if (defaultThreadPoolProfile.getMaxPoolSize() == null) { - defaultThreadPoolProfile.setMaxPoolSize(oldProfile.getMaxPoolSize()); - } - if (defaultThreadPoolProfile.getRejectedPolicy() == null) { - defaultThreadPoolProfile.setRejectedPolicy(oldProfile.getRejectedPolicy()); - } - if (defaultThreadPoolProfile.getMaxQueueSize() == null) { - defaultThreadPoolProfile.setMaxQueueSize(oldProfile.getMaxQueueSize()); - } - if (defaultThreadPoolProfile.getPoolSize() == null) { - defaultThreadPoolProfile.setPoolSize(oldProfile.getPoolSize()); - } - if (defaultThreadPoolProfile.getTimeUnit() == null) { - defaultThreadPoolProfile.setTimeUnit(oldProfile.getTimeUnit()); - } - } - - // validate that all options has been given as its mandatory for a default thread pool profile - // as it is used as fallback for other profiles if they do not have that particular value - ObjectHelper.notEmpty(defaultThreadPoolProfile.getId(), "id", defaultThreadPoolProfile); - ObjectHelper.notNull(defaultThreadPoolProfile.getKeepAliveTime(), "keepAliveTime", defaultThreadPoolProfile); - ObjectHelper.notNull(defaultThreadPoolProfile.getMaxPoolSize(), "maxPoolSize", defaultThreadPoolProfile); - ObjectHelper.notNull(defaultThreadPoolProfile.getMaxQueueSize(), "maxQueueSize", defaultThreadPoolProfile); - ObjectHelper.notNull(defaultThreadPoolProfile.getPoolSize(), "poolSize", defaultThreadPoolProfile); - ObjectHelper.notNull(defaultThreadPoolProfile.getTimeUnit(), "timeUnit", defaultThreadPoolProfile); + threadPoolProfiles.remove(defaultThreadPoolProfileId); + defaultThreadPoolProfile.addDefaults(builtIndefaultProfile); LOG.info("Using custom DefaultThreadPoolProfile: " + defaultThreadPoolProfile); - // and replace with the new default profile this.defaultThreadPoolProfileId = defaultThreadPoolProfile.getId(); - // and mark the new profile as default defaultThreadPoolProfile.setDefaultProfile(true); registerThreadPoolProfile(defaultThreadPoolProfile); } @@ -170,12 +135,7 @@ public ExecutorService newDefaultThreadPool(Object source, String name) { @Override public ScheduledExecutorService newDefaultScheduledThreadPool(Object source, String name) { - ThreadPoolProfile defaultProfile = getDefaultThreadPoolProfile(); - - ThreadFactory threadFactory = createThreadFactory(name, true); - ScheduledExecutorService executorService = threadPoolFactory.newScheduledThreadPool(defaultProfile.getPoolSize(), threadFactory); - onThreadPoolCreated(executorService, source, null); - return executorService; + return newScheduledThreadPool(source, name, getDefaultThreadPoolProfile()); } @Override @@ -194,35 +154,22 @@ public ExecutorService newThreadPool(Object source, String name, ThreadPoolProfi ObjectHelper.notNull(profile, "ThreadPoolProfile"); ThreadPoolProfile defaultProfile = getDefaultThreadPoolProfile(); - // fallback to use values from default profile if not specified - Integer poolSize = profile.getPoolSize() != null ? profile.getPoolSize() : defaultProfile.getPoolSize(); - Integer maxPoolSize = profile.getMaxPoolSize() != null ? profile.getMaxPoolSize() : defaultProfile.getMaxPoolSize(); - Long keepAliveTime = profile.getKeepAliveTime() != null ? profile.getKeepAliveTime() : defaultProfile.getKeepAliveTime(); - TimeUnit timeUnit = profile.getTimeUnit() != null ? profile.getTimeUnit() : defaultProfile.getTimeUnit(); - Integer maxQueueSize = profile.getMaxQueueSize() != null ? profile.getMaxQueueSize() : defaultProfile.getMaxQueueSize(); - RejectedExecutionHandler handler = profile.getRejectedExecutionHandler() != null ? profile.getRejectedExecutionHandler() : defaultProfile.getRejectedExecutionHandler(); + profile.addDefaults(defaultProfile); ThreadFactory threadFactory = createThreadFactory(name, true); - ExecutorService executorService = threadPoolFactory.newThreadPool(poolSize, maxPoolSize, - keepAliveTime, timeUnit, maxQueueSize, handler, threadFactory); + ExecutorService executorService = threadPoolFactory.newThreadPool(profile, threadFactory); onThreadPoolCreated(executorService, source, profile.getId()); + if (LOG.isDebugEnabled()) { + LOG.debug("Created new ThreadPool for source: {} with name: {}. -> {}", new Object[]{source, name, executorService}); + } + return executorService; } @Override public ExecutorService newThreadPool(Object source, String name, int poolSize, int maxPoolSize) { - ThreadPoolProfile defaultProfile = getDefaultThreadPoolProfile(); - - // fallback to use values from default profile - ExecutorService answer = threadPoolFactory.newThreadPool(poolSize, maxPoolSize, - defaultProfile.getKeepAliveTime(), defaultProfile.getTimeUnit(), defaultProfile.getMaxQueueSize(), - defaultProfile.getRejectedExecutionHandler(), new CamelThreadFactory(threadNamePattern, name, true)); - onThreadPoolCreated(answer, source, null); - - if (LOG.isDebugEnabled()) { - LOG.debug("Created new ThreadPool for source: {} with name: {}. -> {}", new Object[]{source, name, answer}); - } - return answer; + ThreadPoolProfile profile = new ThreadPoolProfileBuilder(name).poolSize(poolSize).maxPoolSize(maxPoolSize).build(); + return newThreadPool(source, name, profile); } @Override @@ -232,7 +179,7 @@ public ExecutorService newSingleThreadExecutor(Object source, String name) { @Override public ExecutorService newCachedThreadPool(Object source, String name) { - ExecutorService answer = threadPoolFactory.newCachedThreadPool(new CamelThreadFactory(threadNamePattern, name, true)); + ExecutorService answer = threadPoolFactory.newCachedThreadPool(createThreadFactory(name, true)); onThreadPoolCreated(answer, source, null); if (LOG.isDebugEnabled()) { @@ -243,29 +190,32 @@ public ExecutorService newCachedThreadPool(Object source, String name) { @Override public ExecutorService newFixedThreadPool(Object source, String name, int poolSize) { - ExecutorService answer = threadPoolFactory.newFixedThreadPool(poolSize, new CamelThreadFactory(threadNamePattern, name, true)); - onThreadPoolCreated(answer, source, null); - - if (LOG.isDebugEnabled()) { - LOG.debug("Created new FixedThreadPool for source: {} with name: {}. -> {}", new Object[]{source, name, answer}); - } - return answer; + ThreadPoolProfile profile = new ThreadPoolProfileBuilder(name).poolSize(poolSize).maxPoolSize(poolSize).keepAliveTime(0L).build(); + return newThreadPool(source, name, profile); } @Override public ScheduledExecutorService newSingleThreadScheduledExecutor(Object source, String name) { return newScheduledThreadPool(source, name, 1); } - + @Override - public ScheduledExecutorService newScheduledThreadPool(Object source, String name, int poolSize) { - ScheduledExecutorService answer = threadPoolFactory.newScheduledThreadPool(poolSize, new CamelThreadFactory(threadNamePattern, name, true)); + public ScheduledExecutorService newScheduledThreadPool(Object source, String name, ThreadPoolProfile profile) { + profile.addDefaults(getDefaultThreadPoolProfile()); + ScheduledExecutorService answer = threadPoolFactory.newScheduledThreadPool(profile, createThreadFactory(name, true)); onThreadPoolCreated(answer, source, null); if (LOG.isDebugEnabled()) { LOG.debug("Created new ScheduledThreadPool for source: {} with name: {}. -> {}", new Object[]{source, name, answer}); } return answer; + + } + + @Override + public ScheduledExecutorService newScheduledThreadPool(Object source, String name, int poolSize) { + ThreadPoolProfile profile = new ThreadPoolProfileBuilder(name).poolSize(poolSize).build(); + return newScheduledThreadPool(source, name, profile); } @Override diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultThreadPoolFactory.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultThreadPoolFactory.java index 3cbb0fa75bd59..318283fa01efb 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultThreadPoolFactory.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultThreadPoolFactory.java @@ -28,6 +28,7 @@ import java.util.concurrent.TimeUnit; import org.apache.camel.spi.ThreadPoolFactory; +import org.apache.camel.spi.ThreadPoolProfile; /** * Factory for thread pools that uses the JDK {@link Executors} for creating the thread pools. @@ -37,13 +38,16 @@ public class DefaultThreadPoolFactory implements ThreadPoolFactory { public ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { return Executors.newCachedThreadPool(threadFactory); } - - public ExecutorService newFixedThreadPool(int poolSize, ThreadFactory threadFactory) { - return Executors.newFixedThreadPool(poolSize, threadFactory); - } - - public ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) throws IllegalArgumentException { - return Executors.newScheduledThreadPool(corePoolSize, threadFactory); + + @Override + public ExecutorService newThreadPool(ThreadPoolProfile profile, ThreadFactory factory) { + return newThreadPool(profile.getPoolSize(), + profile.getMaxPoolSize(), + profile.getKeepAliveTime(), + profile.getTimeUnit(), + profile.getMaxQueueSize(), + profile.getRejectedExecutionHandler(), + factory); } public ExecutorService newThreadPool(int corePoolSize, int maxPoolSize, long keepAliveTime, TimeUnit timeUnit, @@ -84,5 +88,13 @@ public ExecutorService newThreadPool(int corePoolSize, int maxPoolSize, long kee answer.setRejectedExecutionHandler(rejectedExecutionHandler); return answer; } + + /* (non-Javadoc) + * @see org.apache.camel.impl.ThreadPoolFactory#newScheduledThreadPool(java.lang.Integer, java.util.concurrent.ThreadFactory) + */ + @Override + public ScheduledExecutorService newScheduledThreadPool(ThreadPoolProfile profile, ThreadFactory threadFactory) { + return Executors.newScheduledThreadPool(profile.getPoolSize(), threadFactory); + } } diff --git a/camel-core/src/main/java/org/apache/camel/model/ThreadsDefinition.java b/camel-core/src/main/java/org/apache/camel/model/ThreadsDefinition.java index fcddf40314609..aa5ef9f585d87 100644 --- a/camel-core/src/main/java/org/apache/camel/model/ThreadsDefinition.java +++ b/camel-core/src/main/java/org/apache/camel/model/ThreadsDefinition.java @@ -20,6 +20,7 @@ import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; + import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; @@ -29,10 +30,11 @@ import org.apache.camel.Processor; import org.apache.camel.ThreadPoolRejectedPolicy; -import org.apache.camel.builder.ThreadPoolBuilder; +import org.apache.camel.builder.ThreadPoolProfileBuilder; import org.apache.camel.builder.xml.TimeUnitAdapter; import org.apache.camel.processor.Pipeline; import org.apache.camel.processor.ThreadsProcessor; +import org.apache.camel.spi.ExecutorServiceManager; import org.apache.camel.spi.RouteContext; import org.apache.camel.spi.ThreadPoolProfile; @@ -81,24 +83,16 @@ public Processor createProcessor(RouteContext routeContext) throws Exception { executorService = ProcessorDefinitionHelper.getConfiguredExecutorService(routeContext, name, this); // if no explicit then create from the options if (executorService == null) { - ThreadPoolProfile profile = routeContext.getCamelContext().getExecutorServiceManager().getDefaultThreadPoolProfile(); - // use the default thread pool profile as base and then override with values - // use a custom pool based on the settings - int core = getPoolSize() != null ? getPoolSize() : profile.getPoolSize(); - int max = getMaxPoolSize() != null ? getMaxPoolSize() : profile.getMaxPoolSize(); - long keepAlive = getKeepAliveTime() != null ? getKeepAliveTime() : profile.getKeepAliveTime(); - int maxQueue = getMaxQueueSize() != null ? getMaxQueueSize() : profile.getMaxQueueSize(); - TimeUnit tu = getTimeUnit() != null ? getTimeUnit() : profile.getTimeUnit(); - ThreadPoolRejectedPolicy rejected = getRejectedPolicy() != null ? getRejectedPolicy() : profile.getRejectedPolicy(); - + ExecutorServiceManager manager = routeContext.getCamelContext().getExecutorServiceManager(); // create the thread pool using a builder - executorService = new ThreadPoolBuilder(routeContext.getCamelContext()) - .poolSize(core) - .maxPoolSize(max) - .keepAliveTime(keepAlive, tu) - .maxQueueSize(maxQueue) - .rejectedPolicy(rejected) - .build(this, name); + ThreadPoolProfile profile = new ThreadPoolProfileBuilder(name) + .poolSize(getPoolSize()) + .maxPoolSize(getMaxPoolSize()) + .keepAliveTime(getKeepAliveTime(), getTimeUnit()) + .maxQueueSize(getMaxQueueSize()) + .rejectedPolicy(getRejectedPolicy()) + .build(); + executorService = manager.newThreadPool(this, name, profile); } ThreadsProcessor thread = new ThreadsProcessor(routeContext.getCamelContext(), executorService); diff --git a/camel-core/src/main/java/org/apache/camel/spi/ExecutorServiceManager.java b/camel-core/src/main/java/org/apache/camel/spi/ExecutorServiceManager.java index 49efb0720c1b5..11070a96e0dcd 100644 --- a/camel-core/src/main/java/org/apache/camel/spi/ExecutorServiceManager.java +++ b/camel-core/src/main/java/org/apache/camel/spi/ExecutorServiceManager.java @@ -220,6 +220,8 @@ public interface ExecutorServiceManager extends ShutdownableService { * @return the created thread pool */ ScheduledExecutorService newSingleThreadScheduledExecutor(Object source, String name); + + ScheduledExecutorService newScheduledThreadPool(Object source, String name, ThreadPoolProfile profile); /** * Shutdown the given executor service. @@ -237,4 +239,5 @@ public interface ExecutorServiceManager extends ShutdownableService { * @see java.util.concurrent.ExecutorService#shutdownNow() */ List<Runnable> shutdownNow(ExecutorService executorService); + } diff --git a/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolFactory.java b/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolFactory.java index c97f5ab68ea06..cc31ad23ad938 100644 --- a/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolFactory.java +++ b/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolFactory.java @@ -17,73 +17,41 @@ package org.apache.camel.spi; import java.util.concurrent.ExecutorService; -import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; /** - * Factory to crate {@link ExecutorService} and {@link ScheduledExecutorService} instances - * <p/> - * This interface allows to customize the creation of these objects to adapt Camel - * for application servers and other environments where thread pools should - * not be created with the JDK methods, as provided by the {@link org.apache.camel.impl.DefaultThreadPoolFactory}. - * - * @see ExecutorServiceManager + * Creates ExecutorService and ScheduledExecutorService objects that work with a thread pool for a given ThreadPoolProfile and ThreadFactory. + * + * This interface allows to customize the creation of these objects to adapt camel for application servers and other environments where thread pools + * should not be created with the jdk methods */ public interface ThreadPoolFactory { - /** * Creates a new cached thread pool * <p/> * The cached thread pool is a term from the JDK from the method {@link java.util.concurrent.Executors#newCachedThreadPool()}. - * Implementators of this interface, may create a different kind of pool than the cached, or check the source code - * of the JDK to create a pool using the same settings. + * Typically it will have no size limit (this is why it is handled separately * * @param threadFactory factory for creating threads * @return the created thread pool */ ExecutorService newCachedThreadPool(ThreadFactory threadFactory); - + /** - * Creates a new fixed thread pool - * <p/> - * The fixed thread pool is a term from the JDK from the method {@link java.util.concurrent.Executors#newFixedThreadPool(int)}. - * Implementators of this interface, may create a different kind of pool than the fixed, or check the source code - * of the JDK to create a pool using the same settings. - * - * @param poolSize the number of threads in the pool - * @param threadFactory factory for creating threads - * @return the created thread pool + * Create a thread pool using the given thread pool profile + * + * @param profile + * @param threadFactory + * @return */ - ExecutorService newFixedThreadPool(int poolSize, ThreadFactory threadFactory); - + ExecutorService newThreadPool(ThreadPoolProfile profile, ThreadFactory threadFactory); + /** - * Creates a new scheduled thread pool - * - * @param corePoolSize the core pool size - * @param threadFactory factory for creating threads - * @return the created thread pool - * @throws IllegalArgumentException if parameters is not valid - */ - ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) throws IllegalArgumentException; - - /** - * Creates a new thread pool - * - * @param corePoolSize the core pool size - * @param maxPoolSize the maximum pool size - * @param keepAliveTime keep alive time - * @param timeUnit keep alive time unit - * @param maxQueueSize the maximum number of tasks in the queue, use <tt>Integer.MAX_VALUE</tt> or <tt>-1</tt> to indicate unbounded - * @param rejectedExecutionHandler the handler for tasks which cannot be executed by the thread pool. - * If <tt>null</tt> is provided then {@link java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy CallerRunsPolicy} is used. - * @param threadFactory factory for creating threads - * @return the created thread pool - * @throws IllegalArgumentException if parameters is not valid + * Create a scheduled thread pool using the given thread pool profile + * @param profile + * @param threadFactory + * @return */ - ExecutorService newThreadPool(int corePoolSize, int maxPoolSize, long keepAliveTime, TimeUnit timeUnit, - int maxQueueSize, RejectedExecutionHandler rejectedExecutionHandler, - ThreadFactory threadFactory) throws IllegalArgumentException; - -} + ScheduledExecutorService newScheduledThreadPool(ThreadPoolProfile profile, ThreadFactory threadFactory); +} \ No newline at end of file diff --git a/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolProfile.java b/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolProfile.java index c4f2e933477b0..87b9a01fd991b 100644 --- a/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolProfile.java +++ b/camel-core/src/main/java/org/apache/camel/spi/ThreadPoolProfile.java @@ -219,6 +219,49 @@ public void setRejectedPolicy(ThreadPoolRejectedPolicy rejectedPolicy) { this.rejectedPolicy = rejectedPolicy; } + /** + * Overwrites each attribute that is null with the attribute from defaultProfile + * + * @param defaultProfile2 + */ + public void addDefaults(ThreadPoolProfile defaultProfile2) { + if (defaultProfile2 == null) { + return; + } + if (poolSize == null) { + poolSize = defaultProfile2.getPoolSize(); + } + if (maxPoolSize == null) { + maxPoolSize = defaultProfile2.getMaxPoolSize(); + } + if (keepAliveTime == null) { + keepAliveTime = defaultProfile2.getKeepAliveTime(); + } + if (timeUnit == null) { + timeUnit = defaultProfile2.getTimeUnit(); + } + if (maxQueueSize == null) { + maxQueueSize = defaultProfile2.getMaxQueueSize(); + } + if (rejectedPolicy == null) { + rejectedPolicy = defaultProfile2.getRejectedPolicy(); + } + } + + @Override + public ThreadPoolProfile clone() { + ThreadPoolProfile cloned = new ThreadPoolProfile(); + cloned.setDefaultProfile(defaultProfile); + cloned.setId(id); + cloned.setKeepAliveTime(keepAliveTime); + cloned.setMaxPoolSize(maxPoolSize); + cloned.setMaxQueueSize(maxQueueSize); + cloned.setPoolSize(maxPoolSize); + cloned.setRejectedPolicy(rejectedPolicy); + cloned.setTimeUnit(timeUnit); + return cloned; + } + @Override public String toString() { return "ThreadPoolProfile[" + id + " (" + defaultProfile + ") size:" + poolSize + "-" + maxPoolSize diff --git a/camel-core/src/test/java/org/apache/camel/impl/CustomThreadPoolFactoryTest.java b/camel-core/src/test/java/org/apache/camel/impl/CustomThreadPoolFactoryTest.java index 6d26693cc0b2c..f5467c0ef541e 100644 --- a/camel-core/src/test/java/org/apache/camel/impl/CustomThreadPoolFactoryTest.java +++ b/camel-core/src/test/java/org/apache/camel/impl/CustomThreadPoolFactoryTest.java @@ -18,7 +18,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionHandler; -import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; @@ -54,18 +53,6 @@ public ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { return super.newCachedThreadPool(threadFactory); } - @Override - public ExecutorService newFixedThreadPool(int poolSize, ThreadFactory threadFactory) { - invoked = true; - return super.newFixedThreadPool(poolSize, threadFactory); - } - - @Override - public ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) throws IllegalArgumentException { - invoked = true; - return super.newScheduledThreadPool(corePoolSize, threadFactory); - } - @Override public ExecutorService newThreadPool(int corePoolSize, int maxPoolSize, long keepAliveTime, TimeUnit timeUnit, int maxQueueSize, RejectedExecutionHandler rejectedExecutionHandler, ThreadFactory threadFactory) throws IllegalArgumentException { diff --git a/camel-core/src/test/java/org/apache/camel/impl/DefaultExecutorServiceManagerTest.java b/camel-core/src/test/java/org/apache/camel/impl/DefaultExecutorServiceManagerTest.java index af9c1963afd91..75204f0f93e76 100644 --- a/camel-core/src/test/java/org/apache/camel/impl/DefaultExecutorServiceManagerTest.java +++ b/camel-core/src/test/java/org/apache/camel/impl/DefaultExecutorServiceManagerTest.java @@ -357,8 +357,8 @@ public void testNewFixedThreadPool() throws Exception { ThreadPoolExecutor tp = assertIsInstanceOf(ThreadPoolExecutor.class, pool); // a fixed dont use keep alive - assertEquals(0, tp.getKeepAliveTime(TimeUnit.SECONDS)); - assertEquals(5, tp.getMaximumPoolSize()); + assertEquals("keepAliveTime", 0, tp.getKeepAliveTime(TimeUnit.SECONDS)); + assertEquals("maximumPoolSize", 5, tp.getMaximumPoolSize()); assertEquals(5, tp.getCorePoolSize()); assertFalse(tp.isShutdown()); @@ -373,8 +373,8 @@ public void testNewSingleThreadExecutor() throws Exception { ThreadPoolExecutor tp = assertIsInstanceOf(ThreadPoolExecutor.class, pool); // a single dont use keep alive - assertEquals(0, tp.getKeepAliveTime(TimeUnit.SECONDS)); - assertEquals(1, tp.getMaximumPoolSize()); + assertEquals("keepAliveTime", 0, tp.getKeepAliveTime(TimeUnit.SECONDS)); + assertEquals("maximumPoolSize", 1, tp.getMaximumPoolSize()); assertEquals(1, tp.getCorePoolSize()); assertFalse(tp.isShutdown()); diff --git a/components/camel-core-xml/src/main/java/org/apache/camel/core/xml/AbstractCamelThreadPoolFactoryBean.java b/components/camel-core-xml/src/main/java/org/apache/camel/core/xml/AbstractCamelThreadPoolFactoryBean.java index 47338594284c3..624ab8087eb55 100644 --- a/components/camel-core-xml/src/main/java/org/apache/camel/core/xml/AbstractCamelThreadPoolFactoryBean.java +++ b/components/camel-core-xml/src/main/java/org/apache/camel/core/xml/AbstractCamelThreadPoolFactoryBean.java @@ -25,8 +25,9 @@ import org.apache.camel.CamelContext; import org.apache.camel.ThreadPoolRejectedPolicy; -import org.apache.camel.builder.ThreadPoolBuilder; +import org.apache.camel.builder.ThreadPoolProfileBuilder; import org.apache.camel.builder.xml.TimeUnitAdapter; +import org.apache.camel.spi.ThreadPoolProfile; import org.apache.camel.util.CamelContextHelper; /** @@ -74,10 +75,14 @@ public ExecutorService getObject() throws Exception { queueSize = CamelContextHelper.parseInteger(getCamelContext(), maxQueueSize); } - ExecutorService answer = new ThreadPoolBuilder(getCamelContext()) - .poolSize(size).maxPoolSize(max).keepAliveTime(keepAlive, getTimeUnit()) - .maxQueueSize(queueSize).rejectedPolicy(getRejectedPolicy()) - .build(getId(), getThreadName()); + ThreadPoolProfile profile = new ThreadPoolProfileBuilder(getId()) + .poolSize(size) + .maxPoolSize(max) + .keepAliveTime(keepAlive, timeUnit) + .maxQueueSize(queueSize) + .rejectedPolicy(rejectedPolicy) + .build(); + ExecutorService answer = getCamelContext().getExecutorServiceManager().newThreadPool(getId(), getThreadName(), profile); return answer; } diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/config/CustomThreadPoolFactoryTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/config/CustomThreadPoolFactoryTest.java index a756b06391406..31729538c3ce3 100644 --- a/components/camel-spring/src/test/java/org/apache/camel/spring/config/CustomThreadPoolFactoryTest.java +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/config/CustomThreadPoolFactoryTest.java @@ -18,7 +18,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionHandler; -import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; @@ -56,18 +55,6 @@ public ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { return super.newCachedThreadPool(threadFactory); } - @Override - public ExecutorService newFixedThreadPool(int poolSize, ThreadFactory threadFactory) { - invoked = true; - return super.newFixedThreadPool(poolSize, threadFactory); - } - - @Override - public ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) throws IllegalArgumentException { - invoked = true; - return super.newScheduledThreadPool(corePoolSize, threadFactory); - } - @Override public ExecutorService newThreadPool(int corePoolSize, int maxPoolSize, long keepAliveTime, TimeUnit timeUnit, int maxQueueSize, RejectedExecutionHandler rejectedExecutionHandler, ThreadFactory threadFactory) throws IllegalArgumentException {
7eb6b0fc4c0975ce708ce97632222ecb1129ed03
restlet-framework-java
- Initial code for enhanced internal HTTP- connectors.--
p
https://github.com/restlet/restlet-framework-java
diff --git a/incubator/org.restlet.ext.jxta/META-INF/MANIFEST.MF b/incubator/org.restlet.ext.jxta/META-INF/MANIFEST.MF index 038ef0bd74..de50ee7e6a 100644 --- a/incubator/org.restlet.ext.jxta/META-INF/MANIFEST.MF +++ b/incubator/org.restlet.ext.jxta/META-INF/MANIFEST.MF @@ -25,6 +25,7 @@ Import-Package: net.jxta, org.restlet.engine.application, org.restlet.engine.component, org.restlet.engine.http, + org.restlet.engine.http.stream, org.restlet.engine.local, org.restlet.engine.security, org.restlet.engine.util, diff --git a/incubator/org.restlet.ext.jxta/src/org/restlet/ext/jxta/JxtaClientCall.java b/incubator/org.restlet.ext.jxta/src/org/restlet/ext/jxta/JxtaClientCall.java index de63526fd6..e0f3c85419 100644 --- a/incubator/org.restlet.ext.jxta/src/org/restlet/ext/jxta/JxtaClientCall.java +++ b/incubator/org.restlet.ext.jxta/src/org/restlet/ext/jxta/JxtaClientCall.java @@ -37,7 +37,7 @@ import net.jxta.socket.JxtaSocket; import org.restlet.Request; -import org.restlet.engine.http.StreamClientCall; +import org.restlet.engine.http.stream.StreamClientCall; /** * JXTA HTTP client call. diff --git a/incubator/org.restlet.ext.jxta/src/org/restlet/ext/jxta/JxtaClientHelper.java b/incubator/org.restlet.ext.jxta/src/org/restlet/ext/jxta/JxtaClientHelper.java index b9085115e8..4e0e8334a6 100644 --- a/incubator/org.restlet.ext.jxta/src/org/restlet/ext/jxta/JxtaClientHelper.java +++ b/incubator/org.restlet.ext.jxta/src/org/restlet/ext/jxta/JxtaClientHelper.java @@ -35,7 +35,7 @@ import net.jxta.protocol.PipeAdvertisement; import org.restlet.Client; -import org.restlet.engine.http.StreamClientHelper; +import org.restlet.engine.http.stream.StreamClientHelper; /** * Abstract JXTA-based HTTP server connector helper. diff --git a/incubator/org.restlet.ext.jxta/src/org/restlet/ext/jxta/JxtaServerHelper.java b/incubator/org.restlet.ext.jxta/src/org/restlet/ext/jxta/JxtaServerHelper.java index 092f21be12..7ef6b15461 100644 --- a/incubator/org.restlet.ext.jxta/src/org/restlet/ext/jxta/JxtaServerHelper.java +++ b/incubator/org.restlet.ext.jxta/src/org/restlet/ext/jxta/JxtaServerHelper.java @@ -35,7 +35,7 @@ import net.jxta.protocol.PipeAdvertisement; import org.restlet.Server; -import org.restlet.engine.http.StreamServerHelper; +import org.restlet.engine.http.stream.StreamServerHelper; /** * Base JXTA connector. diff --git a/modules/org.restlet.ext.jaxrs/META-INF/MANIFEST.MF b/modules/org.restlet.ext.jaxrs/META-INF/MANIFEST.MF index 5954fe0c87..c74f0af20b 100644 --- a/modules/org.restlet.ext.jaxrs/META-INF/MANIFEST.MF +++ b/modules/org.restlet.ext.jaxrs/META-INF/MANIFEST.MF @@ -72,6 +72,7 @@ Import-Package: javax.activation;version="1.1.1";resolution:=optional, org.restlet.engine.application, org.restlet.engine.component, org.restlet.engine.http, + org.restlet.engine.http.adapter, org.restlet.engine.http.header, org.restlet.engine.io, org.restlet.engine.local, diff --git a/modules/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/Util.java b/modules/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/Util.java index 249c84d92f..7ac9600d78 100644 --- a/modules/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/Util.java +++ b/modules/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/Util.java @@ -76,9 +76,9 @@ import org.restlet.data.MediaType; import org.restlet.data.Metadata; import org.restlet.data.Parameter; -import org.restlet.engine.http.ClientAdapter; import org.restlet.engine.http.ClientCall; -import org.restlet.engine.http.ServerAdapter; +import org.restlet.engine.http.adapter.ClientAdapter; +import org.restlet.engine.http.adapter.ServerAdapter; import org.restlet.engine.http.header.ContentType; import org.restlet.engine.http.header.HeaderUtils; import org.restlet.engine.util.DateUtils; diff --git a/modules/org.restlet.ext.servlet/META-INF/MANIFEST.MF b/modules/org.restlet.ext.servlet/META-INF/MANIFEST.MF index d9c014022f..58539deafb 100644 --- a/modules/org.restlet.ext.servlet/META-INF/MANIFEST.MF +++ b/modules/org.restlet.ext.servlet/META-INF/MANIFEST.MF @@ -22,6 +22,7 @@ Import-Package: javax.servlet, org.restlet.engine.application, org.restlet.engine.component, org.restlet.engine.http, + org.restlet.engine.http.adapter, org.restlet.engine.http.header, org.restlet.engine.local, org.restlet.engine.security, diff --git a/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletAdapter.java b/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletAdapter.java index c1ec8af5c5..fad501652d 100644 --- a/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletAdapter.java +++ b/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletAdapter.java @@ -43,7 +43,7 @@ import org.restlet.data.Reference; import org.restlet.engine.http.HttpRequest; import org.restlet.engine.http.HttpResponse; -import org.restlet.engine.http.ServerAdapter; +import org.restlet.engine.http.adapter.ServerAdapter; import org.restlet.ext.servlet.internal.ServletCall; import org.restlet.ext.servlet.internal.ServletLogger; diff --git a/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletConverter.java b/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletConverter.java index d68f9e78af..d60652b12f 100644 --- a/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletConverter.java +++ b/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletConverter.java @@ -43,7 +43,7 @@ import org.restlet.data.Reference; import org.restlet.engine.http.HttpRequest; import org.restlet.engine.http.HttpResponse; -import org.restlet.engine.http.ServerAdapter; +import org.restlet.engine.http.adapter.ServerAdapter; import org.restlet.ext.servlet.internal.ServletCall; import org.restlet.ext.servlet.internal.ServletLogger; diff --git a/modules/org.restlet.ext.xdb/META-INF/MANIFEST.MF b/modules/org.restlet.ext.xdb/META-INF/MANIFEST.MF index 7d9d29e748..bf3867a329 100644 --- a/modules/org.restlet.ext.xdb/META-INF/MANIFEST.MF +++ b/modules/org.restlet.ext.xdb/META-INF/MANIFEST.MF @@ -25,6 +25,7 @@ Import-Package: javax.servlet, org.restlet.engine.application, org.restlet.engine.component, org.restlet.engine.http, + org.restlet.engine.http.adapter, org.restlet.engine.http.io, org.restlet.engine.io, org.restlet.engine.local, diff --git a/modules/org.restlet.ext.xdb/src/org/restlet/ext/xdb/XdbServletAdapter.java b/modules/org.restlet.ext.xdb/src/org/restlet/ext/xdb/XdbServletAdapter.java index ed45fc0b25..e7141a0820 100644 --- a/modules/org.restlet.ext.xdb/src/org/restlet/ext/xdb/XdbServletAdapter.java +++ b/modules/org.restlet.ext.xdb/src/org/restlet/ext/xdb/XdbServletAdapter.java @@ -47,7 +47,7 @@ import org.restlet.data.Reference; import org.restlet.engine.http.HttpRequest; import org.restlet.engine.http.HttpResponse; -import org.restlet.engine.http.ServerAdapter; +import org.restlet.engine.http.adapter.ServerAdapter; import org.restlet.ext.servlet.internal.ServletLogger; import org.restlet.ext.xdb.internal.XdbServletCall; diff --git a/modules/org.restlet.ext.xdb/src/org/restlet/ext/xdb/XdbServletConverter.java b/modules/org.restlet.ext.xdb/src/org/restlet/ext/xdb/XdbServletConverter.java index 6553dd35a5..3ca878a8d1 100644 --- a/modules/org.restlet.ext.xdb/src/org/restlet/ext/xdb/XdbServletConverter.java +++ b/modules/org.restlet.ext.xdb/src/org/restlet/ext/xdb/XdbServletConverter.java @@ -47,7 +47,7 @@ import org.restlet.data.Reference; import org.restlet.engine.http.HttpRequest; import org.restlet.engine.http.HttpResponse; -import org.restlet.engine.http.ServerAdapter; +import org.restlet.engine.http.adapter.ServerAdapter; import org.restlet.ext.servlet.internal.ServletLogger; import org.restlet.ext.xdb.internal.XdbServletCall; diff --git a/modules/org.restlet.test/src/org/restlet/test/engine/BaseConnectorsTestCase.java b/modules/org.restlet.test/src/org/restlet/test/engine/BaseConnectorsTestCase.java index 08778a1b00..2906b9b2c0 100644 --- a/modules/org.restlet.test/src/org/restlet/test/engine/BaseConnectorsTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/engine/BaseConnectorsTestCase.java @@ -37,8 +37,8 @@ import org.restlet.engine.ClientHelper; import org.restlet.engine.Engine; import org.restlet.engine.ServerHelper; -import org.restlet.engine.http.StreamClientHelper; -import org.restlet.engine.http.StreamServerHelper; +import org.restlet.engine.http.stream.StreamClientHelper; +import org.restlet.engine.http.stream.StreamServerHelper; import org.restlet.test.RestletTestCase; /** diff --git a/modules/org.restlet/META-INF/MANIFEST.MF b/modules/org.restlet/META-INF/MANIFEST.MF index 81259ea6d9..c89891d46b 100644 --- a/modules/org.restlet/META-INF/MANIFEST.MF +++ b/modules/org.restlet/META-INF/MANIFEST.MF @@ -21,7 +21,6 @@ Export-Package: org.restlet; org.restlet.security", org.restlet.engine; uses:="org.restlet.engine.log, - org.restlet.representation, org.restlet, org.restlet.engine.security, org.restlet.util, @@ -50,20 +49,39 @@ Export-Package: org.restlet; org.restlet.engine", org.restlet.engine.http; uses:="org.restlet.representation, - org.restlet.util, org.restlet, + org.restlet.util, org.restlet.engine, + org.restlet.engine.http.adapter, org.restlet.service, - javax.net, org.restlet.data", + org.restlet.engine.http.adapter; + uses:="org.restlet.data, + org.restlet.engine.http, + org.restlet.representation, + org.restlet, + org.restlet.util", + org.restlet.engine.http.connector; + uses:="org.restlet.representation, + org.restlet, + org.restlet.util, + org.restlet.engine, + org.restlet.data, + org.restlet.engine.http", org.restlet.engine.http.header;uses:="org.restlet.data,org.restlet.representation,org.restlet.util", - org.restlet.engine.http.io, + org.restlet.engine.http.io;uses:="org.restlet.representation,org.restlet.util", org.restlet.engine.http.security; uses:="org.restlet.data, org.restlet.engine.http.header, org.restlet.engine.security, org.restlet.util, org.restlet", + org.restlet.engine.http.stream; + uses:="javax.net, + org.restlet.data, + org.restlet.engine.http, + org.restlet.representation, + org.restlet", org.restlet.engine.internal;uses:="org.osgi.framework", org.restlet.engine.io;uses:="org.restlet.data,org.restlet.representation", org.restlet.engine.local; diff --git a/modules/org.restlet/module.xml b/modules/org.restlet/module.xml index bbe4ad0d7f..f93c74d0db 100644 --- a/modules/org.restlet/module.xml +++ b/modules/org.restlet/module.xml @@ -21,9 +21,12 @@ <export>org.restlet.engine.component</export> <export>org.restlet.engine.converter</export> <export>org.restlet.engine.http</export> + <export>org.restlet.engine.http.adapter</export> + <export>org.restlet.engine.http.connector</export> <export>org.restlet.engine.http.header</export> <export>org.restlet.engine.http.io</export> <export>org.restlet.engine.http.security</export> + <export>org.restlet.engine.http.stream</export> <export>org.restlet.engine.io</export> <export>org.restlet.engine.local</export> <export>org.restlet.engine.riap</export> @@ -71,9 +74,8 @@ <exclude name="META-INF/MANIFEST.MF" /> <exclude name="src/com/**" /> <exclude name="src/org/restlet/engine/internal/Activator.java" /> - <exclude name="src/org/restlet/engine/http/Connection*.java" /> - <exclude name="src/org/restlet/engine/http/StreamServer*" /> - <exclude name="src/org/restlet/engine/http/StreamClient*" /> + <exclude name="src/org/restlet/engine/http/connector/**" /> + <exclude name="src/org/restlet/engine/http/stream/**" /> <exclude name="src/org/restlet/engine/log/IdentClient.java" /> <exclude name="src/org/restlet/service/TaskService.java" /> ]]> @@ -109,15 +111,14 @@ <exclude name="src/org/restlet/engine/TemplateDispatcher.java" /> <exclude name="src/org/restlet/engine/component/**" /> <exclude name="src/org/restlet/engine/converter/**" /> - <exclude name="src/org/restlet/engine/http/Connection*.java" /> <exclude name="src/org/restlet/engine/http/HttpRequest.java" /> <exclude name="src/org/restlet/engine/http/HttpResponse*.java" /> <exclude name="src/org/restlet/engine/http/HttpServer*.java" /> <exclude name="src/org/restlet/engine/http/Server*" /> - <exclude name="src/org/restlet/engine/http/StreamServer*" /> - <exclude name="src/org/restlet/engine/http/StreamClient*" /> + <exclude name="src/org/restlet/engine/http/connector/**" /> <exclude name="src/org/restlet/engine/http/io/**" /> <exclude name="src/org/restlet/engine/http/security/**" /> + <exclude name="src/org/restlet/engine/http/stream/**" /> <exclude name="src/org/restlet/engine/internal/**" /> <exclude name="src/org/restlet/engine/io/BioUtils.java" /> <exclude name="src/org/restlet/engine/local/**" /> diff --git a/modules/org.restlet/src/org/restlet/engine/Engine.java b/modules/org.restlet/src/org/restlet/engine/Engine.java index 2fc7b330b0..ea574ea973 100644 --- a/modules/org.restlet/src/org/restlet/engine/Engine.java +++ b/modules/org.restlet/src/org/restlet/engine/Engine.java @@ -638,7 +638,7 @@ public void registerDefaultAuthentications() { public void registerDefaultConnectors() { // [ifndef gae, gwt] getRegisteredClients().add( - new org.restlet.engine.http.StreamClientHelper(null)); + new org.restlet.engine.http.stream.StreamClientHelper(null)); // [enddef] // [ifndef gwt] getRegisteredClients().add( @@ -654,7 +654,7 @@ public void registerDefaultConnectors() { // [enddef] // [ifndef gae, gwt] getRegisteredServers().add( - new org.restlet.engine.http.StreamServerHelper(null)); + new org.restlet.engine.http.stream.StreamServerHelper(null)); // [enddef] // [ifdef gwt] uncomment // getRegisteredClients().add( diff --git a/modules/org.restlet/src/org/restlet/engine/http/ClientCall.java b/modules/org.restlet/src/org/restlet/engine/http/ClientCall.java index 8410ba2921..449f27485d 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/ClientCall.java +++ b/modules/org.restlet/src/org/restlet/engine/http/ClientCall.java @@ -44,6 +44,7 @@ import org.restlet.data.Parameter; import org.restlet.data.Status; import org.restlet.data.Tag; +import org.restlet.engine.http.adapter.ClientAdapter; import org.restlet.engine.http.header.ContentType; import org.restlet.engine.http.header.DispositionReader; import org.restlet.engine.http.header.HeaderReader; diff --git a/modules/org.restlet/src/org/restlet/engine/http/HttpClientHelper.java b/modules/org.restlet/src/org/restlet/engine/http/HttpClientHelper.java index d3640b1a99..7cd0147c9f 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/HttpClientHelper.java +++ b/modules/org.restlet/src/org/restlet/engine/http/HttpClientHelper.java @@ -38,6 +38,7 @@ import org.restlet.Response; import org.restlet.data.Status; import org.restlet.engine.ClientHelper; +import org.restlet.engine.http.adapter.ClientAdapter; /** * Base HTTP client connector. Here is the list of parameters that are diff --git a/modules/org.restlet/src/org/restlet/engine/http/HttpServerHelper.java b/modules/org.restlet/src/org/restlet/engine/http/HttpServerHelper.java index 34668e1f0e..0f2028753c 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/HttpServerHelper.java +++ b/modules/org.restlet/src/org/restlet/engine/http/HttpServerHelper.java @@ -37,6 +37,7 @@ import org.restlet.Server; import org.restlet.engine.Engine; import org.restlet.engine.ServerHelper; +import org.restlet.engine.http.adapter.ServerAdapter; /** * Base HTTP server connector. Here is the list of parameters that are diff --git a/modules/org.restlet/src/org/restlet/engine/http/Adapter.java b/modules/org.restlet/src/org/restlet/engine/http/adapter/Adapter.java similarity index 99% rename from modules/org.restlet/src/org/restlet/engine/http/Adapter.java rename to modules/org.restlet/src/org/restlet/engine/http/adapter/Adapter.java index 838e753425..542c699ce0 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/Adapter.java +++ b/modules/org.restlet/src/org/restlet/engine/http/adapter/Adapter.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.engine.http; +package org.restlet.engine.http.adapter; import java.util.logging.Logger; diff --git a/modules/org.restlet/src/org/restlet/engine/http/ClientAdapter.java b/modules/org.restlet/src/org/restlet/engine/http/adapter/ClientAdapter.java similarity index 99% rename from modules/org.restlet/src/org/restlet/engine/http/ClientAdapter.java rename to modules/org.restlet/src/org/restlet/engine/http/adapter/ClientAdapter.java index f969eb1858..b9efdf3320 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/ClientAdapter.java +++ b/modules/org.restlet/src/org/restlet/engine/http/adapter/ClientAdapter.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.engine.http; +package org.restlet.engine.http.adapter; import java.io.IOException; import java.util.Date; @@ -53,6 +53,8 @@ import org.restlet.data.Warning; import org.restlet.engine.Edition; import org.restlet.engine.Engine; +import org.restlet.engine.http.ClientCall; +import org.restlet.engine.http.HttpClientHelper; import org.restlet.engine.http.header.CacheControlReader; import org.restlet.engine.http.header.CacheControlUtils; import org.restlet.engine.http.header.CookieReader; diff --git a/modules/org.restlet/src/org/restlet/engine/http/ServerAdapter.java b/modules/org.restlet/src/org/restlet/engine/http/adapter/ServerAdapter.java similarity index 99% rename from modules/org.restlet/src/org/restlet/engine/http/ServerAdapter.java rename to modules/org.restlet/src/org/restlet/engine/http/adapter/ServerAdapter.java index ccc5c098fc..df8c3085a2 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/ServerAdapter.java +++ b/modules/org.restlet/src/org/restlet/engine/http/adapter/ServerAdapter.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.engine.http; +package org.restlet.engine.http.adapter; import java.io.IOException; import java.security.cert.Certificate; @@ -49,6 +49,10 @@ import org.restlet.data.Parameter; import org.restlet.data.Status; import org.restlet.data.Warning; +import org.restlet.engine.http.Call; +import org.restlet.engine.http.HttpRequest; +import org.restlet.engine.http.HttpResponse; +import org.restlet.engine.http.ServerCall; import org.restlet.engine.http.header.CacheControlUtils; import org.restlet.engine.http.header.CookieUtils; import org.restlet.engine.http.header.DispositionUtils; diff --git a/modules/org.restlet/src/org/restlet/engine/http/adapter/package.html b/modules/org.restlet/src/org/restlet/engine/http/adapter/package.html new file mode 100644 index 0000000000..8b4319ce38 --- /dev/null +++ b/modules/org.restlet/src/org/restlet/engine/http/adapter/package.html @@ -0,0 +1,7 @@ +<HTML> +<BODY> +New advanced internal HTTP connector. +<p> +@since Restlet 2.0 +</BODY> +</HTML> \ No newline at end of file diff --git a/modules/org.restlet/src/org/restlet/engine/http/Connection.java b/modules/org.restlet/src/org/restlet/engine/http/connector/Connection.java similarity index 95% rename from modules/org.restlet/src/org/restlet/engine/http/Connection.java rename to modules/org.restlet/src/org/restlet/engine/http/connector/Connection.java index 80fbb6731f..3e5c8649ed 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/Connection.java +++ b/modules/org.restlet/src/org/restlet/engine/http/connector/Connection.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.engine.http; +package org.restlet.engine.http.connector; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; diff --git a/modules/org.restlet/src/org/restlet/engine/http/ConnectionState.java b/modules/org.restlet/src/org/restlet/engine/http/connector/ConnectionState.java similarity index 94% rename from modules/org.restlet/src/org/restlet/engine/http/ConnectionState.java rename to modules/org.restlet/src/org/restlet/engine/http/connector/ConnectionState.java index d8353875d3..baef77acf0 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/ConnectionState.java +++ b/modules/org.restlet/src/org/restlet/engine/http/connector/ConnectionState.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.engine.http; +package org.restlet.engine.http.connector; /** * Enumeration of the states of a connection. diff --git a/modules/org.restlet/src/org/restlet/engine/http/InternalRequest.java b/modules/org.restlet/src/org/restlet/engine/http/connector/InternalRequest.java similarity index 96% rename from modules/org.restlet/src/org/restlet/engine/http/InternalRequest.java rename to modules/org.restlet/src/org/restlet/engine/http/connector/InternalRequest.java index bd2beee6e6..0e30d6801d 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/InternalRequest.java +++ b/modules/org.restlet/src/org/restlet/engine/http/connector/InternalRequest.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.engine.http; +package org.restlet.engine.http.connector; import java.security.Principal; import java.security.cert.Certificate; @@ -51,6 +51,7 @@ import org.restlet.data.Reference; import org.restlet.data.Tag; import org.restlet.data.Warning; +import org.restlet.engine.http.Call; import org.restlet.engine.http.header.CacheControlReader; import org.restlet.engine.http.header.CookieReader; import org.restlet.engine.http.header.HeaderReader; diff --git a/modules/org.restlet/src/org/restlet/engine/http/InternalResponse.java b/modules/org.restlet/src/org/restlet/engine/http/connector/InternalResponse.java similarity index 94% rename from modules/org.restlet/src/org/restlet/engine/http/InternalResponse.java rename to modules/org.restlet/src/org/restlet/engine/http/connector/InternalResponse.java index ece046434c..2d62beda91 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/InternalResponse.java +++ b/modules/org.restlet/src/org/restlet/engine/http/connector/InternalResponse.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.engine.http; +package org.restlet.engine.http.connector; import org.restlet.Request; import org.restlet.Response; @@ -36,6 +36,7 @@ import org.restlet.data.ServerInfo; import org.restlet.data.Status; import org.restlet.engine.Engine; +import org.restlet.engine.http.ServerCall; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.util.Series; diff --git a/modules/org.restlet/src/org/restlet/engine/http/InternalServerCall.java b/modules/org.restlet/src/org/restlet/engine/http/connector/InternalServerCall.java similarity index 96% rename from modules/org.restlet/src/org/restlet/engine/http/InternalServerCall.java rename to modules/org.restlet/src/org/restlet/engine/http/connector/InternalServerCall.java index fb549d2427..549ce0aa8b 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/InternalServerCall.java +++ b/modules/org.restlet/src/org/restlet/engine/http/connector/InternalServerCall.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.engine.http; +package org.restlet.engine.http.connector; import java.io.InputStream; import java.io.OutputStream; diff --git a/modules/org.restlet/src/org/restlet/engine/http/InternalServerConnection.java b/modules/org.restlet/src/org/restlet/engine/http/connector/InternalServerConnection.java similarity index 96% rename from modules/org.restlet/src/org/restlet/engine/http/InternalServerConnection.java rename to modules/org.restlet/src/org/restlet/engine/http/connector/InternalServerConnection.java index edd881ba76..4134b1145e 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/InternalServerConnection.java +++ b/modules/org.restlet/src/org/restlet/engine/http/connector/InternalServerConnection.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.engine.http; +package org.restlet.engine.http.connector; import java.io.IOException; import java.net.Socket; diff --git a/modules/org.restlet/src/org/restlet/engine/http/InternalServerHandler.java b/modules/org.restlet/src/org/restlet/engine/http/connector/InternalServerHandler.java similarity index 93% rename from modules/org.restlet/src/org/restlet/engine/http/InternalServerHandler.java rename to modules/org.restlet/src/org/restlet/engine/http/connector/InternalServerHandler.java index 08cb2d388f..bf2a4a0f36 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/InternalServerHandler.java +++ b/modules/org.restlet/src/org/restlet/engine/http/connector/InternalServerHandler.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.engine.http; +package org.restlet.engine.http.connector; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; @@ -36,6 +36,8 @@ import java.net.Socket; import java.util.logging.Level; +import org.restlet.engine.http.stream.StreamServerCall; + /** * Class that handles an incoming socket. * diff --git a/modules/org.restlet/src/org/restlet/engine/http/InternalServerHelper.java b/modules/org.restlet/src/org/restlet/engine/http/connector/InternalServerHelper.java similarity index 95% rename from modules/org.restlet/src/org/restlet/engine/http/InternalServerHelper.java rename to modules/org.restlet/src/org/restlet/engine/http/connector/InternalServerHelper.java index 23720f10d6..df23191843 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/InternalServerHelper.java +++ b/modules/org.restlet/src/org/restlet/engine/http/connector/InternalServerHelper.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.engine.http; +package org.restlet.engine.http.connector; import java.io.IOException; import java.net.InetSocketAddress; @@ -43,6 +43,7 @@ import org.restlet.Server; import org.restlet.data.Protocol; +import org.restlet.engine.http.HttpServerHelper; import org.restlet.engine.log.LoggingThreadFactory; /** diff --git a/modules/org.restlet/src/org/restlet/engine/http/InternalServerListener.java b/modules/org.restlet/src/org/restlet/engine/http/connector/InternalServerListener.java similarity index 96% rename from modules/org.restlet/src/org/restlet/engine/http/InternalServerListener.java rename to modules/org.restlet/src/org/restlet/engine/http/connector/InternalServerListener.java index 205eaee32e..0d8e462ea6 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/InternalServerListener.java +++ b/modules/org.restlet/src/org/restlet/engine/http/connector/InternalServerListener.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.engine.http; +package org.restlet.engine.http.connector; import java.io.IOException; import java.nio.channels.ClosedByInterruptException; diff --git a/modules/org.restlet/src/org/restlet/engine/http/connector/package.html b/modules/org.restlet/src/org/restlet/engine/http/connector/package.html new file mode 100644 index 0000000000..8b4319ce38 --- /dev/null +++ b/modules/org.restlet/src/org/restlet/engine/http/connector/package.html @@ -0,0 +1,7 @@ +<HTML> +<BODY> +New advanced internal HTTP connector. +<p> +@since Restlet 2.0 +</BODY> +</HTML> \ No newline at end of file diff --git a/modules/org.restlet/src/org/restlet/engine/http/StreamClientCall.java b/modules/org.restlet/src/org/restlet/engine/http/stream/StreamClientCall.java similarity index 99% rename from modules/org.restlet/src/org/restlet/engine/http/StreamClientCall.java rename to modules/org.restlet/src/org/restlet/engine/http/stream/StreamClientCall.java index 415b7228c8..6d858464b8 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/StreamClientCall.java +++ b/modules/org.restlet/src/org/restlet/engine/http/stream/StreamClientCall.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.engine.http; +package org.restlet.engine.http.stream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; @@ -49,6 +49,7 @@ import org.restlet.data.Parameter; import org.restlet.data.Reference; import org.restlet.data.Status; +import org.restlet.engine.http.ClientCall; import org.restlet.engine.http.header.HeaderUtils; import org.restlet.engine.http.header.HeaderConstants; import org.restlet.engine.http.io.ChunkedInputStream; diff --git a/modules/org.restlet/src/org/restlet/engine/http/StreamClientHelper.java b/modules/org.restlet/src/org/restlet/engine/http/stream/StreamClientHelper.java similarity index 98% rename from modules/org.restlet/src/org/restlet/engine/http/StreamClientHelper.java rename to modules/org.restlet/src/org/restlet/engine/http/stream/StreamClientHelper.java index d652a9394e..4529877c3e 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/StreamClientHelper.java +++ b/modules/org.restlet/src/org/restlet/engine/http/stream/StreamClientHelper.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.engine.http; +package org.restlet.engine.http.stream; import java.io.File; import java.io.FileInputStream; @@ -49,6 +49,8 @@ import org.restlet.Client; import org.restlet.Request; import org.restlet.data.Protocol; +import org.restlet.engine.http.ClientCall; +import org.restlet.engine.http.HttpClientHelper; /** * HTTP client helper based on BIO sockets. Here is the list of parameters that diff --git a/modules/org.restlet/src/org/restlet/engine/http/ConnectionHandler.java b/modules/org.restlet/src/org/restlet/engine/http/stream/StreamHandler.java similarity index 90% rename from modules/org.restlet/src/org/restlet/engine/http/ConnectionHandler.java rename to modules/org.restlet/src/org/restlet/engine/http/stream/StreamHandler.java index 99e4bc3659..00e7c4e8fb 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/ConnectionHandler.java +++ b/modules/org.restlet/src/org/restlet/engine/http/stream/StreamHandler.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.engine.http; +package org.restlet.engine.http.stream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; @@ -41,7 +41,7 @@ * * @author Jerome Louvel */ -public class ConnectionHandler implements Runnable { +public class StreamHandler implements Runnable { /** The target server helper. */ private final StreamServerHelper helper; @@ -57,7 +57,7 @@ public class ConnectionHandler implements Runnable { * @param socket * The socket connection to handle. */ - public ConnectionHandler(StreamServerHelper helper, Socket socket) { + public StreamHandler(StreamServerHelper helper, Socket socket) { this.helper = helper; this.socket = socket; } diff --git a/modules/org.restlet/src/org/restlet/engine/http/ConnectionListener.java b/modules/org.restlet/src/org/restlet/engine/http/stream/StreamListener.java similarity index 91% rename from modules/org.restlet/src/org/restlet/engine/http/ConnectionListener.java rename to modules/org.restlet/src/org/restlet/engine/http/stream/StreamListener.java index 14527a52db..c45b8d0b42 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/ConnectionListener.java +++ b/modules/org.restlet/src/org/restlet/engine/http/stream/StreamListener.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.engine.http; +package org.restlet.engine.http.stream; import java.io.IOException; import java.nio.channels.ClosedByInterruptException; @@ -44,7 +44,7 @@ * * @author Jerome Louvel */ -public class ConnectionListener implements Runnable { +public class StreamListener implements Runnable { /** The target server helper. */ private final StreamServerHelper helper; @@ -73,7 +73,7 @@ public class ConnectionListener implements Runnable { * @param handlerService * The handler service. */ - public ConnectionListener(StreamServerHelper helper, + public StreamListener(StreamServerHelper helper, ServerSocketChannel serverSocket, CountDownLatch latch, ExecutorService handlerService) { this.helper = helper; @@ -92,7 +92,7 @@ public void run() { SocketChannel client = this.serverSocket.accept(); if (!this.handlerService.isShutdown()) { - this.handlerService.submit(new ConnectionHandler( + this.handlerService.submit(new StreamHandler( this.helper, client.socket())); } } catch (ClosedByInterruptException ex) { diff --git a/modules/org.restlet/src/org/restlet/engine/http/StreamServerCall.java b/modules/org.restlet/src/org/restlet/engine/http/stream/StreamServerCall.java similarity index 98% rename from modules/org.restlet/src/org/restlet/engine/http/StreamServerCall.java rename to modules/org.restlet/src/org/restlet/engine/http/stream/StreamServerCall.java index d99d5fb043..bf956caf05 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/StreamServerCall.java +++ b/modules/org.restlet/src/org/restlet/engine/http/stream/StreamServerCall.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.engine.http; +package org.restlet.engine.http.stream; import java.io.IOException; import java.io.InputStream; @@ -42,6 +42,7 @@ import org.restlet.Response; import org.restlet.Server; +import org.restlet.engine.http.ServerCall; import org.restlet.engine.http.io.ChunkedInputStream; import org.restlet.engine.http.io.ChunkedOutputStream; import org.restlet.engine.http.io.InputEntityStream; diff --git a/modules/org.restlet/src/org/restlet/engine/http/StreamServerHelper.java b/modules/org.restlet/src/org/restlet/engine/http/stream/StreamServerHelper.java similarity index 97% rename from modules/org.restlet/src/org/restlet/engine/http/StreamServerHelper.java rename to modules/org.restlet/src/org/restlet/engine/http/stream/StreamServerHelper.java index 3f73842859..5c49dbe53f 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/StreamServerHelper.java +++ b/modules/org.restlet/src/org/restlet/engine/http/stream/StreamServerHelper.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.engine.http; +package org.restlet.engine.http.stream; import java.io.IOException; import java.net.InetSocketAddress; @@ -43,6 +43,7 @@ import org.restlet.Server; import org.restlet.data.Protocol; +import org.restlet.engine.http.HttpServerHelper; import org.restlet.engine.log.LoggingThreadFactory; /** @@ -121,7 +122,7 @@ public synchronized void start() throws Exception { // Start the socket listener service this.latch = new CountDownLatch(1); - this.listenerService.submit(new ConnectionListener(this, + this.listenerService.submit(new StreamListener(this, this.serverSocketChannel, this.latch, this.handlerService)); // Wait for the listener to start up and count down the latch diff --git a/modules/org.restlet/src/org/restlet/engine/http/stream/package.html b/modules/org.restlet/src/org/restlet/engine/http/stream/package.html new file mode 100644 index 0000000000..bec1a53870 --- /dev/null +++ b/modules/org.restlet/src/org/restlet/engine/http/stream/package.html @@ -0,0 +1,7 @@ +<HTML> +<BODY> +Internal HTTP connector. +<p> +@since Restlet 2.0 +</BODY> +</HTML> \ No newline at end of file
b492b73284ef5080274716132406b765d5e47ea0
Mylyn Reviews
322734: UI Rework - review results drop down - review summary drop down
a
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSummaryTaskEditorPart.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSummaryTaskEditorPart.java index 24edd414..5404ec38 100644 --- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSummaryTaskEditorPart.java +++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewSummaryTaskEditorPart.java @@ -34,6 +34,7 @@ import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Table; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Section; @@ -42,6 +43,7 @@ * @author Kilian Matt */ public class ReviewSummaryTaskEditorPart extends AbstractTaskEditorPart { + public static final String ID_PART_REVIEWSUMMARY = "org.eclipse.mylyn.reviews.ui.editors.parts.reviewsummary"; //$NON-NLS-1$ public ReviewSummaryTaskEditorPart() { @@ -59,8 +61,11 @@ public void createControl(final Composite parent, FormToolkit toolkit) { summarySection.setText(Messages.ReviewSummaryTaskEditorPart_Partname); Composite reviewResultsComposite = toolkit .createComposite(summarySection); + toolkit.paintBordersFor(reviewResultsComposite); reviewResultsComposite.setLayout(new GridLayout(1, false)); - TableViewer reviewResults = createResultsTableViewer(reviewResultsComposite); + + TableViewer reviewResults = createResultsTableViewer( + reviewResultsComposite, toolkit); reviewResults.getControl().setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, true)); @@ -77,11 +82,16 @@ private TableViewerColumn createColumn(TableViewer parent, } private TableViewer createResultsTableViewer( - Composite reviewResultsComposite) { - TableViewer reviewResults = new TableViewer(reviewResultsComposite); - reviewResults.getTable().setHeaderVisible(true); - createColumn(reviewResults, Messages.ReviewSummaryTaskEditorPart_Header_ReviewId); - + Composite reviewResultsComposite, FormToolkit toolkit) { + Table table = toolkit.createTable(reviewResultsComposite, SWT.SINGLE + | SWT.FULL_SELECTION); + table.setHeaderVisible(true); + table.setLinesVisible(true); + table.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TREE_BORDER); + + TableViewer reviewResults = new TableViewer(table); + createColumn(reviewResults, + Messages.ReviewSummaryTaskEditorPart_Header_ReviewId); createColumn(reviewResults, Messages.ReviewSummaryTaskEditorPart_Header_Scope); createColumn(reviewResults, @@ -91,7 +101,8 @@ private TableViewer createResultsTableViewer( createColumn(reviewResults, Messages.ReviewSummaryTaskEditorPart_Header_Result); - createColumn(reviewResults, Messages.ReviewSummaryTaskEditorPart_Header_Comment); + createColumn(reviewResults, + Messages.ReviewSummaryTaskEditorPart_Header_Comment); reviewResults.setContentProvider(new IStructuredContentProvider() { @@ -105,9 +116,9 @@ public Object[] getElements(Object inputElement) { if (inputElement instanceof ITaskContainer) { ITaskContainer taskContainer = (ITaskContainer) inputElement; List<ReviewSubTask> reviewSubTasks = ReviewsUtil - .getReviewSubTasksFor(taskContainer, TasksUi - .getTaskDataManager(), TasksUi - .getRepositoryModel(), + .getReviewSubTasksFor(taskContainer, + TasksUi.getTaskDataManager(), + TasksUi.getRepositoryModel(), new NullProgressMonitor()); return reviewSubTasks @@ -163,6 +174,7 @@ public String getColumnText(Object element, int columnIndex) { return null; } } + }); reviewResults.setInput(getModel().getTask()); reviewResults.addDoubleClickListener(new IDoubleClickListener() { diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java index e3648f50..a627412e 100644 --- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java +++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java @@ -45,10 +45,10 @@ import org.eclipse.mylyn.tasks.ui.TasksUi; import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart; import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; -import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.Point; @@ -90,8 +90,7 @@ public void createControl(Composite parent, FormToolkit toolkit) { section.setLayout(gl); section.setLayoutData(gd); - composite = toolkit.createComposite(section); // , SWT.BACKGROUND); - composite.setLayout(createSectionClientLayout()); + composite = toolkit.createComposite(section); composite.setLayout(new GridLayout(1, true)); @@ -252,13 +251,20 @@ private void createResultFields(Composite composite, FormToolkit toolkit) { } Composite resultComposite = toolkit.createComposite(composite); + toolkit.paintBordersFor(resultComposite); + + CCombo ratingsCombo = new CCombo(resultComposite, SWT.READ_ONLY + | SWT.FLAT); + ratingsCombo.setData(FormToolkit.KEY_DRAW_BORDER, + FormToolkit.TREE_BORDER); + toolkit.adapt(ratingsCombo, false, false); + resultComposite.setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true, false)); resultComposite.setLayout(new GridLayout(2, false)); - final ComboViewer ratingList = new ComboViewer(resultComposite, - SWT.READ_ONLY | SWT.BORDER | SWT.FLAT); - ratingList.setContentProvider(ArrayContentProvider.getInstance()); + final ComboViewer ratingList = new ComboViewer(ratingsCombo); + ratingList.setContentProvider(ArrayContentProvider.getInstance()); ratingList.setLabelProvider(new LabelProvider() { @Override public String getText(Object element) { @@ -295,7 +301,7 @@ public Image getImage(Object element) { Rating rating = review.getResult().getRating(); ratingList.setSelection(new StructuredSelection(rating)); String comment = review.getResult().getText(); - commentText.setText(comment!=null?comment:""); + commentText.setText(comment != null ? comment : ""); } commentText.addModifyListener(new ModifyListener() { @@ -364,16 +370,6 @@ private DiffNode getDiffEditorNullInput() { return new DiffNode(new DiffNode(SWT.LEFT), new DiffNode(SWT.RIGHT)); } - private GridLayout createSectionClientLayout() { - GridLayout layout = new GridLayout(2, false); - layout.marginHeight = 0; - // leave 1px for borders - layout.marginTop = 2; - // spacing if a section is expanded - layout.marginBottom = 8; - return layout; - } - private static class MissingFile extends CompositeImageDescriptor { ISharedImages sharedImages = PlatformUI.getWorkbench() .getSharedImages();
89cafb31528e6d9edd1503deff0e2afa75209a44
kotlin
tuple literals--
a
https://github.com/JetBrains/kotlin
diff --git a/idea/src/org/jetbrains/jet/codegen/ExpressionCodegen.java b/idea/src/org/jetbrains/jet/codegen/ExpressionCodegen.java index 6f6ef95c26d39..1e31dc1d109df 100644 --- a/idea/src/org/jetbrains/jet/codegen/ExpressionCodegen.java +++ b/idea/src/org/jetbrains/jet/codegen/ExpressionCodegen.java @@ -1788,6 +1788,29 @@ public void run() { myMap.leaveTemp(subjectType.getSize()); } + @Override + public void visitTupleExpression(JetTupleExpression expression) { + final List<JetExpression> entries = expression.getEntries(); + if (entries.size() > 22) { + throw new UnsupportedOperationException("tuple too large"); + } + final String className = "jet/Tuple" + entries.size(); + Type tupleType = Type.getObjectType(className); + StringBuilder signature = new StringBuilder("("); + for (JetExpression entry : entries) { + signature.append("Ljava/lang/Object;"); + } + signature.append(")V"); + + v.anew(tupleType); + v.dup(); + for (JetExpression entry : entries) { + gen(entry, OBJECT_TYPE); + } + v.invokespecial(className, "<init>", signature.toString()); + myStack.push(StackValue.onStack(tupleType)); + } + private void throwNewException(final String className) { v.anew(Type.getObjectType(className)); v.dup(); diff --git a/idea/tests/org/jetbrains/jet/codegen/NamespaceGenTest.java b/idea/tests/org/jetbrains/jet/codegen/NamespaceGenTest.java index 8f34886b5374e..daf24b69b3d83 100644 --- a/idea/tests/org/jetbrains/jet/codegen/NamespaceGenTest.java +++ b/idea/tests/org/jetbrains/jet/codegen/NamespaceGenTest.java @@ -1,6 +1,7 @@ package org.jetbrains.jet.codegen; import jet.IntRange; +import jet.Tuple2; import org.jetbrains.jet.parsing.JetParsingTest; import java.awt.*; @@ -435,4 +436,12 @@ public void testArrayAccessForArrayList() throws Exception { main.invoke(null, list); assertEquals("JetLanguage", list.get(0)); } + + public void testTupleLiteral() throws Exception { + loadText("fun foo() = (1, \"foo\")"); + final Method main = generateFunction(); + Tuple2 tuple2 = (Tuple2) main.invoke(null); + assertEquals(1, tuple2._1); + assertEquals("foo", tuple2._2); + } }
85ec6bc6d7cd0904757b596627fd3666de7738dd
camel
added fix for- https://issues.apache.org/activemq/browse/CAMEL-347 to enable JUEL to invoke- methods in expressions--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@631503 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/camel
diff --git a/components/camel-juel/src/main/java/org/apache/camel/language/juel/BeanAndMethodELResolver.java b/components/camel-juel/src/main/java/org/apache/camel/language/juel/BeanAndMethodELResolver.java new file mode 100644 index 0000000000000..2412b27fa96a3 --- /dev/null +++ b/components/camel-juel/src/main/java/org/apache/camel/language/juel/BeanAndMethodELResolver.java @@ -0,0 +1,84 @@ +/** + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.language.juel; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +import javax.el.BeanELResolver; +import javax.el.ELContext; +import javax.el.PropertyNotFoundException; + +/** + * An extension of the JUEL {@link BeanELResolver} which also supports the resolving of methods + * + * @version $Revision: 1.1 $ + */ +public class BeanAndMethodELResolver extends BeanELResolver { + public BeanAndMethodELResolver() { + super(false); + } + + @Override + public Object getValue(ELContext elContext, Object base, Object property) { + try { + return super.getValue(elContext, base, property); + } + catch (PropertyNotFoundException e) { + // lets see if its a method call... + Method method = findMethod(elContext, base, property); + if (method != null) { + elContext.setPropertyResolved(true); + return method; + } + else { + throw e; + } + } + } + + protected Method findMethod(ELContext elContext, Object base, Object property) { + if (base != null && property instanceof String) { + Method[] methods = base.getClass().getMethods(); + List<Method> matching = new ArrayList<Method>(); + for (Method method : methods) { + if (method.getName().equals(property) && Modifier.isPublic(method.getModifiers())) { + matching.add(method); + } + } + int size = matching.size(); + if (size > 0) { + if (size > 1) { + // TODO there's currently no way for JUEL to tell us how many parameters there are + // so lets just pick the first one that has a single param by default + for (Method method : matching) { + Class<?>[] paramTypes = method.getParameterTypes(); + if (paramTypes.length == 1) { + return method; + } + } + } + // lets default to the first one + return matching.get(0); + } + } + return null; + } +} diff --git a/components/camel-juel/src/main/java/org/apache/camel/language/juel/JuelExpression.java b/components/camel-juel/src/main/java/org/apache/camel/language/juel/JuelExpression.java index dbeb68dc43ba8..a2d5e80e14c4f 100644 --- a/components/camel-juel/src/main/java/org/apache/camel/language/juel/JuelExpression.java +++ b/components/camel-juel/src/main/java/org/apache/camel/language/juel/JuelExpression.java @@ -16,12 +16,11 @@ */ package org.apache.camel.language.juel; -import javax.el.ELContext; -import javax.el.ExpressionFactory; -import javax.el.ValueExpression; +import java.util.Properties; -import de.odysseus.el.util.SimpleContext; +import javax.el.*; +import de.odysseus.el.util.SimpleContext; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.impl.ExpressionSupport; @@ -29,14 +28,14 @@ /** * The <a href="http://activemq.apache.org/camel/el.html">EL Language from JSP and JSF</a> * using the <a href="http://activemq.apache.org/camel/juel.html">JUEL library</a> - * + * * @version $Revision$ */ public class JuelExpression extends ExpressionSupport<Exchange> { - private final String expression; private final Class<?> type; private ExpressionFactory expressionFactory; + private Properties expressionFactoryProperties; public JuelExpression(String expression, Class<?> type) { this.expression = expression; @@ -57,7 +56,8 @@ public Object evaluate(Exchange exchange) { public ExpressionFactory getExpressionFactory() { if (expressionFactory == null) { - expressionFactory = ExpressionFactory.newInstance(); + Properties properties = getExpressionFactoryProperties(); + expressionFactory = ExpressionFactory.newInstance(properties); } return expressionFactory; } @@ -66,6 +66,18 @@ public void setExpressionFactory(ExpressionFactory expressionFactory) { this.expressionFactory = expressionFactory; } + public Properties getExpressionFactoryProperties() { + if (expressionFactoryProperties == null) { + expressionFactoryProperties = new Properties(); + populateDefaultExpressionProperties(expressionFactoryProperties); + } + return expressionFactoryProperties; + } + + public void setExpressionFactoryProperties(Properties expressionFactoryProperties) { + this.expressionFactoryProperties = expressionFactoryProperties; + } + protected ELContext populateContext(ELContext context, Exchange exchange) { setVariable(context, "exchange", exchange, Exchange.class); setVariable(context, "in", exchange.getIn(), Message.class); @@ -74,6 +86,14 @@ protected ELContext populateContext(ELContext context, Exchange exchange) { return context; } + /** + * A Strategy Method to populate the default properties used to create the expression factory + */ + protected void populateDefaultExpressionProperties(Properties properties) { + // lets enable method invocations + properties.setProperty("javax.el.methodInvocations", "true"); + } + protected void setVariable(ELContext context, String name, Object value, Class<?> type) { ValueExpression valueExpression = getExpressionFactory().createValueExpression(value, type); SimpleContext simpleContext = (SimpleContext) context; @@ -84,7 +104,17 @@ protected void setVariable(ELContext context, String name, Object value, Class<? * Factory method to create the EL context */ protected ELContext createContext() { - return new SimpleContext(); + ELResolver resolver = new CompositeELResolver() { + { + //add(methodResolver); + add(new ArrayELResolver(false)); + add(new ListELResolver(false)); + add(new MapELResolver(false)); + add(new ResourceBundleELResolver()); + add(new BeanAndMethodELResolver()); + } + }; + return new SimpleContext(resolver); } protected String assertionFailureMessage(Exchange exchange) { diff --git a/components/camel-juel/src/test/java/org/apache/camel/language/juel/JuelLanguageTest.java b/components/camel-juel/src/test/java/org/apache/camel/language/juel/JuelLanguageTest.java index e7e5734aed8e2..dba142ceb009c 100644 --- a/components/camel-juel/src/test/java/org/apache/camel/language/juel/JuelLanguageTest.java +++ b/components/camel-juel/src/test/java/org/apache/camel/language/juel/JuelLanguageTest.java @@ -28,6 +28,10 @@ public void testElExpressions() throws Exception { assertExpression("${in.body}", "<hello id='m123'>world!</hello>"); } + public void testElPredicates() throws Exception { + assertPredicate("${in.headers.foo.startsWith('a')}"); + } + protected String getLanguageName() { return "el"; }
16cb7d8d59add7b3ef513bba0de6a4fc07e3bc52
aeshell$aesh
search is more complete, support forward/reverse in emacs mode more complete readline support in emacs mode
a
https://github.com/aeshell/aesh
diff --git a/src/main/java/org/jboss/jreadline/console/Console.java b/src/main/java/org/jboss/jreadline/console/Console.java index 673a9e1fb..a24060ca1 100644 --- a/src/main/java/org/jboss/jreadline/console/Console.java +++ b/src/main/java/org/jboss/jreadline/console/Console.java @@ -19,9 +19,11 @@ import org.jboss.jreadline.edit.EditMode; import org.jboss.jreadline.edit.EmacsEditMode; import org.jboss.jreadline.edit.PasteManager; +import org.jboss.jreadline.edit.ViEditMode; import org.jboss.jreadline.edit.actions.*; import org.jboss.jreadline.history.History; import org.jboss.jreadline.history.InMemoryHistory; +import org.jboss.jreadline.history.SearchDirection; import org.jboss.jreadline.terminal.POSIXTerminal; import org.jboss.jreadline.terminal.Terminal; import org.jboss.jreadline.undo.UndoAction; @@ -132,29 +134,40 @@ else if(action == Action.SEARCH) { switch (operation.getMovement()) { //init a previous search case PREV: + history.setSearchDirection(SearchDirection.REVERSE); searchTerm = new StringBuilder(buffer.getLine()); if (searchTerm.length() > 0) { - result = history.searchPrevious(searchTerm.toString()); + result = history.search(searchTerm.toString()); + } + break; + + case NEXT: + history.setSearchDirection(SearchDirection.FORWARD); + searchTerm = new StringBuilder(buffer.getLine()); + if (searchTerm.length() > 0) { + result = history.search(searchTerm.toString()); } break; case PREV_WORD: - result = history.searchPrevious(searchTerm.toString()); + history.setSearchDirection(SearchDirection.REVERSE); + result = history.search(searchTerm.toString()); + break; + case NEXT_WORD: + history.setSearchDirection(SearchDirection.FORWARD); + result = history.search(searchTerm.toString()); break; case PREV_BIG_WORD: - - if (searchTerm.length() > 0) { + if (searchTerm.length() > 0) searchTerm.deleteCharAt(searchTerm.length() - 1); - } - break; // new search input, append to search case ALL: searchTerm.appendCodePoint(c); //check if the new searchTerm will find anything - StringBuilder tmpResult = history.searchPrevious(searchTerm.toString()); + StringBuilder tmpResult = history.search(searchTerm.toString()); // if(tmpResult == null) { searchTerm.deleteCharAt(searchTerm.length()-1); @@ -258,6 +271,12 @@ else if(action == Action.PASTE) { else doPaste(0, false); } + else if(action == Action.CHANGE_EDITMODE) { + if(operation.getMovement() == Movement.PREV) + editMode = new EmacsEditMode(); + else if(operation.getMovement() == Movement.NEXT) + editMode = new ViEditMode(); + } else if(action == Action.NO_ACTION) { //atm do nothing } @@ -438,7 +457,11 @@ private void printSearch(String searchTerm, String result) throws IOException { //cursor should be placed at the index of searchTerm int cursor = result.indexOf(searchTerm); - StringBuilder out = new StringBuilder("(reverse-i-search) `"); + StringBuilder out = null; + if(history.getSearchDirection() == SearchDirection.REVERSE) + out = new StringBuilder("(reverse-i-search) `"); + else + out = new StringBuilder("(forward-i-search) `"); out.append(searchTerm).append("': "); cursor += out.length(); out.append(result); //.append("\u001b[K"); diff --git a/src/main/java/org/jboss/jreadline/edit/EmacsEditMode.java b/src/main/java/org/jboss/jreadline/edit/EmacsEditMode.java index ce8e46031..2814b106a 100644 --- a/src/main/java/org/jboss/jreadline/edit/EmacsEditMode.java +++ b/src/main/java/org/jboss/jreadline/edit/EmacsEditMode.java @@ -24,6 +24,9 @@ * TODO: * - add support for different os key values (mainly windows) * + * Trying to follow the gnu readline impl found here: + * http://cnswww.cns.cwru.edu/php/chet/readline/readline.html + * * @author Ståle W. Pedersen <[email protected]> */ public class EmacsEditMode implements EditMode { @@ -45,20 +48,27 @@ public class EmacsEditMode implements EditMode { private final static short CTRL_N = 14; private final static short CTRL_P = 16; private final static short CTRL_R = 18; + private final static short CTRL_S = 19; private final static short CTRL_U = 21; private final static short CTRL_V = 22; private final static short CTRL_W = 23; - private final static short CTRL_X = 24; // prev word + private final static short CTRL_X = 24; + private final static short CTRL_Y = 25; // yank private final static short ESCAPE = 27; + private final static short CTRL__ = 31; private final static short ARROW_START = 91; private final static short LEFT = 68; private final static short RIGHT = 67; private final static short UP = 65; private final static short DOWN = 66; private final static short BACKSPACE = 127; + private final static short F = 102; // needed to handle M-f + private final static short B = 98; // needed to handle M-b + private final static short D = 100; // needed to handle M-d private boolean arrowStart = false; private boolean arrowPrefix = false; + private boolean ctrl_xState = false; private Action mode = Action.EDIT; @@ -75,6 +85,9 @@ public Operation parseInput(int input) { else if(input == CTRL_R) { return new Operation(Movement.PREV_WORD, Action.SEARCH); } + else if(input == CTRL_S) { + return new Operation(Movement.NEXT_WORD, Action.SEARCH); + } else if(input == BACKSPACE) { return new Operation(Movement.PREV_BIG_WORD, Action.SEARCH); } @@ -99,7 +112,7 @@ else if(input == BACKSPACE) else if(input == CTRL_B) return new Operation(Movement.PREV, Action.MOVE); else if(input == CTRL_D) - return new Operation(Movement.PREV, Action.EXIT); + return new Operation(Movement.NEXT, Action.DELETE); else if(input == CTRL_E) return new Operation(Movement.END, Action.MOVE); else if(input == CTRL_F) @@ -111,33 +124,75 @@ else if(input == CTRL_H) else if(input == CTRL_I) return new Operation(Movement.PREV, Action.COMPLETE); else if(input == CTRL_K) - return new Operation(Movement.ALL, Action.DELETE); + return new Operation(Movement.END, Action.DELETE); else if(input == CTRL_L) return new Operation(Movement.ALL, Action.DELETE); //TODO: should change to clear screen else if(input == CTRL_N) return new Operation(Movement.NEXT, Action.HISTORY); else if(input == CTRL_P) return new Operation(Movement.PREV, Action.HISTORY); - else if(input == CTRL_U) - return new Operation(Movement.BEGINNING, Action.DELETE); + else if(input == CTRL__) + return new Operation(Action.UNDO); + + else if(input == CTRL_U) { + //only undo if C-x have been pressed first + if(ctrl_xState) { + ctrl_xState = false; + return new Operation(Action.UNDO); + } + else + return new Operation(Movement.BEGINNING, Action.DELETE); + } else if(input == CTRL_V) return new Operation(Movement.NEXT, Action.PASTE_FROM_CLIPBOARD); + // Kill from the cursor to the previous whitespace else if(input == CTRL_W) - return new Operation(Movement.PREV_WORD, Action.DELETE); - else if(input == CTRL_X) - return new Operation(Movement.PREV_WORD, Action.MOVE); + return new Operation(Movement.PREV_BIG_WORD, Action.DELETE); + + // Yank the most recently killed text back into the buffer at the cursor. + else if(input == CTRL_Y) + return new Operation(Movement.NEXT, Action.PASTE); else if(input == CR) return new Operation(Movement.BEGINNING, Action.MOVE); // search else if(input == CTRL_R) { mode = Action.SEARCH; - return new Operation(Movement.PREV, Action.SEARCH); } + else if(input == CTRL_S) { + mode = Action.SEARCH; + return new Operation(Movement.NEXT, Action.SEARCH); + } + + //enter C-x state + else if(input == CTRL_X) { + ctrl_xState = true; + return new Operation(Action.NO_ACTION); + } + + // handle meta keys + else if(input == F && arrowStart) { + arrowStart = false; + return new Operation(Movement.NEXT_WORD, Action.MOVE); + } + else if(input == B && arrowStart) { + arrowStart = false; + return new Operation(Movement.PREV_WORD, Action.MOVE); + } + else if(input == D && arrowStart) { + arrowStart = false; + return new Operation(Movement.NEXT_WORD, Action.DELETE); + } // handle arrow keys else if(input == ESCAPE) { + // if we've already gotten a escape + if(arrowStart) { + arrowStart = false; + return new Operation(Action.NO_ACTION); + } + //new escape, set status as arrowStart if(!arrowPrefix && !arrowStart) { arrowStart = true; return new Operation(Action.NO_ACTION); diff --git a/src/main/java/org/jboss/jreadline/edit/ViEditMode.java b/src/main/java/org/jboss/jreadline/edit/ViEditMode.java index 0ec257323..7c746b5be 100644 --- a/src/main/java/org/jboss/jreadline/edit/ViEditMode.java +++ b/src/main/java/org/jboss/jreadline/edit/ViEditMode.java @@ -46,6 +46,7 @@ public class ViEditMode implements EditMode { private static final short VI_SHIFT_I = 73; private static final short VI_TILDE = 126; private static final short VI_Y = 121; + private static final short CTRL_E = 5; //movement private static final short VI_H = 104; @@ -272,6 +273,8 @@ else if(c == VI_Y) { else mode = Action.YANK; } + else if(c == CTRL_E) + return new Operation(Movement.PREV, Action.CHANGE_EDITMODE); return new Operation(Movement.BEGINNING, Action.NO_ACTION); } diff --git a/src/main/java/org/jboss/jreadline/edit/actions/Action.java b/src/main/java/org/jboss/jreadline/edit/actions/Action.java index a2fc01001..dea889024 100644 --- a/src/main/java/org/jboss/jreadline/edit/actions/Action.java +++ b/src/main/java/org/jboss/jreadline/edit/actions/Action.java @@ -38,5 +38,6 @@ public enum Action { CASE, EXIT, ABORT, + CHANGE_EDITMODE, NO_ACTION; } diff --git a/src/main/java/org/jboss/jreadline/history/History.java b/src/main/java/org/jboss/jreadline/history/History.java index b3eaf9bc7..c2956aaa3 100644 --- a/src/main/java/org/jboss/jreadline/history/History.java +++ b/src/main/java/org/jboss/jreadline/history/History.java @@ -30,13 +30,15 @@ public interface History { int size(); + void setSearchDirection(SearchDirection direction); + + SearchDirection getSearchDirection(); + StringBuilder getNextFetch(); StringBuilder getPreviousFetch(); - StringBuilder searchNext(String search); - - StringBuilder searchPrevious(String search); + StringBuilder search(String search); void setCurrent(StringBuilder line); diff --git a/src/main/java/org/jboss/jreadline/history/InMemoryHistory.java b/src/main/java/org/jboss/jreadline/history/InMemoryHistory.java index 5b67831c4..55696be8e 100644 --- a/src/main/java/org/jboss/jreadline/history/InMemoryHistory.java +++ b/src/main/java/org/jboss/jreadline/history/InMemoryHistory.java @@ -30,6 +30,7 @@ public class InMemoryHistory implements History { private int lastFetchedId = -1; private int lastSearchedId = 0; private StringBuilder current; + private SearchDirection searchDirection = SearchDirection.REVERSE; @Override public void push(StringBuilder entry) { @@ -60,6 +61,16 @@ public int size() { return historyList.size(); } + @Override + public void setSearchDirection(SearchDirection direction) { + searchDirection = direction; + } + + @Override + public SearchDirection getSearchDirection() { + return searchDirection; + } + @Override public StringBuilder getPreviousFetch() { if(size() < 1) @@ -73,7 +84,14 @@ public StringBuilder getPreviousFetch() { } @Override - public StringBuilder searchNext(String search) { + public StringBuilder search(String search) { + if(searchDirection == SearchDirection.REVERSE) + return searchReverse(search); + else + return searchForward(search); + } + + private StringBuilder searchForward(String search) { for(; lastSearchedId < size(); lastSearchedId++) { if(historyList.get(lastSearchedId).indexOf(search) != -1) return get(lastSearchedId); @@ -83,9 +101,8 @@ public StringBuilder searchNext(String search) { return null; } - @Override - public StringBuilder searchPrevious(String search) { - if(lastSearchedId < 1) + private StringBuilder searchReverse(String search) { + if(lastSearchedId < 1 || lastSearchedId >= size()) lastSearchedId = size()-1; for(; lastSearchedId >= 0; lastSearchedId-- ) { diff --git a/src/main/java/org/jboss/jreadline/history/SearchDirection.java b/src/main/java/org/jboss/jreadline/history/SearchDirection.java new file mode 100644 index 000000000..8a701ca6e --- /dev/null +++ b/src/main/java/org/jboss/jreadline/history/SearchDirection.java @@ -0,0 +1,26 @@ + /* + * 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.history; + +/** + * + * @author <a href="mailto:[email protected]">Ståle W. Pedersen</a> + */ +public enum SearchDirection { + REVERSE, + FORWARD; +} diff --git a/src/main/java/org/jboss/jreadline/terminal/POSIXTerminal.java b/src/main/java/org/jboss/jreadline/terminal/POSIXTerminal.java index 0e95e20d9..33b399201 100644 --- a/src/main/java/org/jboss/jreadline/terminal/POSIXTerminal.java +++ b/src/main/java/org/jboss/jreadline/terminal/POSIXTerminal.java @@ -76,7 +76,8 @@ public void init() { //checkBackspace(); // set the console to be character-buffered instead of line-buffered - stty("-icanon min 1"); + // -ixon will give access to ctrl-s/ctrl-q + stty("-ixon -icanon min 1"); // disable character echoing stty("-echo");
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<String> completionCandidates) { this.completionCandidates.addAll(completionCandidates); } - + + public void removeEscapedSpacesFromCompletionCandidates() { + setCompletionCandidates(Parser.switchEscapedSpacesToSpacesInList(getCompletionCandidates())); + } + public List<String> getFormattedCompletionCandidates() { if(offset < cursor) { List<String> fixedCandidates = new ArrayList<String>(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<String> 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<String> 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<String> 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<String> completions, int termHeight, int termWidth) { - if(completions == null || completions.size() < 1) + public static String formatDisplayList(List<String> 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<String> 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<String> switchEscapedSpacesToSpacesInList(List<String> list) { + List<String> newList = new ArrayList<String>(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 <a href="mailto:[email protected]">Ståle W. Pedersen</a> + */ +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<String> 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 ")); + } + }
eff73c243eabb0f63129eed9ad3ccf6be36c56b4
drools
[DROOLS-94] fix BaseObjectClassFieldReader when- reading numeric values--
c
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java index 2bc60ce137a..ff2ed967dc4 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java +++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/MiscTest2.java @@ -1589,9 +1589,9 @@ public void testJitCastOfPrimitiveType() { // DROOLS-79 String str = "rule R when\n" + - " Number(longValue < (Long)7)\n" + - "then\n" + - "end\n"; + " Number(longValue < (Long)7)\n" + + "then\n" + + "end\n"; KnowledgeBase kbase = loadKnowledgeBaseFromString(str); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); @@ -1599,4 +1599,35 @@ public void testJitCastOfPrimitiveType() { ksession.insert(new Long(6)); assertEquals(1, ksession.fireAllRules()); } + + @Test + public void testMatchIntegers() { + // DROOLS-94 + String str = + "global java.util.List list; \n" + + "rule R when\n" + + " $i : Integer( this == 1 )\n" + + "then\n" + + " list.add( $i );\n" + + "end\n" + + "rule S when\n" + + " $i : Integer( this == 2 )\n" + + "then\n" + + " list.add( $i );\n" + + "end\n" + + "rule T when\n" + + " $i : Integer( this == 3 )\n" + + "then\n" + + " list.add( $i );\n" + + "end\n"; + + KnowledgeBase kbase = loadKnowledgeBaseFromString(str); + StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); + + List list = new ArrayList(); + ksession.setGlobal( "list", list ); + + ksession.insert( new Integer( 1 ) ); + ksession.fireAllRules(); + } } diff --git a/drools-core/src/main/java/org/drools/core/base/extractors/BaseObjectClassFieldReader.java b/drools-core/src/main/java/org/drools/core/base/extractors/BaseObjectClassFieldReader.java index 50cfb1e8ffe..2effc8528b5 100755 --- a/drools-core/src/main/java/org/drools/core/base/extractors/BaseObjectClassFieldReader.java +++ b/drools-core/src/main/java/org/drools/core/base/extractors/BaseObjectClassFieldReader.java @@ -85,6 +85,8 @@ public double getDoubleValue(InternalWorkingMemory workingMemory, if( value instanceof Character ) { return ((Character) value).charValue(); + } else if ( value instanceof Number ) { + return ((Number) value).doubleValue(); } throw new RuntimeDroolsException( "Conversion to double not supported from " + getExtractToClass().getName() ); @@ -97,6 +99,8 @@ public float getFloatValue(InternalWorkingMemory workingMemory, if( value instanceof Character ) { return ((Character) value).charValue(); + } else if ( value instanceof Number ) { + return ((Number) value).floatValue(); } throw new RuntimeDroolsException( "Conversion to float not supported from " + getExtractToClass().getName() ); @@ -109,6 +113,8 @@ public int getIntValue(InternalWorkingMemory workingMemory, if( value instanceof Character ) { return ((Character) value).charValue(); + } else if ( value instanceof Number ) { + return ((Number) value).intValue(); } throw new RuntimeDroolsException( "Conversion to int not supported from " + getExtractToClass().getName() ); @@ -121,6 +127,8 @@ public long getLongValue(InternalWorkingMemory workingMemory, if( value instanceof Character ) { return ((Character) value).charValue(); + } else if ( value instanceof Number ) { + return ((Number) value).longValue(); } throw new RuntimeDroolsException( "Conversion to long not supported from " + getExtractToClass().getName() ); @@ -133,8 +141,10 @@ public short getShortValue(InternalWorkingMemory workingMemory, if( value instanceof Character ) { return (short) ((Character) value).charValue(); + } else if ( value instanceof Number ) { + return ((Number) value).shortValue(); } - + throw new RuntimeDroolsException( "Conversion to short not supported from " + getExtractToClass().getName() ); }
2f3d64b70fbd92d4f3fe132bf0dd46a822ee14d6
drools
JBRULES-976: fixing problems with collections- clonning and adding unit tests--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@13162 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
p
https://github.com/kiegroup/drools
diff --git a/drools-core/src/main/java/org/drools/util/ShadowProxyUtils.java b/drools-core/src/main/java/org/drools/util/ShadowProxyUtils.java index c9645536720..6ba4bb284ec 100644 --- a/drools-core/src/main/java/org/drools/util/ShadowProxyUtils.java +++ b/drools-core/src/main/java/org/drools/util/ShadowProxyUtils.java @@ -20,6 +20,7 @@ import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.Collection; +import java.util.Collections; import java.util.Map; /** @@ -29,6 +30,12 @@ */ public class ShadowProxyUtils { + /* Collections.UnmodifiableCollection is a package + * private class, thus the confusing bit above + * to get a Class to compare to. */ + private static final Class UNMODIFIABLE_MAP = Collections.unmodifiableMap( Collections.EMPTY_MAP ).getClass(); + private static final Class UNMODIFIABLE_COLLECTION = Collections.unmodifiableCollection( Collections.EMPTY_LIST ).getClass(); + private ShadowProxyUtils() { } @@ -41,24 +48,37 @@ public static Object cloneObject(Object original) { clone = cloneMethod.invoke( original, new Object[0] ); } catch ( Exception e ) { - // Nothing to do + /* Failed to clone. Don't worry about it, and just return + * the original object. */ } } if ( clone == null ) { try { - if ( original instanceof Map ) { + if ( original instanceof Map && + original != Collections.EMPTY_MAP && + !UNMODIFIABLE_MAP.isAssignableFrom( original.getClass() ) ) { + + /* empty and unmodifiable maps can't (and don't need to) be shadowed */ clone = original.getClass().newInstance(); ((Map) clone).putAll( (Map) original ); - } else if ( original instanceof Collection ) { + + } else if ( original instanceof Collection && + original != Collections.EMPTY_LIST && + original != Collections.EMPTY_SET && + !UNMODIFIABLE_COLLECTION.isAssignableFrom( original.getClass() ) ) { + + /* empty and unmodifiable collections can't (and don't need to) be shadowed */ clone = original.getClass().newInstance(); ((Collection) clone).addAll( (Collection) original ); + } else if ( original.getClass().isArray() ) { clone = cloneArray( original ); } + } catch ( Exception e ) { - e.printStackTrace(); - // nothing to do + /* Failed to clone. Don't worry about it, and just return + * the original object. */ } } @@ -85,10 +105,13 @@ public static Object cloneArray(Object original) { // cannot be invoked reflectively, so need to do copy construction: result = Array.newInstance( componentType, arrayLength ); - - if( componentType.isArray() ) { - for( int i = 0; i < arrayLength; i++ ) { - Array.set( result, i, cloneArray( Array.get( original, i ) ) ); + + if ( componentType.isArray() ) { + for ( int i = 0; i < arrayLength; i++ ) { + Array.set( result, + i, + cloneArray( Array.get( original, + i ) ) ); } } else { System.arraycopy( original, diff --git a/drools-core/src/test/java/org/drools/util/ShadowProxyUtilsTest.java b/drools-core/src/test/java/org/drools/util/ShadowProxyUtilsTest.java new file mode 100644 index 00000000000..47de0c7ab0a --- /dev/null +++ b/drools-core/src/test/java/org/drools/util/ShadowProxyUtilsTest.java @@ -0,0 +1,134 @@ +package org.drools.util; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +import junit.framework.TestCase; + +public class ShadowProxyUtilsTest extends TestCase { + + protected void setUp() throws Exception { + super.setUp(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + public void testCloneList() { + List list = new ArrayList(); + list.add( "a" ); + list.add( "b" ); + + List clone = (List) ShadowProxyUtils.cloneObject( list ); + assertEquals( list, + clone ); + assertNotSame( list, + clone ); + } + + public void testCloneMap() { + Map map = new TreeMap(); + map.put( "a", + "a" ); + map.put( "b", + "b" ); + + Map clone = (Map) ShadowProxyUtils.cloneObject( map ); + assertEquals( map, + clone ); + assertNotSame( map, + clone ); + } + + public void testCloneArray() { + int[][] array = new int[][]{{0, 0}, {0, 1}, {1, 0}, {1, 1}}; + + int[][] clone = (int[][]) ShadowProxyUtils.cloneObject( array ); + assertTrue( Arrays.deepEquals( array, + clone ) ); + assertNotSame( array, + clone ); + } + + public void testCloneUnmodifiableSet() { + Set set = new HashSet(); + set.add( "a" ); + set.add( "b" ); + + Set unmod = Collections.unmodifiableSet( set ); + + Set clone = (Set) ShadowProxyUtils.cloneObject( unmod ); + assertEquals( unmod, + clone ); + assertSame( unmod, + clone ); + } + + public void testCloneUnmodifiableMap() { + Map map = new TreeMap(); + map.put( "a", + "a" ); + map.put( "b", + "b" ); + Map unmod = Collections.unmodifiableMap( map ); + + Map clone = (Map) ShadowProxyUtils.cloneObject( unmod ); + assertEquals( unmod, + clone ); + assertSame( unmod, + clone ); + } + + public void testCloneEmptyList() { + List list = Collections.EMPTY_LIST; + + List clone = (List) ShadowProxyUtils.cloneObject( list ); + assertEquals( list, + clone ); + assertSame( list, + clone ); + } + + public void testCloneEmptySet() { + Set set = Collections.EMPTY_SET; + + Set clone = (Set) ShadowProxyUtils.cloneObject( set ); + assertEquals( set, + clone ); + assertSame( set, + clone ); + } + + public void testCloneEmptyMap() { + Map map = Collections.EMPTY_MAP; + + Map clone = (Map) ShadowProxyUtils.cloneObject( map ); + assertEquals( map, + clone ); + assertSame( map, + clone ); + } + + public void testCloneRegularObject() { + // this is never supposed to happen, + // but we don't want the method to blow up if it happens + Object obj = new Object(); + + Object clone = (Object) ShadowProxyUtils.cloneObject( obj ); + assertEquals( obj, + clone ); + assertSame( obj, + clone ); + + } + + + +}
1e49dcda27564e133e5528db215d8fb2d08130d0
kotlin
Extract Function: Make member/top-level function- private by default--
c
https://github.com/JetBrains/kotlin
diff --git a/idea/src/org/jetbrains/jet/plugin/refactoring/extractFunction/ui/KotlinExtractFunctionDialog.java b/idea/src/org/jetbrains/jet/plugin/refactoring/extractFunction/ui/KotlinExtractFunctionDialog.java index b94ae589d0e70..98af2355c7234 100644 --- a/idea/src/org/jetbrains/jet/plugin/refactoring/extractFunction/ui/KotlinExtractFunctionDialog.java +++ b/idea/src/org/jetbrains/jet/plugin/refactoring/extractFunction/ui/KotlinExtractFunctionDialog.java @@ -125,8 +125,7 @@ public void documentChanged(DocumentEvent event) { boolean enableVisibility = isVisibilitySectionAvailable(); visibilityBox.setEnabled(enableVisibility); if (enableVisibility) { - String visibility = originalDescriptor.getDescriptor().getVisibility(); - visibilityBox.setSelectedItem(visibility.isEmpty() ? "internal" : visibility); + visibilityBox.setSelectedItem("private"); } visibilityBox.addItemListener( new ItemListener() {
5b500c684ff416cf88937999b1205dd66d48bc67
orientdb
Removed old code to handle temporary records in- indexes--
p
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexMVRBTreeAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexMVRBTreeAbstract.java index ec82eb5bed3..be590f0944c 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexMVRBTreeAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexMVRBTreeAbstract.java @@ -17,7 +17,6 @@ import java.util.Collection; import java.util.Collections; -import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map.Entry; @@ -62,7 +61,6 @@ public abstract class OIndexMVRBTreeAbstract extends OSharedResource implements protected Set<String> clustersToIndex = new LinkedHashSet<String>(); protected OIndexCallback callback; protected boolean automatic; - protected Set<Object> tempItems = new HashSet<Object>(); @ODocumentInstance protected ODocument configuration; @@ -533,29 +531,7 @@ public void onAfterTxRollback(ODatabase iDatabase) { public void onBeforeTxCommit(ODatabase iDatabase) { } - /** - * Reset documents into the set to update its hashcode. - */ public void onAfterTxCommit(ODatabase iDatabase) { - acquireExclusiveLock(); - - try { - if (tempItems.size() > 0) { - for (Object key : tempItems) { - Set<OIdentifiable> set = map.get(key); - if (set != null) { - // RE-ADD ALL THE ITEM TO UPDATE THE HASHCODE (CHANGED AFTER SAVE+COMMIT) - final ORecordLazySet newSet = new ORecordLazySet(configuration.getDatabase()); - newSet.addAll(set); - map.put(key, newSet); - } - } - } - tempItems.clear(); - - } finally { - releaseExclusiveLock(); - } } public void onClose(ODatabase iDatabase) { diff --git a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexNotUnique.java b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexNotUnique.java index 34802bfeb47..33324ea2669 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/index/OIndexNotUnique.java +++ b/core/src/main/java/com/orientechnologies/orient/core/index/OIndexNotUnique.java @@ -43,9 +43,6 @@ public OIndex put(final Object iKey, final ORecord<?> iSingleValue) { if (!iSingleValue.getIdentity().isValid()) iSingleValue.save(); - if (iSingleValue.getIdentity().isTemporary()) - tempItems.add(iKey); - values.add(iSingleValue); map.put(iKey, values);
0531b8bff5c14d9504beefb4ad47f473e3a22932
ReactiveX-RxJava
Change hasException to hasThrowable--
p
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/Notification.java b/rxjava-core/src/main/java/rx/Notification.java index ad6b81c002..866ed06450 100644 --- a/rxjava-core/src/main/java/rx/Notification.java +++ b/rxjava-core/src/main/java/rx/Notification.java @@ -91,7 +91,7 @@ public boolean hasValue() { * * @return a value indicating whether this notification has an exception. */ - public boolean hasException() { + public boolean hasThrowable() { return isOnError() && throwable != null; } @@ -125,7 +125,7 @@ public String toString() { StringBuilder str = new StringBuilder("[").append(super.toString()).append(" ").append(getKind()); if (hasValue()) str.append(" ").append(getValue()); - if (hasException()) + if (hasThrowable()) str.append(" ").append(getThrowable().getMessage()); str.append("]"); return str.toString(); @@ -136,7 +136,7 @@ public int hashCode() { int hash = getKind().hashCode(); if (hasValue()) hash = hash * 31 + getValue().hashCode(); - if (hasException()) + if (hasThrowable()) hash = hash * 31 + getThrowable().hashCode(); return hash; } @@ -154,7 +154,7 @@ public boolean equals(Object obj) { return false; if (hasValue() && !getValue().equals(notification.getValue())) return false; - if (hasException() && !getThrowable().equals(notification.getThrowable())) + if (hasThrowable() && !getThrowable().equals(notification.getThrowable())) return false; return true; }
3d8af1b1e6726cca4ecd7d087ec79eb1ff943aff
Delta Spike
[maven-release-plugin] prepare release deltaspike-project-0.4
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/cdictrl/api/pom.xml b/deltaspike/cdictrl/api/pom.xml index 3e65f7e99..b7f0cc4e8 100644 --- a/deltaspike/cdictrl/api/pom.xml +++ b/deltaspike/cdictrl/api/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.cdictrl</groupId> <artifactId>cdictrl-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/cdictrl/impl-openejb/pom.xml b/deltaspike/cdictrl/impl-openejb/pom.xml index 63c20be9e..4a8c6a542 100644 --- a/deltaspike/cdictrl/impl-openejb/pom.xml +++ b/deltaspike/cdictrl/impl-openejb/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.cdictrl</groupId> <artifactId>cdictrl-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/cdictrl/impl-owb/pom.xml b/deltaspike/cdictrl/impl-owb/pom.xml index f1fc27193..d12ad4d3e 100644 --- a/deltaspike/cdictrl/impl-owb/pom.xml +++ b/deltaspike/cdictrl/impl-owb/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.cdictrl</groupId> <artifactId>cdictrl-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/cdictrl/impl-weld/pom.xml b/deltaspike/cdictrl/impl-weld/pom.xml index d106a7740..57117debd 100644 --- a/deltaspike/cdictrl/impl-weld/pom.xml +++ b/deltaspike/cdictrl/impl-weld/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.cdictrl</groupId> <artifactId>cdictrl-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/cdictrl/pom.xml b/deltaspike/cdictrl/pom.xml index e06050ef4..6fe4c8a6d 100644 --- a/deltaspike/cdictrl/pom.xml +++ b/deltaspike/cdictrl/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike</groupId> <artifactId>parent</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <relativePath>../parent/pom.xml</relativePath> </parent> diff --git a/deltaspike/cdictrl/tck/pom.xml b/deltaspike/cdictrl/tck/pom.xml index e54eab847..778faeca2 100644 --- a/deltaspike/cdictrl/tck/pom.xml +++ b/deltaspike/cdictrl/tck/pom.xml @@ -22,7 +22,7 @@ <parent> <groupId>org.apache.deltaspike.cdictrl</groupId> <artifactId>cdictrl-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/checkstyle-rules/pom.xml b/deltaspike/checkstyle-rules/pom.xml index f86b2d078..3ade08b4a 100644 --- a/deltaspike/checkstyle-rules/pom.xml +++ b/deltaspike/checkstyle-rules/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike</groupId> <artifactId>deltaspike-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/core/api/pom.xml b/deltaspike/core/api/pom.xml index 04d0d7f16..633ad513e 100644 --- a/deltaspike/core/api/pom.xml +++ b/deltaspike/core/api/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.core</groupId> <artifactId>core-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/core/impl/pom.xml b/deltaspike/core/impl/pom.xml index 87e0cc01f..092b4d978 100644 --- a/deltaspike/core/impl/pom.xml +++ b/deltaspike/core/impl/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.core</groupId> <artifactId>core-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/core/pom.xml b/deltaspike/core/pom.xml index 87c408f51..bd378a314 100644 --- a/deltaspike/core/pom.xml +++ b/deltaspike/core/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike</groupId> <artifactId>parent-code</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <relativePath>../parent/code/pom.xml</relativePath> </parent> diff --git a/deltaspike/examples/jse-examples/pom.xml b/deltaspike/examples/jse-examples/pom.xml index 17d46dbde..04bd7923c 100644 --- a/deltaspike/examples/jse-examples/pom.xml +++ b/deltaspike/examples/jse-examples/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.examples</groupId> <artifactId>examples-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> </parent> <groupId>org.apache.deltaspike.examples</groupId> diff --git a/deltaspike/examples/jsf-examples/pom.xml b/deltaspike/examples/jsf-examples/pom.xml index 40c4428da..519a82758 100644 --- a/deltaspike/examples/jsf-examples/pom.xml +++ b/deltaspike/examples/jsf-examples/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.examples</groupId> <artifactId>examples-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> </parent> <artifactId>deltaspike-jsf-example</artifactId> diff --git a/deltaspike/examples/pom.xml b/deltaspike/examples/pom.xml index 96c56efa2..71cb7f6bc 100644 --- a/deltaspike/examples/pom.xml +++ b/deltaspike/examples/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike</groupId> <artifactId>parent</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <relativePath>../parent/pom.xml</relativePath> </parent> diff --git a/deltaspike/modules/jpa/api/pom.xml b/deltaspike/modules/jpa/api/pom.xml index 1ff696a5d..a680cff57 100644 --- a/deltaspike/modules/jpa/api/pom.xml +++ b/deltaspike/modules/jpa/api/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>jpa-module-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> diff --git a/deltaspike/modules/jpa/impl/pom.xml b/deltaspike/modules/jpa/impl/pom.xml index 6276e006b..2b49251fb 100644 --- a/deltaspike/modules/jpa/impl/pom.xml +++ b/deltaspike/modules/jpa/impl/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>jpa-module-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> diff --git a/deltaspike/modules/jpa/pom.xml b/deltaspike/modules/jpa/pom.xml index 118ea517e..d139ab352 100644 --- a/deltaspike/modules/jpa/pom.xml +++ b/deltaspike/modules/jpa/pom.xml @@ -23,12 +23,12 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>modules-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>jpa-module-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <packaging>pom</packaging> <name>Apache DeltaSpike JPA-Module</name> diff --git a/deltaspike/modules/jsf/api/pom.xml b/deltaspike/modules/jsf/api/pom.xml index d5c4c7081..f4cb24183 100644 --- a/deltaspike/modules/jsf/api/pom.xml +++ b/deltaspike/modules/jsf/api/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>jsf-module-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> diff --git a/deltaspike/modules/jsf/impl/pom.xml b/deltaspike/modules/jsf/impl/pom.xml index 9b91dfe81..a7da307d1 100644 --- a/deltaspike/modules/jsf/impl/pom.xml +++ b/deltaspike/modules/jsf/impl/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>jsf-module-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> diff --git a/deltaspike/modules/jsf/pom.xml b/deltaspike/modules/jsf/pom.xml index 3fd60ea8e..b0a975443 100644 --- a/deltaspike/modules/jsf/pom.xml +++ b/deltaspike/modules/jsf/pom.xml @@ -23,12 +23,12 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>modules-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>jsf-module-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <packaging>pom</packaging> <name>Apache DeltaSpike JSF-Module</name> diff --git a/deltaspike/modules/partial-bean/api/pom.xml b/deltaspike/modules/partial-bean/api/pom.xml index 2221ac727..dba14d189 100644 --- a/deltaspike/modules/partial-bean/api/pom.xml +++ b/deltaspike/modules/partial-bean/api/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>partial-bean-module-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> diff --git a/deltaspike/modules/partial-bean/impl/pom.xml b/deltaspike/modules/partial-bean/impl/pom.xml index f7b7552a1..be9937650 100644 --- a/deltaspike/modules/partial-bean/impl/pom.xml +++ b/deltaspike/modules/partial-bean/impl/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>partial-bean-module-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> diff --git a/deltaspike/modules/partial-bean/pom.xml b/deltaspike/modules/partial-bean/pom.xml index 9e0b64e2d..c6cf172df 100644 --- a/deltaspike/modules/partial-bean/pom.xml +++ b/deltaspike/modules/partial-bean/pom.xml @@ -23,12 +23,12 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>modules-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>partial-bean-module-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <packaging>pom</packaging> <name>Apache DeltaSpike Partial-Bean-Module</name> diff --git a/deltaspike/modules/pom.xml b/deltaspike/modules/pom.xml index d4f1591c5..eb4ea6b54 100644 --- a/deltaspike/modules/pom.xml +++ b/deltaspike/modules/pom.xml @@ -23,13 +23,13 @@ <parent> <groupId>org.apache.deltaspike</groupId> <artifactId>parent-code</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <relativePath>../parent/code/pom.xml</relativePath> </parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>modules-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <packaging>pom</packaging> <name>Apache DeltaSpike Modules</name> diff --git a/deltaspike/modules/security/api/pom.xml b/deltaspike/modules/security/api/pom.xml index a00186480..d8a222c15 100644 --- a/deltaspike/modules/security/api/pom.xml +++ b/deltaspike/modules/security/api/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>security-module-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> diff --git a/deltaspike/modules/security/impl/pom.xml b/deltaspike/modules/security/impl/pom.xml index 59cec9854..52d6642b9 100644 --- a/deltaspike/modules/security/impl/pom.xml +++ b/deltaspike/modules/security/impl/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>security-module-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> diff --git a/deltaspike/modules/security/pom.xml b/deltaspike/modules/security/pom.xml index ad8dd2b67..93ac462f1 100644 --- a/deltaspike/modules/security/pom.xml +++ b/deltaspike/modules/security/pom.xml @@ -23,12 +23,12 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>modules-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>security-module-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <packaging>pom</packaging> <name>Apache DeltaSpike Security-Module</name> diff --git a/deltaspike/parent/code/pom.xml b/deltaspike/parent/code/pom.xml index 29ef60437..d282fcfac 100644 --- a/deltaspike/parent/code/pom.xml +++ b/deltaspike/parent/code/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike</groupId> <artifactId>parent</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/parent/pom.xml b/deltaspike/parent/pom.xml index c2ae65a94..f1b4eec26 100644 --- a/deltaspike/parent/pom.xml +++ b/deltaspike/parent/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike</groupId> <artifactId>deltaspike-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <relativePath>../pom.xml</relativePath> </parent> @@ -120,7 +120,7 @@ <deltaspike.osgi.exclude.dependencies>false</deltaspike.osgi.exclude.dependencies> <deltaspike.osgi.provide.capability /> <deltaspike.osgi.require.capability /> - <cdi.osgi.beans-managed></cdi.osgi.beans-managed> + <cdi.osgi.beans-managed /> </properties> diff --git a/deltaspike/pom.xml b/deltaspike/pom.xml index 063ec0751..6d45e7197 100644 --- a/deltaspike/pom.xml +++ b/deltaspike/pom.xml @@ -36,7 +36,7 @@ --> <groupId>org.apache.deltaspike</groupId> <artifactId>deltaspike-project</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <packaging>pom</packaging> <name>Apache DeltaSpike</name> @@ -49,7 +49,7 @@ <connection>scm:git:https://git-wip-us.apache.org/repos/asf/incubator-deltaspike.git</connection> <developerConnection>scm:git:https://git-wip-us.apache.org/repos/asf/incubator-deltaspike.git</developerConnection> <url>https://git-wip-us.apache.org/repos/asf/incubator-deltaspike.git</url> - <tag>HEAD</tag> + <tag>deltaspike-project-0.4</tag> </scm> <modules> diff --git a/deltaspike/test-utils/pom.xml b/deltaspike/test-utils/pom.xml index cdae1c324..0bc3f9128 100644 --- a/deltaspike/test-utils/pom.xml +++ b/deltaspike/test-utils/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike</groupId> <artifactId>parent</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <relativePath>../parent/pom.xml</relativePath> </parent>
bd5dbb665e1af5b3ac2f63eaea49b36377bb8b1a
kotlin
Fix header scope for secondary constructors--Add companion object's scope and nested classes-- -KT-6996 fixed-
c
https://github.com/JetBrains/kotlin
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyClassDescriptor.java b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyClassDescriptor.java index 051caf4b5a1a2..e8a947b69a0f2 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyClassDescriptor.java +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/lazy/descriptors/LazyClassDescriptor.java @@ -277,20 +277,22 @@ private JetScope computeScopeForMemberDeclarationResolution() { thisScope.setImplicitReceiver(this.getThisAsReceiverParameter()); thisScope.changeLockLevel(WritableScope.LockLevel.READING); - ClassDescriptor companionObjectDescriptor = getCompanionObjectDescriptor(); - JetScope companionObjectAdapterScope = (companionObjectDescriptor != null) ? new CompanionObjectMixinScope(companionObjectDescriptor) : JetScope.Empty.INSTANCE$; - return new ChainedScope( this, "ScopeForMemberDeclarationResolution: " + getName(), thisScope, getScopeForMemberLookup(), getScopeForClassHeaderResolution(), - companionObjectAdapterScope, + getCompanionObjectScope(), getStaticScope() ); } + private JetScope getCompanionObjectScope() { + ClassDescriptor companionObjectDescriptor = getCompanionObjectDescriptor(); + return (companionObjectDescriptor != null) ? new CompanionObjectMixinScope(companionObjectDescriptor) : JetScope.Empty.INSTANCE$; + } + @Override @NotNull public JetScope getScopeForInitializerResolution() { @@ -346,6 +348,8 @@ private JetScope computeScopeForSecondaryConstructorHeaderResolution() { this, "ScopeForSecondaryConstructorHeaderResolution: " + getName(), getScopeForClassHeaderResolution(), + getCompanionObjectScope(), + DescriptorUtils.getStaticNestedClassesScope(this), getStaticScope() ); } diff --git a/compiler/testData/codegen/box/secondaryConstructors/accessToCompanion.kt b/compiler/testData/codegen/box/secondaryConstructors/accessToCompanion.kt new file mode 100644 index 0000000000000..ec5e0bbb1e656 --- /dev/null +++ b/compiler/testData/codegen/box/secondaryConstructors/accessToCompanion.kt @@ -0,0 +1,21 @@ +class A(val result: Int) { + companion object { + fun foo(): Int = 1 + val prop = 2 + val C = 3 + } + object B { + fun bar(): Int = 4 + val prop = 5 + } + object C { + } + + constructor() : this(foo() + prop + B.bar() + B.prop + C) {} +} + +fun box(): String { + val result = A().result + if (result != 15) return "fail: $result" + return "OK" +} diff --git a/compiler/testData/diagnostics/tests/secondaryConstructors/companionObjectScope.kt b/compiler/testData/diagnostics/tests/secondaryConstructors/companionObjectScope.kt new file mode 100644 index 0000000000000..43a40a6e941eb --- /dev/null +++ b/compiler/testData/diagnostics/tests/secondaryConstructors/companionObjectScope.kt @@ -0,0 +1,17 @@ +// !DIAGNOSTICS: -UNUSED_PARAMETER +class A { + companion object { + fun foo(): Int = 1 + val prop = 2 + val C = 3 + } + object B { + fun bar(): Int = 4 + val prop = 5 + } + object C { + } + + constructor(x: Int) {} + constructor() : this(foo() + prop + B.bar() + B.prop + C) {} +} diff --git a/compiler/testData/diagnostics/tests/secondaryConstructors/companionObjectScope.txt b/compiler/testData/diagnostics/tests/secondaryConstructors/companionObjectScope.txt new file mode 100644 index 0000000000000..ce9dc54bddce6 --- /dev/null +++ b/compiler/testData/diagnostics/tests/secondaryConstructors/companionObjectScope.txt @@ -0,0 +1,35 @@ +package + +internal final class A { + public constructor A() + public constructor A(/*0*/ x: kotlin.Int) + public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean + public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int + public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String + + internal object B { + private constructor B() + internal final val prop: kotlin.Int = 5 + internal final fun bar(): kotlin.Int + public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean + public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int + public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String + } + + internal object C { + private constructor C() + public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean + public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int + public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String + } + + internal companion object Companion { + private constructor Companion() + internal final val C: kotlin.Int = 3 + internal final val prop: kotlin.Int = 2 + public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean + internal final fun foo(): kotlin.Int + public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int + public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String + } +} diff --git a/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java b/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java index c8798054dfa18..0e194f976a1c5 100644 --- a/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java +++ b/compiler/tests/org/jetbrains/kotlin/checkers/JetDiagnosticsTestGenerated.java @@ -10587,6 +10587,12 @@ public void testClassInitializersWithoutPrimary() throws Exception { doTest(fileName); } + @TestMetadata("companionObjectScope.kt") + public void testCompanionObjectScope() throws Exception { + String fileName = JetTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/secondaryConstructors/companionObjectScope.kt"); + doTest(fileName); + } + @TestMetadata("constructorCallType.kt") public void testConstructorCallType() throws Exception { String fileName = JetTestUtils.navigationMetadata("compiler/testData/diagnostics/tests/secondaryConstructors/constructorCallType.kt"); diff --git a/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxCodegenTestGenerated.java b/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxCodegenTestGenerated.java index cff58a0734824..a6be7a9c3352f 100644 --- a/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxCodegenTestGenerated.java +++ b/compiler/tests/org/jetbrains/kotlin/codegen/generated/BlackBoxCodegenTestGenerated.java @@ -6317,6 +6317,12 @@ public void testSyntheticVsReal() throws Exception { @TestDataPath("$PROJECT_ROOT") @RunWith(JUnit3RunnerWithInners.class) public static class SecondaryConstructors extends AbstractBlackBoxCodegenTest { + @TestMetadata("accessToCompanion.kt") + public void testAccessToCompanion() throws Exception { + String fileName = JetTestUtils.navigationMetadata("compiler/testData/codegen/box/secondaryConstructors/accessToCompanion.kt"); + doTest(fileName); + } + public void testAllFilesPresentInSecondaryConstructors() throws Exception { JetTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("compiler/testData/codegen/box/secondaryConstructors"), Pattern.compile("^(.+)\\.kt$"), true); }
3be0759b44c97834e6fd96ac189500aa4d58dcc1
orientdb
Fixed issue -1445 providing the new TIMEOUT in- most of the commands--
c
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutorAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutorAbstract.java index e8f9485d140..1f87da6be4c 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutorAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutorAbstract.java @@ -15,6 +15,7 @@ */ package com.orientechnologies.orient.core.command; +import java.util.Locale; import java.util.Map; import com.orientechnologies.common.listener.OProgressListener; @@ -35,8 +36,9 @@ public abstract class OCommandExecutorAbstract extends OBaseParser implements OC protected Map<Object, Object> parameters; protected OCommandContext context; - public OCommandExecutorAbstract init(final String iText) { - parserText = iText; + public OCommandExecutorAbstract init(final OCommandRequestText iRequest) { + parserText = iRequest.getText().trim(); + parserTextUpperCase = parserText.toUpperCase(Locale.ENGLISH); return this; } diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequest.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequest.java index 1fb1d707de0..920c9fbc76e 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequest.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequest.java @@ -23,6 +23,10 @@ * @param <T> */ public interface OCommandRequest { + public enum TIMEOUT_STRATEGY { + EXCEPTION, RETURN + } + public <RET> RET execute(Object... iArgs); /** @@ -40,6 +44,27 @@ public interface OCommandRequest { */ public OCommandRequest setLimit(int iLimit); + /** + * Returns the command timeout. 0 means no timeout. + * + * @return + */ + public long getTimeoutTime(); + + /** + * Returns the command timeout strategy between the defined ones. + * + * @return + */ + public TIMEOUT_STRATEGY getTimeoutStrategy(); + + /** + * Sets the command timeout. When the command execution time is major than the timeout the command returns + * + * @param timeout + */ + public void setTimeout(long timeout, TIMEOUT_STRATEGY strategy); + /** * Returns true if the command doesn't change the database, otherwise false. */ diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAbstract.java index 4c52a5849e5..fa21df7fc00 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAbstract.java @@ -19,6 +19,7 @@ import java.util.Map; import com.orientechnologies.common.listener.OProgressListener; +import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.db.record.OIdentifiable; /** @@ -31,10 +32,12 @@ public abstract class OCommandRequestAbstract implements OCommandRequestInternal { protected OCommandResultListener resultListener; protected OProgressListener progressListener; - protected int limit = -1; + protected int limit = -1; + protected long timeoutMs = OGlobalConfiguration.COMMAND_TIMEOUT.getValueAsLong(); + protected TIMEOUT_STRATEGY timeoutStrategy = TIMEOUT_STRATEGY.EXCEPTION; protected Map<Object, Object> parameters; - protected String fetchPlan = null; - protected boolean useCache = false; + protected String fetchPlan = null; + protected boolean useCache = false; protected OCommandContext context; protected OCommandRequestAbstract() { @@ -128,4 +131,17 @@ public OCommandRequestAbstract setContext(final OCommandContext iContext) { context = iContext; return this; } + + public long getTimeoutTime() { + return timeoutMs; + } + + public void setTimeout(final long timeout, TIMEOUT_STRATEGY strategy) { + this.timeoutMs = timeout; + this.timeoutStrategy = strategy; + } + + public TIMEOUT_STRATEGY getTimeoutStrategy() { + return timeoutStrategy; + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java index 5352ec9cbfc..04752630f1c 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java @@ -28,15 +28,18 @@ * @param <T> */ public interface OCommandRequestInternal extends OCommandRequest, OSerializableStream { - public Map<Object, Object> getParameters(); - public OCommandResultListener getResultListener(); + public static final String EXECUTION_BEGUN = "EXECUTION_BEGUN"; - public void setResultListener(OCommandResultListener iListener); + public Map<Object, Object> getParameters(); - public OProgressListener getProgressListener(); + public OCommandResultListener getResultListener(); - public OCommandRequestInternal setProgressListener(OProgressListener iProgressListener); + public void setResultListener(OCommandResultListener iListener); - public void reset(); + public OProgressListener getProgressListener(); + + public OCommandRequestInternal setProgressListener(OProgressListener iProgressListener); + + public void reset(); } diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestTextAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestTextAbstract.java index 732f46bece5..b4598281c83 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestTextAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestTextAbstract.java @@ -125,6 +125,11 @@ protected byte[] toStream(final OMemoryStream buffer) { buffer.set(compositeKey.toStream()); } } + + // TIMEOUT + buffer.set(timeoutMs); + buffer.set((byte) timeoutStrategy.ordinal()); + return buffer.toByteArray(); } @@ -177,6 +182,9 @@ protected void fromStream(final OMemoryStream buffer) { parameters.put(p.getKey(), value); } } + + timeoutMs = buffer.getAsLong(); + timeoutStrategy = TIMEOUT_STRATEGY.values()[buffer.getAsByte()]; } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java b/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java index 087cd68f410..dd6fc79dfea 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java +++ b/core/src/main/java/com/orientechnologies/orient/core/config/OGlobalConfiguration.java @@ -355,6 +355,9 @@ public void change(final Object iCurrentValue, final Object iNewValue) { } }), + // COMMAND + COMMAND_TIMEOUT("command.timeout", "Default timeout for commands expressed in milliseconds", Long.class, 0), + // CLIENT CLIENT_CHANNEL_MIN_POOL("client.channel.minPool", "Minimum pool size", Integer.class, 1), diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAbstract.java index 16807468731..c9801165f66 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAbstract.java @@ -15,9 +15,9 @@ */ package com.orientechnologies.orient.core.sql; -import java.util.Locale; - import com.orientechnologies.orient.core.command.OCommandExecutorAbstract; +import com.orientechnologies.orient.core.command.OCommandRequest.TIMEOUT_STRATEGY; +import com.orientechnologies.orient.core.config.OGlobalConfiguration; /** * SQL abstract Command Executor implementation. @@ -32,6 +32,7 @@ public abstract class OCommandExecutorSQLAbstract extends OCommandExecutorAbstra public static final String KEYWORD_WHERE = "WHERE"; public static final String KEYWORD_LIMIT = "LIMIT"; public static final String KEYWORD_SKIP = "SKIP"; + public static final String KEYWORD_TIMEOUT = "TIMEOUT"; public static final String KEYWORD_KEY = "key"; public static final String KEYWORD_RID = "rid"; public static final String CLUSTER_PREFIX = "CLUSTER:"; @@ -39,6 +40,9 @@ public abstract class OCommandExecutorSQLAbstract extends OCommandExecutorAbstra public static final String INDEX_PREFIX = "INDEX:"; public static final String DICTIONARY_PREFIX = "DICTIONARY:"; + protected long timeoutMs = OGlobalConfiguration.COMMAND_TIMEOUT.getValueAsLong(); + protected TIMEOUT_STRATEGY timeoutStrategy = TIMEOUT_STRATEGY.EXCEPTION; + protected void throwSyntaxErrorException(final String iText) { throw new OCommandSQLParsingException(iText + ". Use " + getSyntax(), parserText, parserGetPreviousPosition()); } @@ -47,14 +51,40 @@ protected void throwParsingException(final String iText) { throw new OCommandSQLParsingException(iText, parserText, parserGetPreviousPosition()); } - @Override - public OCommandExecutorSQLAbstract init(String iText) { - iText = iText.trim(); - parserTextUpperCase = iText.toUpperCase(Locale.ENGLISH); - return (OCommandExecutorSQLAbstract) super.init(iText); - } - public boolean isIdempotent() { return false; } + + /** + * Parses the timeout keyword if found. + */ + protected boolean parseTimeout(final String w) throws OCommandSQLParsingException { + if (!w.equals(KEYWORD_TIMEOUT)) + return false; + + parserNextWord(true); + String word = parserGetLastWord(); + + try { + timeoutMs = Long.parseLong(word); + } catch (Exception e) { + throwParsingException("Invalid " + KEYWORD_TIMEOUT + " value setted to '" + word + + "' but it should be a valid long. Example: " + KEYWORD_TIMEOUT + " 3000"); + } + + if (timeoutMs < 0) + throwParsingException("Invalid " + KEYWORD_TIMEOUT + ": value setted to less than ZERO. Example: " + timeoutMs + " 10"); + + parserNextWord(true); + word = parserGetLastWord(); + + if (word.equals(TIMEOUT_STRATEGY.EXCEPTION.toString())) + timeoutStrategy = TIMEOUT_STRATEGY.EXCEPTION; + else if (word.equals(TIMEOUT_STRATEGY.RETURN.toString())) + timeoutStrategy = TIMEOUT_STRATEGY.RETURN; + else + parserGoBack(); + + return true; + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterClass.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterClass.java index 47ad969ef18..3e04a79279f 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterClass.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterClass.java @@ -49,7 +49,7 @@ public OCommandExecutorSQLAlterClass parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterCluster.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterCluster.java index a3366c5213e..07558bf140f 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterCluster.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterCluster.java @@ -52,7 +52,8 @@ public OCommandExecutorSQLAlterCluster parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterDatabase.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterDatabase.java index d53bbfa2be6..2bdbe49bfd2 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterDatabase.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterDatabase.java @@ -47,7 +47,8 @@ public OCommandExecutorSQLAlterDatabase parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterProperty.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterProperty.java index 912bd6a0d00..0ada27949a8 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterProperty.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLAlterProperty.java @@ -49,7 +49,8 @@ public class OCommandExecutorSQLAlterProperty extends OCommandExecutorSQLAbstrac public OCommandExecutorSQLAlterProperty parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java index c1388936a59..ae245b405e7 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateClass.java @@ -50,7 +50,8 @@ public OCommandExecutorSQLCreateClass parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateCluster.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateCluster.java index 4514ff84338..6f48a91e28c 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateCluster.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateCluster.java @@ -53,7 +53,8 @@ public OCommandExecutorSQLCreateCluster parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + parserRequiredKeyword(KEYWORD_CREATE); parserRequiredKeyword(KEYWORD_CLUSTER); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateEdge.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateEdge.java index 287469ef3d0..4f1f3543687 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateEdge.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateEdge.java @@ -52,7 +52,8 @@ public OCommandExecutorSQLCreateEdge parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + parserRequiredKeyword("CREATE"); parserRequiredKeyword("EDGE"); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateFunction.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateFunction.java index 82950427733..efc5b507b80 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateFunction.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateFunction.java @@ -47,7 +47,8 @@ public OCommandExecutorSQLCreateFunction parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + parserRequiredKeyword("CREATE"); parserRequiredKeyword("FUNCTION"); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateIndex.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateIndex.java index d67a679f924..c902be41839 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateIndex.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateIndex.java @@ -63,7 +63,8 @@ public class OCommandExecutorSQLCreateIndex extends OCommandExecutorSQLAbstract public OCommandExecutorSQLCreateIndex parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + final StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateLink.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateLink.java index 04b6e2da030..6090b6e1fe0 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateLink.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateLink.java @@ -65,7 +65,8 @@ public class OCommandExecutorSQLCreateLink extends OCommandExecutorSQLAbstract { public OCommandExecutorSQLCreateLink parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateProperty.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateProperty.java index 2e6167d0aa4..280f24236f5 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateProperty.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateProperty.java @@ -49,7 +49,8 @@ public class OCommandExecutorSQLCreateProperty extends OCommandExecutorSQLAbstra public OCommandExecutorSQLCreateProperty parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateVertex.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateVertex.java index 2b6d136e260..bdb2f69200e 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateVertex.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLCreateVertex.java @@ -45,7 +45,8 @@ public OCommandExecutorSQLCreateVertex parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + String className = null; diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDelete.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDelete.java index 0accc30b62c..e25c500a2ba 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDelete.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDelete.java @@ -66,7 +66,8 @@ public OCommandExecutorSQLDelete parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + query = null; recordCount = 0; diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteEdge.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteEdge.java index b0f9c72477d..6b32adedae2 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteEdge.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteEdge.java @@ -56,7 +56,8 @@ public OCommandExecutorSQLDeleteEdge parse(final OCommandRequest iRequest) { database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + parserRequiredKeyword("DELETE"); parserRequiredKeyword("EDGE"); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteVertex.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteVertex.java index 513141f9f82..230164bfbca 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteVertex.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDeleteVertex.java @@ -49,7 +49,8 @@ public OCommandExecutorSQLDeleteVertex parse(final OCommandRequest iRequest) { database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + parserRequiredKeyword("DELETE"); parserRequiredKeyword("VERTEX"); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropClass.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropClass.java index 7df6e5af21e..4e92bd50125 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropClass.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropClass.java @@ -47,7 +47,8 @@ public class OCommandExecutorSQLDropClass extends OCommandExecutorSQLAbstract im public OCommandExecutorSQLDropClass parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + final StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropCluster.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropCluster.java index 27200afee76..1c582d974a6 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropCluster.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropCluster.java @@ -42,7 +42,8 @@ public class OCommandExecutorSQLDropCluster extends OCommandExecutorSQLAbstract public OCommandExecutorSQLDropCluster parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + final StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropIndex.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropIndex.java index d65e6b02665..81aee786a74 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropIndex.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropIndex.java @@ -40,7 +40,8 @@ public class OCommandExecutorSQLDropIndex extends OCommandExecutorSQLAbstract im public OCommandExecutorSQLDropIndex parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + final StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropProperty.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropProperty.java index 49dafedc3c4..b37cd35408f 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropProperty.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLDropProperty.java @@ -49,7 +49,8 @@ public class OCommandExecutorSQLDropProperty extends OCommandExecutorSQLAbstract public OCommandExecutorSQLDropProperty parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + final StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLFindReferences.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLFindReferences.java index 5778546619c..c1b35b5e073 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLFindReferences.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLFindReferences.java @@ -48,7 +48,8 @@ public class OCommandExecutorSQLFindReferences extends OCommandExecutorSQLEarlyR public OCommandExecutorSQLFindReferences parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + parserRequiredKeyword(KEYWORD_FIND); parserRequiredKeyword(KEYWORD_REFERENCES); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLGrant.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLGrant.java index b8407910728..1931a9fa5fa 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLGrant.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLGrant.java @@ -37,7 +37,8 @@ public class OCommandExecutorSQLGrant extends OCommandExecutorSQLPermissionAbstr public OCommandExecutorSQLGrant parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + privilege = ORole.PERMISSION_NONE; resource = null; diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLInsert.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLInsert.java index 4e755e62348..35a3c3810f8 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLInsert.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLInsert.java @@ -54,7 +54,8 @@ public OCommandExecutorSQLInsert parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + className = null; newRecords = null; diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRebuildIndex.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRebuildIndex.java index bbe7fde823d..cb40d905d96 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRebuildIndex.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRebuildIndex.java @@ -42,7 +42,8 @@ public class OCommandExecutorSQLRebuildIndex extends OCommandExecutorSQLAbstract public OCommandExecutorSQLRebuildIndex parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + final StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java index 6238be70e65..65534af6231 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLResultsetAbstract.java @@ -96,7 +96,7 @@ public OCommandExecutorSQLResultsetAbstract parse(final OCommandRequest iRequest OCommandRequestText textRequest = (OCommandRequestText) iRequest; - init(textRequest.getText()); + init(textRequest); if (iRequest instanceof OSQLSynchQuery) { request = (OSQLSynchQuery<ORecordSchemaAware<?>>) iRequest; diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRevoke.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRevoke.java index 1715ddb309b..1f008085736 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRevoke.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLRevoke.java @@ -39,7 +39,8 @@ public OCommandExecutorSQLRevoke parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + privilege = ORole.PERMISSION_NONE; resource = null; diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java index 62702f9c0fc..c4af87e5648 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLSelect.java @@ -31,10 +31,12 @@ import com.orientechnologies.common.collection.OCompositeKey; import com.orientechnologies.common.collection.OMultiValue; +import com.orientechnologies.common.concur.OTimeoutException; import com.orientechnologies.common.concur.resource.OSharedResource; import com.orientechnologies.common.util.OPair; import com.orientechnologies.orient.core.command.OBasicCommandContext; import com.orientechnologies.orient.core.command.OCommandRequest; +import com.orientechnologies.orient.core.command.OCommandRequestInternal; import com.orientechnologies.orient.core.db.record.ODatabaseRecord; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.exception.OCommandExecutionException; @@ -92,7 +94,8 @@ public class OCommandExecutorSQLSelect extends OCommandExecutorSQLResultsetAbstr public static final String KEYWORD_GROUP = "GROUP"; private Map<String, String> projectionDefinition = null; - private Map<String, Object> projections = null; // THIS HAS BEEN KEPT FOR COMPATIBILITY; BUT IT'S USED THE + private Map<String, Object> projections = null; // THIS HAS BEEN KEPT FOR COMPATIBILITY; BUT IT'S + // USED THE // PROJECTIONS IN GROUPED-RESULTS private List<OPair<String, String>> orderedFields; private List<String> groupByFields; @@ -153,6 +156,8 @@ else if (w.equals(KEYWORD_LIMIT)) parseLimit(w); else if (w.equals(KEYWORD_SKIP)) parseSkip(w); + else if (w.equals(KEYWORD_TIMEOUT)) + parseTimeout(w); else throwParsingException("Invalid keyword '" + w + "'"); } @@ -355,6 +360,10 @@ protected boolean assignTarget(Map<Object, Object> iArgs) { } protected boolean executeSearchRecord(final OIdentifiable id) { + + if (!checkTimeout()) + return false; + final ORecordInternal<?> record = id.getRecord(); context.updateMetric("recordReads", +1); @@ -373,6 +382,24 @@ protected boolean executeSearchRecord(final OIdentifiable id) { return true; } + protected boolean checkTimeout() { + if (timeoutMs > 0) { + final Long begun = (Long) context.getVariable(OCommandRequestInternal.EXECUTION_BEGUN); + if (begun != null) { + if (System.currentTimeMillis() - begun.longValue() > timeoutMs) { + // TIMEOUT! + switch (timeoutStrategy) { + case RETURN: + return false; + case EXCEPTION: + throw new OTimeoutException("Command execution timeout exceed (" + timeoutMs + "ms)"); + } + } + } + } + return true; + } + protected boolean handleResult(final OIdentifiable iRecord) { lastRecord = null; diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTraverse.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTraverse.java index b063c16579e..02a2fa91f0f 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTraverse.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTraverse.java @@ -104,6 +104,8 @@ public OCommandExecutorSQLTraverse parse(final OCommandRequest iRequest) { parseLimit(w); else if (w.equals(KEYWORD_SKIP)) parseSkip(w); + else if (w.equals(KEYWORD_TIMEOUT)) + parseTimeout(w); } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateClass.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateClass.java index 63d4adc916e..bc713db2775 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateClass.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateClass.java @@ -43,7 +43,8 @@ public OCommandExecutorSQLTruncateClass parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateCluster.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateCluster.java index 7c3079e5083..77d30763ca8 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateCluster.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateCluster.java @@ -44,7 +44,8 @@ public OCommandExecutorSQLTruncateCluster parse(final OCommandRequest iRequest) final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateRecord.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateRecord.java index 5d581d20360..49768ec3f0a 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateRecord.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLTruncateRecord.java @@ -46,7 +46,8 @@ public class OCommandExecutorSQLTruncateRecord extends OCommandExecutorSQLAbstra public OCommandExecutorSQLTruncateRecord parse(final OCommandRequest iRequest) { getDatabase().checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + StringBuilder word = new StringBuilder(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java index cc0fcfdf968..5d95038cb44 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OCommandExecutorSQLUpdate.java @@ -76,7 +76,8 @@ public OCommandExecutorSQLUpdate parse(final OCommandRequest iRequest) { final ODatabaseRecord database = getDatabase(); database.checkSecurity(ODatabaseSecurityResources.COMMAND, ORole.PERMISSION_READ); - init(((OCommandRequestText) iRequest).getText()); + init((OCommandRequestText) iRequest); + setEntries.clear(); addEntries.clear(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java index b03f1d3f998..13567cf999a 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageEmbedded.java @@ -23,6 +23,7 @@ import com.orientechnologies.orient.core.Orient; import com.orientechnologies.orient.core.command.OCommandExecutor; import com.orientechnologies.orient.core.command.OCommandManager; +import com.orientechnologies.orient.core.command.OCommandRequestInternal; import com.orientechnologies.orient.core.command.OCommandRequestText; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; @@ -92,6 +93,8 @@ public Object executeCommand(final OCommandRequestText iCommand, final OCommandE throw new OCommandExecutionException("Cannot execute non idempotent command"); long beginTime = Orient.instance().getProfiler().startChrono(); + executor.getContext().setVariable(OCommandRequestInternal.EXECUTION_BEGUN, System.currentTimeMillis()); + try { final Object result = executor.execute(iCommand.getParameters()); @@ -104,11 +107,12 @@ public Object executeCommand(final OCommandRequestText iCommand, final OCommandE throw new OCommandExecutionException("Error on execution of command: " + iCommand, e); } finally { - Orient - .instance() - .getProfiler() - .stopChrono("db." + ODatabaseRecordThreadLocal.INSTANCE.get().getName() + ".command." + iCommand.toString(), - "Command executed against the database", beginTime, "db.*.command.*"); + if (Orient.instance().getProfiler().isRecording()) + Orient + .instance() + .getProfiler() + .stopChrono("db." + ODatabaseRecordThreadLocal.INSTANCE.get().getName() + ".command." + iCommand.toString(), + "Command executed against the database", beginTime, "db.*.command.*"); } } diff --git a/object/src/main/java/com/orientechnologies/orient/object/db/OCommandSQLPojoWrapper.java b/object/src/main/java/com/orientechnologies/orient/object/db/OCommandSQLPojoWrapper.java index e7a62a66c34..2e29005b6de 100644 --- a/object/src/main/java/com/orientechnologies/orient/object/db/OCommandSQLPojoWrapper.java +++ b/object/src/main/java/com/orientechnologies/orient/object/db/OCommandSQLPojoWrapper.java @@ -109,4 +109,20 @@ public OCommandRequest setContext(final OCommandContext iContext) { command.setContext(iContext); return this; } + + @Override + public long getTimeoutTime() { + return command.getTimeoutTime(); + } + + @Override + public TIMEOUT_STRATEGY getTimeoutStrategy() { + return command.getTimeoutStrategy(); + } + + @Override + public void setTimeout(long timeout, TIMEOUT_STRATEGY strategy) { + command.setTimeout(timeout, strategy); + + } } diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java index 3b44b781188..99feabfd001 100755 --- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java +++ b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java @@ -24,6 +24,7 @@ import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; + import com.orientechnologies.common.io.OIOException; import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.OConstants; @@ -326,15 +327,15 @@ protected boolean executeRequest() throws IOException { releaseDatabase(); break; - case OChannelBinaryProtocol.REQUEST_DATACLUSTER_FREEZE: - freezeCluster(); - break; + case OChannelBinaryProtocol.REQUEST_DATACLUSTER_FREEZE: + freezeCluster(); + break; - case OChannelBinaryProtocol.REQUEST_DATACLUSTER_RELEASE: - releaseCluster(); - break; + case OChannelBinaryProtocol.REQUEST_DATACLUSTER_RELEASE: + releaseCluster(); + break; - case OChannelBinaryProtocol.REQUEST_RECORD_CLEAN_OUT: + case OChannelBinaryProtocol.REQUEST_RECORD_CLEAN_OUT: cleanOutRecord(); break; @@ -1125,6 +1126,12 @@ protected void command() throws IOException { final Map<String, Integer> fetchPlan = command != null ? OFetchHelper.buildFetchPlan(command.getFetchPlan()) : null; command.setResultListener(new AsyncResultListener(empty, clientTxId, fetchPlan, recordsToSend)); + final long serverTimeout = OGlobalConfiguration.COMMAND_TIMEOUT.getValueAsLong(); + + if (serverTimeout > 0 && command.getTimeoutTime() > serverTimeout) + // FORCE THE SERVER'S TIMEOUT + command.setTimeout(serverTimeout, command.getTimeoutStrategy()); + ((OCommandRequestInternal) connection.database.command(command)).execute(); if (empty.get())
875c9d62c6db32aca16201c369d972bcf4a38dbd
hadoop
HADOOP-6441. Protect web ui from cross site- scripting attacks (XSS) on the host http header and using encoded utf-7.- (omalley)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@891132 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hadoop
diff --git a/CHANGES.txt b/CHANGES.txt index b9b935d2d137d..dca7ac29771d4 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1222,6 +1222,9 @@ Release 0.21.0 - Unreleased HADOOP-6375. Sync documentation for FsShell du with its implementation. (Todd Lipcon via cdouglas) + HADOOP-6441. Protect web ui from cross site scripting attacks (XSS) on + the host http header and using encoded utf-7. (omalley) + Release 0.20.2 - Unreleased NEW FEATURES diff --git a/src/java/org/apache/hadoop/http/HttpServer.java b/src/java/org/apache/hadoop/http/HttpServer.java index 0257141b8e3b5..4123923abb395 100644 --- a/src/java/org/apache/hadoop/http/HttpServer.java +++ b/src/java/org/apache/hadoop/http/HttpServer.java @@ -624,6 +624,25 @@ public Map<String, String[]> getParameterMap() { } return result; } + + /** + * Quote the url so that users specifying the HOST HTTP header + * can't inject attacks. + */ + @Override + public StringBuffer getRequestURL(){ + String url = rawRequest.getRequestURL().toString(); + return new StringBuffer(HtmlQuoting.quoteHtmlChars(url)); + } + + /** + * Quote the server name so that users specifying the HOST HTTP header + * can't inject attacks. + */ + @Override + public String getServerName() { + return HtmlQuoting.quoteHtmlChars(rawRequest.getServerName()); + } } @Override @@ -641,6 +660,10 @@ public void doFilter(ServletRequest request, ) throws IOException, ServletException { HttpServletRequestWrapper quoted = new RequestQuoter((HttpServletRequest) request); + final HttpServletResponse httpResponse = (HttpServletResponse) response; + // set the default to UTF-8 so that we don't need to worry about IE7 + // choosing to interpret the special characters as UTF-7 + httpResponse.setContentType("text/html;charset=utf-8"); chain.doFilter(quoted, response); }
40f2ca089b1afec3842f70653aa6150d4ceff273
Search_api
Issue #2100191 by drunken monkey, Bojhan: Added an admin description to the Search API landing page.
a
https://github.com/lucidworks/drupal_search_api
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 5d9f3501..d382f21f 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,5 +1,7 @@ Search API 1.x, dev (xx/xx/xxxx): --------------------------------- +- #2100191 by drunken monkey, Bojhan: Added an admin description to the Search + API landing page. Search API 1.9 (10/23/2013): ---------------------------- diff --git a/search_api.module b/search_api.module index 3faf2d02..395a230b 100644 --- a/search_api.module +++ b/search_api.module @@ -153,6 +153,16 @@ function search_api_menu() { return $items; } +/** + * Implements hook_help(). + */ +function search_api_help($path) { + switch ($path) { + case 'admin/config/search/search_api': + return '<p>' . t('A search server and search index are used to execute searches. Several indexes can exist per server.<br />You need at least one server and one index to create searches on your site.') . '</p>'; + } +} + /** * Implements hook_hook_info(). */
6bf0a3d3c115164601e9d5877e8a80e2cc779d99
apache$maven-plugins
o Finished MNG-632. Note: I'm not sure wheter my tmpDir approach is the best. It's certain to work all the time (depending on FileUtils.createTempFile), but it may leave a lot of 'garbage' in target/. o Updated maven-core's assembly descriptor to make use of new line endings functionality. git-svn-id: https://svn.apache.org/repos/asf/maven/components/trunk/maven-plugins@267344 13f79535-47bb-0310-9956-ffa450edef68
p
https://github.com/apache/maven-plugins
diff --git a/maven-assembly-plugin/src/main/java/org/apache/maven/plugin/assembly/AssemblyMojo.java b/maven-assembly-plugin/src/main/java/org/apache/maven/plugin/assembly/AssemblyMojo.java index c2e9d49c6d..b2de516d26 100755 --- a/maven-assembly-plugin/src/main/java/org/apache/maven/plugin/assembly/AssemblyMojo.java +++ b/maven-assembly-plugin/src/main/java/org/apache/maven/plugin/assembly/AssemblyMojo.java @@ -34,12 +34,17 @@ import org.codehaus.plexus.archiver.jar.JarArchiver; import org.codehaus.plexus.archiver.tar.TarArchiver; import org.codehaus.plexus.archiver.zip.ZipArchiver; +import org.codehaus.plexus.util.DirectoryScanner; +import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.introspection.ReflectionValueExtractor; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; +import java.io.BufferedReader; +import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; +import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -96,6 +101,13 @@ public class AssemblyMojo */ private MavenProjectHelper projectHelper; + /** + * @parameter expression="${project.build.directory}/archive-tmp" + * @required + * @readonly + */ + private File tempRoot; + public void execute() throws MojoExecutionException @@ -255,6 +267,16 @@ private void processFileSets( Archiver archiver, List fileSets, boolean includeB String directory = fileSet.getDirectory(); String output = fileSet.getOutputDirectory(); + String lineEnding = getLineEndingCharacters( fileSet.getLineEnding() ); + + File tmpDir = null; + + if ( lineEnding != null ) + { + tmpDir = FileUtils.createTempFile( "", "", tempRoot ); + tmpDir.mkdirs(); + } + archiver.setDefaultDirectoryMode( Integer.parseInt( fileSet.getDirectoryMode(), 8 ) ); @@ -263,7 +285,8 @@ private void processFileSets( Archiver archiver, List fileSets, boolean includeB getLog().debug("FileSet["+output+"]" + " dir perms: " + Integer.toString( archiver.getDefaultDirectoryMode(), 8 ) + - " file perms: " + Integer.toString( archiver.getDefaultFileMode(), 8 ) ); + " file perms: " + Integer.toString( archiver.getDefaultFileMode(), 8 ) + + ( fileSet.getLineEnding() == null ? "" : " lineEndings: " + fileSet.getLineEnding() ) ); if ( directory == null ) { @@ -287,16 +310,26 @@ private void processFileSets( Archiver archiver, List fileSets, boolean includeB { includes = null; } - + + // TODO: default excludes should be in the archiver? List excludesList = fileSet.getExcludes(); excludesList.addAll( getDefaultExcludes() ); String[] excludes = (String[]) excludesList.toArray( EMPTY_STRING_ARRAY ); - // TODO: default excludes should be in the archiver? - archiver.addDirectory( new File( directory ), output, includes, excludes ); + + File archiveBaseDir = new File( directory ); + + if ( lineEnding != null ) + { + copySetReplacingLineEndings( archiveBaseDir, tmpDir, includes, excludes, lineEnding ); + + archiveBaseDir = tmpDir; + } + + archiver.addDirectory( archiveBaseDir, output, includes, excludes ); } } - + private static String evaluateFileNameMapping( String expression, Artifact artifact ) throws MojoExecutionException { @@ -462,4 +495,90 @@ public static List getDefaultExcludes() return defaultExcludes; } + private void copyReplacingLineEndings( File source, File dest, String lineEndings ) + throws IOException + { + getLog().debug( "Copying while replacing line endings: " + source + " to " + dest ); + + BufferedReader in = new BufferedReader( new FileReader ( source ) ); + BufferedWriter out = new BufferedWriter ( new FileWriter( dest ) ); + + String line; + + while ( ( line = in.readLine()) != null ) + { + out.write( line ); + out.write( lineEndings ); + } + out.flush(); + out.close(); + } + + + private void copySetReplacingLineEndings( File archiveBaseDir, File tmpDir, String[] includes, String[] excludes, String lineEnding ) + throws ArchiverException + { + DirectoryScanner scanner = new DirectoryScanner(); + scanner.setBasedir( archiveBaseDir.getAbsolutePath() ); + scanner.setIncludes( includes ); + scanner.setExcludes( excludes ); + scanner.scan(); + + String [] dirs = scanner.getIncludedDirectories(); + + for ( int j = 0; j < dirs.length; j ++) + { + new File( tempRoot, dirs[j] ).mkdirs(); + } + + String [] files = scanner.getIncludedFiles(); + + for ( int j = 0; j < files.length; j ++) + { + File targetFile = new File( tmpDir, files[j] ); + + try + { + targetFile.getParentFile().mkdirs(); + + copyReplacingLineEndings( new File( archiveBaseDir, files[j] ), targetFile, lineEnding ); + } + catch (IOException e) + { + throw new ArchiverException("Error copying file '" + + files[j] + "' to '" + targetFile + "'", e); + } + } + + } + + + private static String getLineEndingCharacters( String lineEnding ) + throws ArchiverException + { + if ( lineEnding != null ) + { + if ( lineEnding.equals( "keep" ) ) + { + lineEnding = null; + } + else if ( lineEnding.equals( "dos" ) || lineEnding.equals( "crlf" ) ) + { + lineEnding = "\r\n"; + } + else if ( lineEnding.equals( "unix" ) || lineEnding.equals( "lf" ) ) + { + lineEnding = "\n"; + } + else + { + throw new ArchiverException( "Illlegal lineEnding specified: '" + + lineEnding + "'"); + } + } + + return lineEnding; + } + + } diff --git a/maven-assembly-plugin/src/main/mdo/descriptor.mdo b/maven-assembly-plugin/src/main/mdo/descriptor.mdo index 8f6788a5fd..63b6e8cef7 100644 --- a/maven-assembly-plugin/src/main/mdo/descriptor.mdo +++ b/maven-assembly-plugin/src/main/mdo/descriptor.mdo @@ -104,6 +104,12 @@ <type>String</type> <required>true</required> </field> + <field> + <name>lineEnding</name> + <version>1.0.0</version> + <type>String</type> + <!-- keep | unix | lf | dos | crlf --> + </field> </fields> </class> <class> @@ -129,12 +135,6 @@ <defaultValue>runtime</defaultValue> <required>true</required> </field> - <field> - <name>lineEndings</name> - <version>1.0.0</version> - <type>String</type> - <!-- native, cr, lf, crlf, ..? --> - </field> </fields> </class> </classes>
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; }
9c4dbe7edf5eb277d91c04ae77e6c5e87721d3d3
constretto$constretto-core
o Made changes so that one application using constretto was able to be ported to this trunk without any broken functionality.. So now the new constretto actually are feature complete in regards to what was supported in staged-spring :)
p
https://github.com/constretto/constretto-core
diff --git a/constretto-core/src/main/java/org/constretto/internal/converter/ValueConverterRegistry.java b/constretto-core/src/main/java/org/constretto/internal/converter/ValueConverterRegistry.java index e5c9c416..bcadef94 100644 --- a/constretto-core/src/main/java/org/constretto/internal/converter/ValueConverterRegistry.java +++ b/constretto-core/src/main/java/org/constretto/internal/converter/ValueConverterRegistry.java @@ -29,12 +29,19 @@ public class ValueConverterRegistry { private static final Map<Class<?>, ValueConverter<?>> converters = new HashMap<Class<?>, ValueConverter<?>>() { { put(Boolean.class, new BooleanValueConverter()); + put(boolean.class, new BooleanValueConverter()); put(Float.class, new FloatValueConverter()); + put(float.class, new FloatValueConverter()); put(Double.class, new DoubleValueConverter()); + put(double.class, new DoubleValueConverter()); put(Long.class, new LongValueConverter()); + put(long.class, new LongValueConverter()); put(Integer.class, new IntegerValueConverter()); + put(int.class, new IntegerValueConverter()); put(Byte.class, new ByteValueConverter()); + put(byte.class, new ByteValueConverter()); put(Short.class, new ShortValueConverter()); + put(short.class, new ShortValueConverter()); put(String.class, new StringValueConverter()); put(Resource.class, new SpringResourceValueConverter()); put(File.class, new FileValueConverter()); @@ -47,6 +54,7 @@ public static void registerCustomConverter(Class<?> converterFor, ValueConverter @SuppressWarnings("unchecked") public static <T> T convert(Class<T> clazz, String value) throws ConstrettoException { + if (!converters.containsKey(clazz)) { throw new ConstrettoException("No converter found for class: " + clazz.getName()); } diff --git a/constretto-core/src/main/java/org/constretto/internal/provider/ConfigurationProvider.java b/constretto-core/src/main/java/org/constretto/internal/provider/ConfigurationProvider.java index a6e5fbee..0a1b454e 100644 --- a/constretto-core/src/main/java/org/constretto/internal/provider/ConfigurationProvider.java +++ b/constretto-core/src/main/java/org/constretto/internal/provider/ConfigurationProvider.java @@ -23,7 +23,6 @@ import org.constretto.resolver.ConfigurationContextResolver; import java.util.ArrayList; -import static java.util.Arrays.asList; import java.util.Collection; import java.util.List; import java.util.Map; @@ -39,22 +38,9 @@ public class ConfigurationProvider { public ConfigurationProvider() { } - private ConfigurationProvider(ConfigurationStore... configurationStores) { - this.configurationStores = asList(configurationStores); - } - - public ConfigurationProvider(ConfigurationContextResolver configurationContextResolver) { - this.tags = configurationContextResolver.getTags(); - } - - public ConfigurationProvider(List<String> tags, List<ConfigurationStore> configurationStores) { - this(configurationStores.toArray(new ConfigurationStore[configurationStores.size()])); - this.tags = tags; - } - public ConfigurationProvider(ConfigurationContextResolver resolver, List<ConfigurationStore> configurationStores) { - this(configurationStores.toArray(new ConfigurationStore[configurationStores.size()])); - this.tags.addAll(resolver.getTags()); + this.configurationStores = configurationStores; + setConfigurationContextResolver(resolver); } public ConfigurationProvider addTag(String tag) { @@ -62,9 +48,8 @@ public ConfigurationProvider addTag(String tag) { return this; } - public ConfigurationProvider setConfigurationContextResolver(ConfigurationContextResolver configurationContextResolver) { + public void setConfigurationContextResolver(ConfigurationContextResolver configurationContextResolver) { this.tags.addAll(configurationContextResolver.getTags()); - return this; } public ConfigurationProvider addConfigurationStore(ConfigurationStore configurationStore) { diff --git a/constretto-core/src/main/java/org/constretto/internal/store/PropertiesStore.java b/constretto-core/src/main/java/org/constretto/internal/store/PropertiesStore.java index 878e4748..c3d703f2 100644 --- a/constretto-core/src/main/java/org/constretto/internal/store/PropertiesStore.java +++ b/constretto-core/src/main/java/org/constretto/internal/store/PropertiesStore.java @@ -76,10 +76,12 @@ private void addPropertiesToMap(Properties... props) { private void addResourcesAsProperties(Resource... resources) { for (Resource r : resources) { try { - InputStream is = r.getInputStream(); - Properties props = new Properties(); - props.load(is); - addPropertiesToMap(props); + if (r.exists()) { + InputStream is = r.getInputStream(); + Properties props = new Properties(); + props.load(is); + addPropertiesToMap(props); + } } catch (IOException e) { throw new ConstrettoException(e); } diff --git a/constretto-core/src/test/java/org/constretto/internal/provider/ConfigurationAnnotationsTest.java b/constretto-core/src/test/java/org/constretto/internal/provider/ConfigurationAnnotationsTest.java index 0404fa7e..4d7ae481 100644 --- a/constretto-core/src/test/java/org/constretto/internal/provider/ConfigurationAnnotationsTest.java +++ b/constretto-core/src/test/java/org/constretto/internal/provider/ConfigurationAnnotationsTest.java @@ -20,6 +20,7 @@ import org.constretto.ConstrettoConfiguration; import org.constretto.internal.provider.helper.ConfiguredUsingDefaults; import org.constretto.internal.provider.helper.DataSourceConfiguration; +import org.constretto.internal.provider.helper.DataSourceConfigurationWithNatives; import org.junit.Before; import org.junit.Test; @@ -65,6 +66,14 @@ public void applyConfigrationToAnnotatedConfigurationObject() { assertEquals(new Integer(10), customerDataSource.getVersion()); } + @Test + public void applyConfigrationToAnnotatedConfigurationObjectUsingNativeTypes() { + DataSourceConfigurationWithNatives customerDataSource = new DataSourceConfigurationWithNatives(); + configuration.at("datasources").from("customer").on(customerDataSource); + assertEquals(10, customerDataSource.getVersion()); + assertEquals(10, customerDataSource.getOtherVersion()); + } + @Test public void applyConfigurationWithDefaultValues() { ConfiguredUsingDefaults configuredObject = new ConfiguredUsingDefaults(); diff --git a/constretto-core/src/test/java/org/constretto/internal/provider/helper/DataSourceConfigurationWithNatives.java b/constretto-core/src/test/java/org/constretto/internal/provider/helper/DataSourceConfigurationWithNatives.java new file mode 100644 index 00000000..adb654e6 --- /dev/null +++ b/constretto-core/src/test/java/org/constretto/internal/provider/helper/DataSourceConfigurationWithNatives.java @@ -0,0 +1,45 @@ +/* + * Copyright 2008 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.constretto.internal.provider.helper; + +import org.constretto.annotation.Configuration; +import org.constretto.annotation.Configure; + +/** + * @author <a href="mailto:[email protected]">Kaare Nilsen</a> + */ +public class DataSourceConfigurationWithNatives { + + private int version; + + @Configuration(expression = "version") + private int otherVersion; + + + @Configure + public void configureMe(@Configuration int version) { + this.version = version; + } + + + public int getVersion() { + return version; + } + + public int getOtherVersion() { + return otherVersion; + } +} \ No newline at end of file diff --git a/constretto-spring/src/main/java/org/constretto/spring/ConfigurationAnnotationBeanPostProcessor.java b/constretto-spring/src/main/java/org/constretto/spring/ConfigurationAnnotationBeanPostProcessor.java index 19451fdb..6d639fb6 100755 --- a/constretto-spring/src/main/java/org/constretto/spring/ConfigurationAnnotationBeanPostProcessor.java +++ b/constretto-spring/src/main/java/org/constretto/spring/ConfigurationAnnotationBeanPostProcessor.java @@ -25,6 +25,7 @@ import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Field; @@ -46,7 +47,7 @@ * @see Configuration * @see Environment */ -public class ConfigurationAnnotationBeanPostProcessor implements BeanPostProcessor { +public class ConfigurationAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter { private ConstrettoConfiguration configuration; private AssemblyContextResolver assemblyContextResolver; @@ -65,10 +66,11 @@ public ConfigurationAnnotationBeanPostProcessor(ConstrettoConfiguration configur } - public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + @Override + public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException { injectConfiguration(bean); autowireEnvironment(bean); - return bean; + return true; } public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { @@ -103,7 +105,7 @@ private void updateProperty(Object beanInstance, Field field, String newValue) t if (field.getType().isEnum()) { Object[] enumConstants = field.getType().getEnumConstants(); for (Object enumConstant : enumConstants) { - if (enumConstant.toString().equals(newValue)){ + if (enumConstant.toString().equals(newValue)) { convertedValue = enumConstant; } } @@ -113,7 +115,4 @@ private void updateProperty(Object beanInstance, Field field, String newValue) t field.set(beanInstance, convertedValue); } - - - } diff --git a/constretto-spring/src/main/java/org/constretto/spring/ConstrettoConfigurationFactoryBean.java b/constretto-spring/src/main/java/org/constretto/spring/ConstrettoConfigurationFactoryBean.java index c75f7739..b445fef6 100644 --- a/constretto-spring/src/main/java/org/constretto/spring/ConstrettoConfigurationFactoryBean.java +++ b/constretto-spring/src/main/java/org/constretto/spring/ConstrettoConfigurationFactoryBean.java @@ -19,6 +19,8 @@ import org.constretto.ConstrettoConfiguration; import org.constretto.internal.provider.ConfigurationProvider; import org.constretto.internal.resolver.DefaultConfigurationContextResolver; +import org.constretto.internal.store.SystemPropertiesStore; +import org.constretto.resolver.ConfigurationContextResolver; import org.springframework.beans.factory.FactoryBean; import java.util.List; @@ -28,14 +30,20 @@ */ public class ConstrettoConfigurationFactoryBean implements FactoryBean { - private List<ConfigurationStore> stores; + private final List<ConfigurationStore> stores; + private ConfigurationContextResolver configurationContextResolver; + private boolean systemPropertiesOverrides = true; public ConstrettoConfigurationFactoryBean(List<ConfigurationStore> stores) { this.stores = stores; } public Object getObject() throws Exception { - ConfigurationProvider configurationProvider = new ConfigurationProvider(new DefaultConfigurationContextResolver(), stores); + ConfigurationContextResolver contextResolver = configurationContextResolver == null ? new DefaultConfigurationContextResolver() : configurationContextResolver; + if (systemPropertiesOverrides) { + stores.add(new SystemPropertiesStore()); + } + ConfigurationProvider configurationProvider = new ConfigurationProvider(contextResolver, stores); return configurationProvider.getConfiguration(); } @@ -46,4 +54,12 @@ public Class getObjectType() { public boolean isSingleton() { return true; } + + public void setConfigurationContextResolver(ConfigurationContextResolver configurationContextResolver) { + this.configurationContextResolver = configurationContextResolver; + } + + public void setSystemPropertiesOverrides(boolean systemPropertiesOverrides) { + this.systemPropertiesOverrides = systemPropertiesOverrides; + } } diff --git a/constretto-spring/src/test/java/org/constretto/spring/configuration/EnvironmentAnnotatedFieldTest.java b/constretto-spring/src/test/java/org/constretto/spring/configuration/EnvironmentAnnotatedFieldTest.java index b330740f..7ff31be4 100755 --- a/constretto-spring/src/test/java/org/constretto/spring/configuration/EnvironmentAnnotatedFieldTest.java +++ b/constretto-spring/src/test/java/org/constretto/spring/configuration/EnvironmentAnnotatedFieldTest.java @@ -11,12 +11,11 @@ package org.constretto.spring.configuration; import static junit.framework.Assert.assertEquals; -import static org.constretto.spring.configuration.EnvironmentAnnotatedFieldTest.MyEnvironments.development; - import org.constretto.annotation.Environment; +import org.constretto.internal.provider.ConfigurationProvider; import org.constretto.spring.ConfigurationAnnotationBeanPostProcessor; import org.constretto.spring.assembly.helper.AlwaysDevelopmentEnvironmentResolver; -import org.constretto.internal.provider.ConfigurationProvider; +import static org.constretto.spring.configuration.EnvironmentAnnotatedFieldTest.MyEnvironments.development; import org.junit.Test; /** @@ -28,8 +27,8 @@ public class EnvironmentAnnotatedFieldTest { public void givenClassWithEnvironmentAnnotatedPropertyThenInjectEnvironment() throws Exception { TestClazz testClazz = new TestClazz(); ConfigurationAnnotationBeanPostProcessor annotationBeanPostProcessor = new ConfigurationAnnotationBeanPostProcessor( - new ConfigurationProvider().getConfiguration(),new AlwaysDevelopmentEnvironmentResolver()); - annotationBeanPostProcessor.postProcessBeforeInitialization(testClazz, "testBean"); + new ConfigurationProvider().getConfiguration(), new AlwaysDevelopmentEnvironmentResolver()); + annotationBeanPostProcessor.postProcessAfterInstantiation(testClazz, "testBean"); assertEquals(development, testClazz.getEnvironment()); assertEquals("development", testClazz.getEnvironmentAsString()); } @@ -50,7 +49,7 @@ public String getEnvironmentAsString() { } public enum MyEnvironments { - development, test; + development, test } }
747ce871172baf71ecc0eb8c86f5a0aa4f624b4f
intellij-community
StackOverflow fixed--
c
https://github.com/JetBrains/intellij-community
diff --git a/source/com/intellij/codeInsight/completion/Java15CompletionData.java b/source/com/intellij/codeInsight/completion/Java15CompletionData.java index 59328a9f08295..87dc6862ace7f 100644 --- a/source/com/intellij/codeInsight/completion/Java15CompletionData.java +++ b/source/com/intellij/codeInsight/completion/Java15CompletionData.java @@ -77,7 +77,7 @@ public boolean isAcceptable(Object element, PsiElement context) { }, 2) ))); final CompletionVariant variant = new CompletionVariant(PsiReferenceExpression.class, position); - variant.addCompletionFilterOnElement(new ClassFilter(PsiEnumConstant.class), TailType.COND_EXPR_COLON); + variant.addCompletionFilterOnElement(new ClassFilter(PsiEnumConstant.class), ':'); registerVariant(variant); } }
615adaba0cdfa8685039f4eb0765df053deead9c
restlet-framework-java
Fixed range issue -607.--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet.test/src/org/restlet/test/data/RangeTestCase.java b/modules/org.restlet.test/src/org/restlet/test/data/RangeTestCase.java index 2e97420ce8..b34582859c 100644 --- a/modules/org.restlet.test/src/org/restlet/test/data/RangeTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/data/RangeTestCase.java @@ -266,6 +266,15 @@ public void testGet() throws Exception { assertEquals(2, response.getEntity().getRange().getIndex()); assertEquals(8, response.getEntity().getRange().getSize()); + request.setRanges(Arrays.asList(new Range(2, 1000))); + response = client.handle(request); + assertEquals(Status.SUCCESS_PARTIAL_CONTENT, response.getStatus()); + assertEquals("34567890", response.getEntity().getText()); + assertEquals(10, response.getEntity().getSize()); + assertEquals(8, response.getEntity().getAvailableSize()); + assertEquals(2, response.getEntity().getRange().getIndex()); + assertEquals(8, response.getEntity().getRange().getSize()); + client.stop(); } diff --git a/modules/org.restlet/src/org/restlet/engine/application/RangeFilter.java b/modules/org.restlet/src/org/restlet/engine/application/RangeFilter.java index eea7b61abb..ecbef8ecd0 100644 --- a/modules/org.restlet/src/org/restlet/engine/application/RangeFilter.java +++ b/modules/org.restlet/src/org/restlet/engine/application/RangeFilter.java @@ -106,6 +106,12 @@ protected void afterHandle(Request request, Response response) { .info("The range of the response entity is not equal to the requested one."); } + if (response.getEntity().hasKnownSize() + && requestedRange.getSize() > response + .getEntity().getAvailableSize()) { + requestedRange.setSize(Range.SIZE_MAX); + } + response.setEntity(new RangeRepresentation( response.getEntity(), requestedRange)); response.setStatus(Status.SUCCESS_PARTIAL_CONTENT);
5ac8276168694053d9fc5357793651f139e9390b
hadoop
MAPREDUCE-3392. Fixed Cluster's- getDelegationToken's API to return null when there isn't a supported token.- Contributed by John George. svn merge -c r1200484 --ignore-ancestry- ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.23@1200485 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hadoop
diff --git a/hadoop-mapreduce-project/CHANGES.txt b/hadoop-mapreduce-project/CHANGES.txt index 535024c007377..8f8e3ec50df53 100644 --- a/hadoop-mapreduce-project/CHANGES.txt +++ b/hadoop-mapreduce-project/CHANGES.txt @@ -57,6 +57,9 @@ Release 0.23.1 - Unreleased which per-container connections to NodeManager were lingering long enough to hit the ulimits on number of processes. (vinodkv) + MAPREDUCE-3392. Fixed Cluster's getDelegationToken's API to return null + when there isn't a supported token. (John George via vinodkv) + Release 0.23.0 - 2011-11-01 INCOMPATIBLE CHANGES diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java index 460202167ddcd..4828ebacaa014 100644 --- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java +++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/Cluster.java @@ -390,6 +390,11 @@ public long getTaskTrackerExpiryInterval() throws IOException, getDelegationToken(Text renewer) throws IOException, InterruptedException{ Token<DelegationTokenIdentifier> result = client.getDelegationToken(renewer); + + if (result == null) { + return result; + } + InetSocketAddress addr = Master.getMasterAddress(conf); StringBuilder service = new StringBuilder(); service.append(NetUtils.normalizeHostName(addr.getAddress(). diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TestYarnClientProtocolProvider.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TestYarnClientProtocolProvider.java index 2bc9030bf85ea..490b7a546e684 100644 --- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TestYarnClientProtocolProvider.java +++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TestYarnClientProtocolProvider.java @@ -25,6 +25,7 @@ import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapred.YARNRunner; import org.apache.hadoop.mapreduce.protocol.ClientProtocol; +import org.apache.hadoop.io.Text; import org.junit.Test; public class TestYarnClientProtocolProvider extends TestCase { @@ -56,4 +57,23 @@ public void testClusterWithYarnClientProtocolProvider() throws Exception { } } } + + + @Test + public void testClusterGetDelegationToken() throws Exception { + + Configuration conf = new Configuration(false); + Cluster cluster = null; + try { + conf = new Configuration(); + conf.set(MRConfig.FRAMEWORK_NAME, MRConfig.YARN_FRAMEWORK_NAME); + cluster = new Cluster(conf); + cluster.getDelegationToken(new Text(" ")); + } finally { + if (cluster != null) { + cluster.close(); + } + } + } + }
66de48a353197903c0b45c4af25be24c5588cfe1
hadoop
HDFS-2500. Avoid file system operations in- BPOfferService thread while processing deletes. Contributed by Todd Lipcon.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.23@1190072 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/hadoop
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt index 2ce3a9765a8ce..9a0ecbea52e77 100644 --- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt +++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt @@ -761,6 +761,9 @@ Release 0.23.0 - Unreleased HDFS-2118. Couple dfs data dir improvements. (eli) + HDFS-2500. Avoid file system operations in BPOfferService thread while + processing deletes. (todd) + BUG FIXES HDFS-2344. Fix the TestOfflineEditsViewer test failure in 0.23 branch. diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java index eb953ab7eb241..3f7733608999c 100644 --- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java +++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java @@ -1108,8 +1108,15 @@ private void offerService() throws Exception { if (!heartbeatsDisabledForTests) { DatanodeCommand[] cmds = sendHeartBeat(); metrics.addHeartbeat(now() - startTime); + + long startProcessCommands = now(); if (!processCommand(cmds)) continue; + long endProcessCommands = now(); + if (endProcessCommands - startProcessCommands > 2000) { + LOG.info("Took " + (endProcessCommands - startProcessCommands) + + "ms to process " + cmds.length + " commands from NN"); + } } } diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDataset.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDataset.java index 08b40fed2aae4..53c5525908440 100644 --- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDataset.java +++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDataset.java @@ -2088,10 +2088,9 @@ public void invalidate(String bpid, Block invalidBlks[]) throws IOException { volumeMap.remove(bpid, invalidBlks[i]); } File metaFile = getMetaFile(f, invalidBlks[i].getGenerationStamp()); - long dfsBytes = f.length() + metaFile.length(); // Delete the block asynchronously to make sure we can do it fast enough - asyncDiskService.deleteAsync(v, bpid, f, metaFile, dfsBytes, + asyncDiskService.deleteAsync(v, bpid, f, metaFile, invalidBlks[i].toString()); } if (error) { diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDatasetAsyncDiskService.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDatasetAsyncDiskService.java index 176f8825d9fb2..0c2523b834176 100644 --- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDatasetAsyncDiskService.java +++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FSDatasetAsyncDiskService.java @@ -148,11 +148,11 @@ synchronized void shutdown() { * dfsUsed statistics accordingly. */ void deleteAsync(FSDataset.FSVolume volume, String bpid, File blockFile, - File metaFile, long dfsBytes, String blockName) { + File metaFile, String blockName) { DataNode.LOG.info("Scheduling block " + blockName + " file " + blockFile + " for deletion"); ReplicaFileDeleteTask deletionTask = - new ReplicaFileDeleteTask(volume, bpid, blockFile, metaFile, dfsBytes, + new ReplicaFileDeleteTask(volume, bpid, blockFile, metaFile, blockName); execute(volume.getCurrentDir(), deletionTask); } @@ -165,16 +165,14 @@ static class ReplicaFileDeleteTask implements Runnable { final String blockPoolId; final File blockFile; final File metaFile; - final long dfsBytes; final String blockName; ReplicaFileDeleteTask(FSDataset.FSVolume volume, String bpid, - File blockFile, File metaFile, long dfsBytes, String blockName) { + File blockFile, File metaFile, String blockName) { this.volume = volume; this.blockPoolId = bpid; this.blockFile = blockFile; this.metaFile = metaFile; - this.dfsBytes = dfsBytes; this.blockName = blockName; } @@ -192,6 +190,7 @@ public String toString() { @Override public void run() { + long dfsBytes = blockFile.length() + metaFile.length(); if ( !blockFile.delete() || ( !metaFile.delete() && metaFile.exists() ) ) { DataNode.LOG.warn("Unexpected error trying to delete block " + blockPoolId + " " + blockName + " at file " + blockFile
797495a179c6fdee40b1be4d1c27693040f3f320
drools
BZ-1025874: fixing incremental update of kjars--
c
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/main/java/org/drools/compiler/compiler/CompositeKnowledgeBuilderImpl.java b/drools-compiler/src/main/java/org/drools/compiler/compiler/CompositeKnowledgeBuilderImpl.java index 50ceaf3dc32..c15a0743d6a 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/compiler/CompositeKnowledgeBuilderImpl.java +++ b/drools-compiler/src/main/java/org/drools/compiler/compiler/CompositeKnowledgeBuilderImpl.java @@ -1,20 +1,24 @@ package org.drools.compiler.compiler; -import org.drools.core.builder.conf.impl.JaxbConfigurationImpl; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.drools.compiler.compiler.PackageBuilder.TypeDefinition; import org.drools.compiler.lang.descr.CompositePackageDescr; import org.drools.compiler.lang.descr.ImportDescr; import org.drools.compiler.lang.descr.PackageDescr; import org.drools.compiler.lang.descr.TypeDeclarationDescr; -import org.kie.internal.builder.CompositeKnowledgeBuilder; +import org.drools.core.builder.conf.impl.JaxbConfigurationImpl; import org.kie.api.io.Resource; import org.kie.api.io.ResourceConfiguration; import org.kie.api.io.ResourceType; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import org.kie.internal.builder.ChangeType; +import org.kie.internal.builder.CompositeKnowledgeBuilder; +import org.kie.internal.builder.ResourceChange; +import org.kie.internal.builder.ResourceChangeSet; public class CompositeKnowledgeBuilderImpl implements CompositeKnowledgeBuilder { @@ -46,8 +50,16 @@ public CompositeKnowledgeBuilder add(Resource resource, ResourceType type) { return add(resource, type, resource.getConfiguration()); } + public CompositeKnowledgeBuilder add(Resource resource, ResourceType type, ResourceChangeSet changes) { + return add(resource, type, resource.getConfiguration(), changes); + } + public CompositeKnowledgeBuilder add(Resource resource, ResourceType type, ResourceConfiguration configuration) { - ResourceDescr resourceDescr = new ResourceDescr(configuration, resource); + return add(resource, type, configuration, null); + } + + public CompositeKnowledgeBuilder add(Resource resource, ResourceType type, ResourceConfiguration configuration, ResourceChangeSet changes) { + ResourceDescr resourceDescr = new ResourceDescr(configuration, resource, changes); List<ResourceDescr> resourceDescrs = this.resourcesByType.get(type); if (resourceDescrs == null) { resourceDescrs = new ArrayList<ResourceDescr>(); @@ -91,7 +103,9 @@ private void registerDSL() { if (resourcesByType != null) { for (ResourceDescr resourceDescr : resourcesByType) { try { + pkgBuilder.setAssetFilter(resourceDescr.getFilter()); pkgBuilder.addDsl(resourceDescr.resource); + pkgBuilder.setAssetFilter(null); } catch (RuntimeException e) { if (buildException == null) { buildException = e; @@ -110,6 +124,7 @@ private void buildResources() { if (resourcesByType != null) { for (ResourceDescr resourceDescr : resourcesByType) { try { + pkgBuilder.setAssetFilter(resourceDescr.getFilter()); pkgBuilder.addProcessFromXml(resourceDescr.resource); } catch (RuntimeException e) { if (buildException == null) { @@ -119,6 +134,8 @@ private void buildResources() { if (buildException == null) { buildException = new RuntimeException( e ); } + } finally{ + pkgBuilder.setAssetFilter(null); } } } @@ -128,6 +145,7 @@ private void buildResources() { for (ResourceDescr resourceDescr : resourcesByType) { try { BPMN2ProcessFactory.configurePackageBuilder( pkgBuilder ); + pkgBuilder.setAssetFilter(resourceDescr.getFilter()); pkgBuilder.addProcessFromXml(resourceDescr.resource); } catch (RuntimeException e) { if (buildException == null) { @@ -137,6 +155,8 @@ private void buildResources() { if (buildException == null) { buildException = new RuntimeException( e ); } + } finally{ + pkgBuilder.setAssetFilter(null); } } } @@ -145,6 +165,7 @@ private void buildResources() { if (resourcesByType != null) { for (ResourceDescr resourceDescr : resourcesByType) { try { + pkgBuilder.setAssetFilter(resourceDescr.getFilter()); pkgBuilder.addPackageFromInputStream(resourceDescr.resource); } catch (RuntimeException e) { if (buildException == null) { @@ -154,6 +175,8 @@ private void buildResources() { if (buildException == null) { buildException = new RuntimeException( e ); } + } finally{ + pkgBuilder.setAssetFilter(null); } } } @@ -162,6 +185,7 @@ private void buildResources() { if (resourcesByType != null) { for (ResourceDescr resourceDescr : resourcesByType) { try { + pkgBuilder.setAssetFilter(resourceDescr.getFilter()); pkgBuilder.addPackageFromChangeSet(resourceDescr.resource); } catch (RuntimeException e) { if (buildException == null) { @@ -171,6 +195,8 @@ private void buildResources() { if (buildException == null) { buildException = new RuntimeException( e ); } + } finally{ + pkgBuilder.setAssetFilter(null); } } } @@ -179,6 +205,7 @@ private void buildResources() { if (resourcesByType != null) { for (ResourceDescr resourceDescr : resourcesByType) { try { + pkgBuilder.setAssetFilter(resourceDescr.getFilter()); pkgBuilder.addPackageFromXSD(resourceDescr.resource, (JaxbConfigurationImpl) resourceDescr.configuration); } catch (RuntimeException e) { if (buildException == null) { @@ -188,6 +215,8 @@ private void buildResources() { if (buildException == null) { buildException = new RuntimeException( e ); } + } finally{ + pkgBuilder.setAssetFilter(null); } } } @@ -196,6 +225,7 @@ private void buildResources() { if (resourcesByType != null) { for (ResourceDescr resourceDescr : resourcesByType) { try { + pkgBuilder.setAssetFilter(resourceDescr.getFilter()); pkgBuilder.addPackageFromPMML(resourceDescr.resource, ResourceType.PMML, resourceDescr.configuration); } catch (RuntimeException e) { if (buildException == null) { @@ -205,6 +235,8 @@ private void buildResources() { if (buildException == null) { buildException = new RuntimeException( e ); } + } finally{ + pkgBuilder.setAssetFilter(null); } } } @@ -214,7 +246,9 @@ private void buildOthers() { try { for (Map.Entry<ResourceType, List<ResourceDescr>> entry : resourcesByType.entrySet()) { for (ResourceDescr resourceDescr : entry.getValue()) { + pkgBuilder.setAssetFilter(resourceDescr.getFilter()); pkgBuilder.addPackageForExternalType(resourceDescr.resource, entry.getKey(), resourceDescr.configuration); + pkgBuilder.setAssetFilter(null); } } } catch (RuntimeException e) { @@ -225,15 +259,17 @@ private void buildOthers() { } private void buildRules(Collection<CompositePackageDescr> packages) { - for (PackageDescr packageDescr : packages) { + for (CompositePackageDescr packageDescr : packages) { + pkgBuilder.setAssetFilter(packageDescr.getFilter()); PackageRegistry pkgRegistry = pkgBuilder.getPackageRegistry(packageDescr.getNamespace()); pkgBuilder.processOtherDeclarations(pkgRegistry, packageDescr); pkgBuilder.compileAllRules(packageDescr, pkgRegistry); + pkgBuilder.setAssetFilter(null); } } private void buildTypeDeclarations(Collection<CompositePackageDescr> packages) { - for (PackageDescr packageDescr : packages) { + for (CompositePackageDescr packageDescr : packages) { for (TypeDeclarationDescr typeDeclarationDescr : packageDescr.getTypeDeclarations()) { if (pkgBuilder.isEmpty( typeDeclarationDescr.getNamespace() )) { typeDeclarationDescr.setNamespace( packageDescr.getNamespace() ); // set the default namespace @@ -243,7 +279,7 @@ private void buildTypeDeclarations(Collection<CompositePackageDescr> packages) { } List<PackageBuilder.TypeDefinition> unresolvedTypes = new ArrayList<PackageBuilder.TypeDefinition>(); - for (PackageDescr packageDescr : packages) { + for (CompositePackageDescr packageDescr : packages) { buildTypeDeclarations(packageDescr, unresolvedTypes); } @@ -251,21 +287,24 @@ private void buildTypeDeclarations(Collection<CompositePackageDescr> packages) { pkgBuilder.processUnresolvedType(pkgBuilder.getPackageRegistry(unresolvedType.getNamespace()), unresolvedType); } - for (PackageDescr packageDescr : packages) { + for (CompositePackageDescr packageDescr : packages) { for (ImportDescr importDescr : packageDescr.getImports()) { pkgBuilder.getPackageRegistry(packageDescr.getNamespace()).addImport( importDescr ); } } } - private List<PackageBuilder.TypeDefinition> buildTypeDeclarations(PackageDescr packageDescr, List<PackageBuilder.TypeDefinition> unresolvedTypes) { + private List<PackageBuilder.TypeDefinition> buildTypeDeclarations(CompositePackageDescr packageDescr, List<PackageBuilder.TypeDefinition> unresolvedTypes) { + pkgBuilder.setAssetFilter(packageDescr.getFilter()); PackageRegistry pkgRegistry = pkgBuilder.initPackageRegistry(packageDescr); if (pkgRegistry == null) { return null; } pkgBuilder.processEntryPointDeclarations(pkgRegistry, packageDescr); - return pkgBuilder.processTypeDeclarations(pkgRegistry, packageDescr, unresolvedTypes); + List<TypeDefinition> processTypeDeclarations = pkgBuilder.processTypeDeclarations(pkgRegistry, packageDescr, unresolvedTypes); + pkgBuilder.setAssetFilter(null); + return processTypeDeclarations; } private Collection<CompositePackageDescr> buildPackageDescr() { @@ -287,7 +326,7 @@ private void buildResource(Map<String, CompositePackageDescr> packages, Resource if (resourcesByType != null) { for (ResourceDescr resourceDescr : resourcesByType) { try { - registerPackageDescr(packages, resourceDescr.resource, mapper.map(pkgBuilder, resourceDescr)); + registerPackageDescr(resourceDescr, packages, resourceDescr.resource, mapper.map(pkgBuilder, resourceDescr)); } catch (RuntimeException e) { if (buildException == null) { buildException = e; @@ -301,24 +340,58 @@ private void buildResource(Map<String, CompositePackageDescr> packages, Resource } } - private void registerPackageDescr(Map<String, CompositePackageDescr> packages, Resource resource, PackageDescr packageDescr) { + private void registerPackageDescr(ResourceDescr resourceDescr, Map<String, CompositePackageDescr> packages, Resource resource, PackageDescr packageDescr) { if (packageDescr != null) { CompositePackageDescr compositePackageDescr = packages.get(packageDescr.getNamespace()); if (compositePackageDescr == null) { - packages.put(packageDescr.getNamespace(), new CompositePackageDescr(resource, packageDescr)); + compositePackageDescr = new CompositePackageDescr(resource, packageDescr); + packages.put(packageDescr.getNamespace(), compositePackageDescr); } else { compositePackageDescr.addPackageDescr(resource, packageDescr); } + compositePackageDescr.addFilter( resourceDescr.getFilter() ); } } private static class ResourceDescr { final Resource resource; final ResourceConfiguration configuration; + final ResourceChangeSet changes; + final Map<String, ResourceChange> changeMap; - private ResourceDescr(ResourceConfiguration configuration, Resource resource) { + private ResourceDescr(ResourceConfiguration configuration, Resource resource, ResourceChangeSet changes) { this.configuration = configuration; this.resource = resource; + this.changes = changes; + if( changes != null ) { + changeMap = new HashMap<String, ResourceChange>(); + for( ResourceChange c : changes.getChanges() ) { + changeMap.put(c.getName(), c); + } + } else { + changeMap = null; + } + } + + public PackageBuilder.AssetFilter getFilter() { + return changeMap == null ? null : this.new ChangeSetAssetFilter(); + } + + private class ChangeSetAssetFilter implements PackageBuilder.AssetFilter { + @Override + public Action accept(String pkgName, String assetName) { + ResourceChange change = changeMap.get(assetName); + if( change == null ) { + return Action.DO_NOTHING; + } else if( change.getChangeType().equals(ChangeType.ADDED) ) { + return Action.ADD; + } else if( change.getChangeType().equals(ChangeType.REMOVED) ) { + return Action.REMOVE; + } else if( change.getChangeType().equals(ChangeType.UPDATED) ) { + return Action.UPDATE; + } + return Action.DO_NOTHING; + } } } diff --git a/drools-compiler/src/main/java/org/drools/compiler/compiler/PackageBuilder.java b/drools-compiler/src/main/java/org/drools/compiler/compiler/PackageBuilder.java index 7b69a2f38eb..e2bbef06fba 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/compiler/PackageBuilder.java +++ b/drools-compiler/src/main/java/org/drools/compiler/compiler/PackageBuilder.java @@ -47,6 +47,7 @@ import java.util.Stack; import org.drools.compiler.commons.jci.problems.CompilationProblem; +import org.drools.compiler.compiler.PackageBuilder.AssetFilter.Action; import org.drools.compiler.compiler.xml.XmlPackageReader; import org.drools.compiler.lang.ExpanderException; import org.drools.compiler.lang.descr.AbstractClassTypeDeclarationDescr; @@ -198,7 +199,7 @@ public class PackageBuilder private ClassLoader rootClassLoader; - private final Map<String, Class< ? >> globals; + private final Map<String, Class<?>> globals; private Resource resource; @@ -233,12 +234,14 @@ public class PackageBuilder private int currentRulePackage = 0; + private AssetFilter assetFilter = null; + /** * Use this when package is starting from scratch. */ public PackageBuilder() { - this( (RuleBase) null, - null ); + this((RuleBase) null, + null); } /** @@ -246,13 +249,13 @@ public PackageBuilder() { */ public PackageBuilder(final Package pkg) { - this( pkg, - null ); + this(pkg, + null); } public PackageBuilder(final RuleBase ruleBase) { - this( ruleBase, - null ); + this(ruleBase, + null); } /** @@ -266,20 +269,20 @@ public PackageBuilder(final RuleBase ruleBase) { * @param configuration */ public PackageBuilder(final PackageBuilderConfiguration configuration) { - this( (RuleBase) null, - configuration ); + this((RuleBase) null, + configuration); } public PackageBuilder(Package pkg, - PackageBuilderConfiguration configuration) { - if ( configuration == null ) { + PackageBuilderConfiguration configuration) { + if (configuration == null) { this.configuration = new PackageBuilderConfiguration(); } else { this.configuration = configuration; } this.dateFormats = null;//(DateFormats) this.environment.get( EnvironmentName.DATE_FORMATS ); - if ( this.dateFormats == null ) { + if (this.dateFormats == null) { this.dateFormats = new DateFormatsImpl(); //this.environment.set( EnvironmentName.DATE_FORMATS , this.dateFormats ); } @@ -291,18 +294,18 @@ public PackageBuilder(Package pkg, this.pkgRegistryMap = new LinkedHashMap<String, PackageRegistry>(); this.results = new ArrayList<KnowledgeBuilderResult>(); - PackageRegistry pkgRegistry = new PackageRegistry( this, - pkg ); - pkgRegistry.setDialect( this.defaultDialect ); - this.pkgRegistryMap.put( pkg.getName(), - pkgRegistry ); + PackageRegistry pkgRegistry = new PackageRegistry(this, + pkg); + pkgRegistry.setDialect(this.defaultDialect); + this.pkgRegistryMap.put(pkg.getName(), + pkgRegistry); // add imports to pkg registry - for ( final ImportDeclaration implDecl : pkg.getImports().values() ) { - pkgRegistry.addImport( new ImportDescr( implDecl.getTarget() ) ); + for (final ImportDeclaration implDecl : pkg.getImports().values()) { + pkgRegistry.addImport(new ImportDescr(implDecl.getTarget())); } - globals = new HashMap<String, Class< ? >>(); + globals = new HashMap<String, Class<?>>(); processBuilder = createProcessBuilder(); @@ -311,21 +314,21 @@ public PackageBuilder(Package pkg, } public PackageBuilder(RuleBase ruleBase, - PackageBuilderConfiguration configuration) { - if ( configuration == null ) { + PackageBuilderConfiguration configuration) { + if (configuration == null) { this.configuration = new PackageBuilderConfiguration(); } else { this.configuration = configuration; } - if ( ruleBase != null ) { + if (ruleBase != null) { this.rootClassLoader = ((InternalRuleBase) ruleBase).getRootClassLoader(); } else { this.rootClassLoader = this.configuration.getClassLoader(); } this.dateFormats = null;//(DateFormats) this.environment.get( EnvironmentName.DATE_FORMATS ); - if ( this.dateFormats == null ) { + if (this.dateFormats == null) { this.dateFormats = new DateFormatsImpl(); //this.environment.set( EnvironmentName.DATE_FORMATS , this.dateFormats ); } @@ -339,7 +342,7 @@ public PackageBuilder(RuleBase ruleBase, this.ruleBase = (ReteooRuleBase) ruleBase; - globals = new HashMap<String, Class< ? >>(); + globals = new HashMap<String, Class<?>>(); processBuilder = createProcessBuilder(); @@ -348,70 +351,70 @@ public PackageBuilder(RuleBase ruleBase, } public PackageBuilder deepClone() { - PackageBuilder clone = new PackageBuilder( configuration ); + PackageBuilder clone = new PackageBuilder(configuration); clone.rootClassLoader = rootClassLoader; - for ( Map.Entry<String, PackageRegistry> entry : pkgRegistryMap.entrySet() ) { - clone.pkgRegistryMap.put( entry.getKey(), entry.getValue().clonePackage( rootClassLoader ) ); + for (Map.Entry<String, PackageRegistry> entry : pkgRegistryMap.entrySet()) { + clone.pkgRegistryMap.put(entry.getKey(), entry.getValue().clonePackage(rootClassLoader)); } - clone.results.addAll( results ); - clone.ruleBase = ClassUtils.deepClone( ruleBase, rootClassLoader ); - clone.globals.putAll( globals ); - if ( dslFiles != null ) { + clone.results.addAll(results); + clone.ruleBase = ClassUtils.deepClone(ruleBase, rootClassLoader); + clone.globals.putAll(globals); + if (dslFiles != null) { clone.dslFiles = new ArrayList<DSLTokenizedMappingFile>(); - clone.dslFiles.addAll( dslFiles ); + clone.dslFiles.addAll(dslFiles); } - if ( cacheTypes != null ) { + if (cacheTypes != null) { clone.cacheTypes = new HashMap<String, TypeDeclaration>(); - clone.cacheTypes.putAll( cacheTypes ); + clone.cacheTypes.putAll(cacheTypes); } - clone.packageAttributes.putAll( packageAttributes ); - for ( Map.Entry<String, List<PackageDescr>> entry : packages.entrySet() ) { - clone.packages.put( entry.getKey(), new ArrayList<PackageDescr>( entry.getValue() ) ); + clone.packageAttributes.putAll(packageAttributes); + for (Map.Entry<String, List<PackageDescr>> entry : packages.entrySet()) { + clone.packages.put(entry.getKey(), new ArrayList<PackageDescr>(entry.getValue())); } - clone.packages.putAll( packages ); + clone.packages.putAll(packages); clone.currentRulePackage = currentRulePackage; return clone; } private void initBuiltinTypeDeclarations() { - TypeDeclaration colType = new TypeDeclaration( "Collection" ); - colType.setTypesafe( false ); - colType.setTypeClass( Collection.class ); - builtinTypes.put( "java.util.Collection", - colType ); - - TypeDeclaration mapType = new TypeDeclaration( "Map" ); - mapType.setTypesafe( false ); - mapType.setTypeClass( Map.class ); - builtinTypes.put( "java.util.Map", - mapType ); - - TypeDeclaration activationType = new TypeDeclaration( "Match" ); - activationType.setTypesafe( false ); - activationType.setTypeClass( Match.class ); - builtinTypes.put( Match.class.getCanonicalName(), - activationType ); - - TypeDeclaration thingType = new TypeDeclaration( Thing.class.getSimpleName() ); - thingType.setKind( TypeDeclaration.Kind.TRAIT ); - thingType.setTypeClass( Thing.class ); - builtinTypes.put( Thing.class.getCanonicalName(), - thingType ); + TypeDeclaration colType = new TypeDeclaration("Collection"); + colType.setTypesafe(false); + colType.setTypeClass(Collection.class); + builtinTypes.put("java.util.Collection", + colType); + + TypeDeclaration mapType = new TypeDeclaration("Map"); + mapType.setTypesafe(false); + mapType.setTypeClass(Map.class); + builtinTypes.put("java.util.Map", + mapType); + + TypeDeclaration activationType = new TypeDeclaration("Match"); + activationType.setTypesafe(false); + activationType.setTypeClass(Match.class); + builtinTypes.put(Match.class.getCanonicalName(), + activationType); + + TypeDeclaration thingType = new TypeDeclaration(Thing.class.getSimpleName()); + thingType.setKind(TypeDeclaration.Kind.TRAIT); + thingType.setTypeClass(Thing.class); + builtinTypes.put(Thing.class.getCanonicalName(), + thingType); } private ProcessBuilder createProcessBuilder() { try { - return ProcessBuilderFactory.newProcessBuilder( this ); - } catch ( IllegalArgumentException e ) { + return ProcessBuilderFactory.newProcessBuilder(this); + } catch (IllegalArgumentException e) { processBuilderCreationFailure = e; return null; } } private PMMLCompiler getPMMLCompiler() { - if ( this.pmmlCompiler == null ) { + if (this.pmmlCompiler == null) { this.pmmlCompiler = PMMLCompilerFactory.getPMMLCompiler(); } return this.pmmlCompiler; @@ -425,8 +428,8 @@ private PMMLCompiler getPMMLCompiler() { * @throws IOException */ public void addPackageFromDrl(final Reader reader) throws DroolsParserException, - IOException { - addPackageFromDrl( reader, new ReaderResource( reader, ResourceType.DRL ) ); + IOException { + addPackageFromDrl(reader, new ReaderResource(reader, ResourceType.DRL)); } /** @@ -439,93 +442,92 @@ public void addPackageFromDrl(final Reader reader) throws DroolsParserException, * @throws IOException */ public void addPackageFromDrl(final Reader reader, - final Resource sourceResource) throws DroolsParserException, - IOException { + final Resource sourceResource) throws DroolsParserException, + IOException { this.resource = sourceResource; - final DrlParser parser = new DrlParser( configuration.getLanguageLevel() ); - final PackageDescr pkg = parser.parse( sourceResource, reader ); - this.results.addAll( parser.getErrors() ); - if ( pkg == null ) { - this.results.add( new ParserError( sourceResource, "Parser returned a null Package", 0, 0 ) ); + final DrlParser parser = new DrlParser(configuration.getLanguageLevel()); + final PackageDescr pkg = parser.parse(sourceResource, reader); + this.results.addAll(parser.getErrors()); + if (pkg == null) { + this.results.add(new ParserError(sourceResource, "Parser returned a null Package", 0, 0)); } - if ( !parser.hasErrors() ) { - addPackage( pkg ); + if (!parser.hasErrors()) { + addPackage(pkg); } this.resource = null; } public void addPackageFromDecisionTable(Resource resource, - ResourceConfiguration configuration) throws DroolsParserException, - IOException { + ResourceConfiguration configuration) throws DroolsParserException, + IOException { this.resource = resource; - addPackage( decisionTableToPackageDescr( resource, configuration ) ); + addPackage(decisionTableToPackageDescr(resource, configuration)); this.resource = null; } PackageDescr decisionTableToPackageDescr(Resource resource, - ResourceConfiguration configuration) throws DroolsParserException, - IOException { + ResourceConfiguration configuration) throws DroolsParserException, + IOException { DecisionTableConfiguration dtableConfiguration = (DecisionTableConfiguration) configuration; - String string = DecisionTableFactory.loadFromInputStream( resource.getInputStream(), dtableConfiguration ); + String string = DecisionTableFactory.loadFromInputStream(resource.getInputStream(), dtableConfiguration); - DrlParser parser = new DrlParser( this.configuration.getLanguageLevel() ); - PackageDescr pkg = parser.parse( resource, new StringReader( string ) ); - this.results.addAll( parser.getErrors() ); - if ( pkg == null ) { - this.results.add( new ParserError( resource, "Parser returned a null Package", 0, 0 ) ); + DrlParser parser = new DrlParser(this.configuration.getLanguageLevel()); + PackageDescr pkg = parser.parse(resource, new StringReader(string)); + this.results.addAll(parser.getErrors()); + if (pkg == null) { + this.results.add(new ParserError(resource, "Parser returned a null Package", 0, 0)); } return parser.hasErrors() ? null : pkg; } public void addPackageFromScoreCard(Resource resource, - ResourceConfiguration configuration) throws DroolsParserException, + ResourceConfiguration configuration) throws DroolsParserException, IOException { this.resource = resource; - addPackage( scoreCardToPackageDescr( resource, configuration ) ); + addPackage(scoreCardToPackageDescr(resource, configuration)); this.resource = null; } PackageDescr scoreCardToPackageDescr(Resource resource, - ResourceConfiguration configuration) throws DroolsParserException, + ResourceConfiguration configuration) throws DroolsParserException, IOException { ScoreCardConfiguration scardConfiguration = (ScoreCardConfiguration) configuration; - String string = ScoreCardFactory.loadFromInputStream( resource.getInputStream(), scardConfiguration ); + String string = ScoreCardFactory.loadFromInputStream(resource.getInputStream(), scardConfiguration); - DrlParser parser = new DrlParser( this.configuration.getLanguageLevel() ); - PackageDescr pkg = parser.parse( resource, new StringReader( string ) ); - this.results.addAll( parser.getErrors() ); - if ( pkg == null ) { - this.results.add( new ParserError( resource, "Parser returned a null Package", 0, 0 ) ); + DrlParser parser = new DrlParser(this.configuration.getLanguageLevel()); + PackageDescr pkg = parser.parse(resource, new StringReader(string)); + this.results.addAll(parser.getErrors()); + if (pkg == null) { + this.results.add(new ParserError(resource, "Parser returned a null Package", 0, 0)); } return parser.hasErrors() ? null : pkg; } - public void addPackageFromDrl(Resource resource) throws DroolsParserException, - IOException { + IOException { this.resource = resource; - addPackage( drlToPackageDescr( resource ) ); + addPackage(drlToPackageDescr(resource)); this.resource = null; } PackageDescr drlToPackageDescr(Resource resource) throws DroolsParserException, - IOException { + IOException { PackageDescr pkg; boolean hasErrors = false; - if ( resource instanceof DescrResource ) { + if (resource instanceof DescrResource) { pkg = (PackageDescr) ((DescrResource) resource).getDescr(); } else { - final DrlParser parser = new DrlParser( configuration.getLanguageLevel() ); - pkg = parser.parse( resource ); - this.results.addAll( parser.getErrors() ); - if ( pkg == null ) { - this.results.add( new ParserError( resource, "Parser returned a null Package", 0, 0 ) ); + final DrlParser parser = new DrlParser(configuration.getLanguageLevel()); + pkg = parser.parse(resource); + this.results.addAll(parser.getErrors()); + if (pkg == null) { + this.results.add(new ParserError(resource, "Parser returned a null Package", 0, 0)); } hasErrors = parser.hasErrors(); } - if ( pkg != null ) { - pkg.setResource( resource ); + if (pkg != null) { + pkg.setResource(resource); } return hasErrors ? null : pkg; } @@ -538,43 +540,43 @@ PackageDescr drlToPackageDescr(Resource resource) throws DroolsParserException, * @throws IOException */ public void addPackageFromXml(final Reader reader) throws DroolsParserException, - IOException { - this.resource = new ReaderResource( reader, ResourceType.XDRL ); - final XmlPackageReader xmlReader = new XmlPackageReader( this.configuration.getSemanticModules() ); - xmlReader.getParser().setClassLoader( this.rootClassLoader ); + IOException { + this.resource = new ReaderResource(reader, ResourceType.XDRL); + final XmlPackageReader xmlReader = new XmlPackageReader(this.configuration.getSemanticModules()); + xmlReader.getParser().setClassLoader(this.rootClassLoader); try { - xmlReader.read( reader ); - } catch ( final SAXException e ) { - throw new DroolsParserException( e.toString(), - e.getCause() ); + xmlReader.read(reader); + } catch (final SAXException e) { + throw new DroolsParserException(e.toString(), + e.getCause()); } - addPackage( xmlReader.getPackageDescr() ); + addPackage(xmlReader.getPackageDescr()); this.resource = null; } public void addPackageFromXml(final Resource resource) throws DroolsParserException, - IOException { + IOException { this.resource = resource; - addPackage( xmlToPackageDescr( resource ) ); + addPackage(xmlToPackageDescr(resource)); this.resource = null; } PackageDescr xmlToPackageDescr(Resource resource) throws DroolsParserException, - IOException { - final XmlPackageReader xmlReader = new XmlPackageReader( this.configuration.getSemanticModules() ); - xmlReader.getParser().setClassLoader( this.rootClassLoader ); + IOException { + final XmlPackageReader xmlReader = new XmlPackageReader(this.configuration.getSemanticModules()); + xmlReader.getParser().setClassLoader(this.rootClassLoader); Reader reader = null; try { reader = resource.getReader(); - xmlReader.read( reader ); - } catch ( final SAXException e ) { - throw new DroolsParserException( e.toString(), - e.getCause() ); + xmlReader.read(reader); + } catch (final SAXException e) { + throw new DroolsParserException(e.toString(), + e.getCause()); } finally { - if ( reader != null ) { + if (reader != null) { reader.close(); } } @@ -592,23 +594,23 @@ PackageDescr xmlToPackageDescr(Resource resource) throws DroolsParserException, * @throws IOException */ public void addPackageFromDrl(final Reader source, - final Reader dsl) throws DroolsParserException, - IOException { - this.resource = new ReaderResource( source, ResourceType.DSLR ); + final Reader dsl) throws DroolsParserException, + IOException { + this.resource = new ReaderResource(source, ResourceType.DSLR); - final DrlParser parser = new DrlParser( configuration.getLanguageLevel() ); - final PackageDescr pkg = parser.parse( source, dsl ); - this.results.addAll( parser.getErrors() ); - if ( !parser.hasErrors() ) { - addPackage( pkg ); + final DrlParser parser = new DrlParser(configuration.getLanguageLevel()); + final PackageDescr pkg = parser.parse(source, dsl); + this.results.addAll(parser.getErrors()); + if (!parser.hasErrors()) { + addPackage(pkg); } this.resource = null; } public void addPackageFromDslr(final Resource resource) throws DroolsParserException, - IOException { + IOException { this.resource = resource; - addPackage( dslrToPackageDescr( resource ) ); + addPackage(dslrToPackageDescr(resource)); this.resource = null; } @@ -616,33 +618,33 @@ PackageDescr dslrToPackageDescr(Resource resource) throws DroolsParserException boolean hasErrors; PackageDescr pkg; - DrlParser parser = new DrlParser( configuration.getLanguageLevel() ); + DrlParser parser = new DrlParser(configuration.getLanguageLevel()); DefaultExpander expander = getDslExpander(); Reader reader = null; try { - if ( expander == null ) { + if (expander == null) { expander = new DefaultExpander(); } reader = resource.getReader(); - String str = expander.expand( reader ); - if ( expander.hasErrors() ) { + String str = expander.expand(reader); + if (expander.hasErrors()) { for (ExpanderException error : expander.getErrors()) { - error.setResource( resource ); - this.results.add( error ); + error.setResource(resource); + this.results.add(error); } } - pkg = parser.parse( resource, str ); - this.results.addAll( parser.getErrors() ); + pkg = parser.parse(resource, str); + this.results.addAll(parser.getErrors()); hasErrors = parser.hasErrors(); - } catch ( IOException e ) { - throw new RuntimeException( e ); + } catch (IOException e) { + throw new RuntimeException(e); } finally { - if ( reader != null ) { + if (reader != null) { try { reader.close(); - } catch ( IOException e ) { + } catch (IOException e) { } } } @@ -656,15 +658,15 @@ public void addDsl(Resource resource) throws IOException { Reader reader = null; try { reader = resource.getReader(); - if ( !file.parseAndLoad( reader ) ) { - this.results.addAll( file.getErrors() ); + if (!file.parseAndLoad(reader)) { + this.results.addAll(file.getErrors()); } - if ( this.dslFiles == null ) { + if (this.dslFiles == null) { this.dslFiles = new ArrayList<DSLTokenizedMappingFile>(); } - this.dslFiles.add( file ); + this.dslFiles.add(file); } finally { - if ( reader != null ) { + if (reader != null) { reader.close(); } this.resource = null; @@ -676,135 +678,135 @@ public void addDsl(Resource resource) throws IOException { * Add a ruleflow (.rfm) asset to this package. */ public void addRuleFlow(Reader processSource) { - addProcessFromXml( processSource ); + addProcessFromXml(processSource); } public void addProcessFromXml(Resource resource) { - if ( processBuilder == null ) { - throw new RuntimeException( "Unable to instantiate a process builder", processBuilderCreationFailure ); + if (processBuilder == null) { + throw new RuntimeException("Unable to instantiate a process builder", processBuilderCreationFailure); } - if ( ResourceType.DRF.equals( resource.getResourceType() ) ) { - this.results.add( new DeprecatedResourceTypeWarning( resource, "RF" ) ); + if (ResourceType.DRF.equals(resource.getResourceType())) { + this.results.add(new DeprecatedResourceTypeWarning(resource, "RF")); } this.resource = resource; try { - this.results.addAll( processBuilder.addProcessFromXml( resource ) ); - } catch ( Exception e ) { - if ( e instanceof RuntimeException ) { + this.results.addAll(processBuilder.addProcessFromXml(resource)); + } catch (Exception e) { + if (e instanceof RuntimeException) { throw (RuntimeException) e; } - this.results.add( new ProcessLoadError( resource, "Unable to load process.", e ) ); + this.results.add(new ProcessLoadError(resource, "Unable to load process.", e)); } - this.results = getResults( this.results ); + this.results = getResults(this.results); this.resource = null; } public void addProcessFromXml(Reader processSource) { - addProcessFromXml( new ReaderResource( processSource, ResourceType.DRF ) ); + addProcessFromXml(new ReaderResource(processSource, ResourceType.DRF)); } public void addKnowledgeResource(Resource resource, - ResourceType type, - ResourceConfiguration configuration) { + ResourceType type, + ResourceConfiguration configuration) { try { - ((InternalResource) resource).setResourceType( type ); - if ( ResourceType.DRL.equals( type ) ) { - addPackageFromDrl( resource ); - } else if ( ResourceType.GDRL.equals( type ) ) { - addPackageFromDrl( resource ); - } else if ( ResourceType.RDRL.equals( type ) ) { - addPackageFromDrl( resource ); - } else if ( ResourceType.DESCR.equals( type ) ) { - addPackageFromDrl( resource ); - } else if ( ResourceType.DSLR.equals( type ) ) { - addPackageFromDslr( resource ); - } else if ( ResourceType.RDSLR.equals( type ) ) { - addPackageFromDslr( resource ); - } else if ( ResourceType.DSL.equals( type ) ) { - addDsl( resource ); - } else if ( ResourceType.XDRL.equals( type ) ) { - addPackageFromXml( resource ); - } else if ( ResourceType.DRF.equals( type ) ) { - addProcessFromXml( resource ); - } else if ( ResourceType.BPMN2.equals( type ) ) { - BPMN2ProcessFactory.configurePackageBuilder( this ); - addProcessFromXml( resource ); - } else if ( ResourceType.DTABLE.equals( type ) ) { - addPackageFromDecisionTable( resource, configuration ); - } else if ( ResourceType.PKG.equals( type ) ) { - addPackageFromInputStream( resource ); - } else if ( ResourceType.CHANGE_SET.equals( type ) ) { - addPackageFromChangeSet( resource ); - } else if ( ResourceType.XSD.equals( type ) ) { - addPackageFromXSD( resource, (JaxbConfigurationImpl) configuration ); - } else if ( ResourceType.PMML.equals( type ) ) { - addPackageFromPMML( resource, type, configuration ); - } else if ( ResourceType.SCARD.equals( type ) ) { - addPackageFromScoreCard( resource, configuration ); + ((InternalResource) resource).setResourceType(type); + if (ResourceType.DRL.equals(type)) { + addPackageFromDrl(resource); + } else if (ResourceType.GDRL.equals(type)) { + addPackageFromDrl(resource); + } else if (ResourceType.RDRL.equals(type)) { + addPackageFromDrl(resource); + } else if (ResourceType.DESCR.equals(type)) { + addPackageFromDrl(resource); + } else if (ResourceType.DSLR.equals(type)) { + addPackageFromDslr(resource); + } else if (ResourceType.RDSLR.equals(type)) { + addPackageFromDslr(resource); + } else if (ResourceType.DSL.equals(type)) { + addDsl(resource); + } else if (ResourceType.XDRL.equals(type)) { + addPackageFromXml(resource); + } else if (ResourceType.DRF.equals(type)) { + addProcessFromXml(resource); + } else if (ResourceType.BPMN2.equals(type)) { + BPMN2ProcessFactory.configurePackageBuilder(this); + addProcessFromXml(resource); + } else if (ResourceType.DTABLE.equals(type)) { + addPackageFromDecisionTable(resource, configuration); + } else if (ResourceType.PKG.equals(type)) { + addPackageFromInputStream(resource); + } else if (ResourceType.CHANGE_SET.equals(type)) { + addPackageFromChangeSet(resource); + } else if (ResourceType.XSD.equals(type)) { + addPackageFromXSD(resource, (JaxbConfigurationImpl) configuration); + } else if (ResourceType.PMML.equals(type)) { + addPackageFromPMML(resource, type, configuration); + } else if (ResourceType.SCARD.equals(type)) { + addPackageFromScoreCard(resource, configuration); } else { - addPackageForExternalType( resource, type, configuration ); + addPackageForExternalType(resource, type, configuration); } - } catch ( RuntimeException e ) { + } catch (RuntimeException e) { throw e; - } catch ( Exception e ) { - throw new RuntimeException( e ); + } catch (Exception e) { + throw new RuntimeException(e); } } void addPackageForExternalType(Resource resource, - ResourceType type, - ResourceConfiguration configuration) throws Exception { - ResourceTypeBuilder builder = ResourceTypeBuilderRegistry.getInstance().getResourceTypeBuilder( type ); - if ( builder != null ) { - builder.setPackageBuilder( this ); - builder.addKnowledgeResource( resource, - type, - configuration ); + ResourceType type, + ResourceConfiguration configuration) throws Exception { + ResourceTypeBuilder builder = ResourceTypeBuilderRegistry.getInstance().getResourceTypeBuilder(type); + if (builder != null) { + builder.setPackageBuilder(this); + builder.addKnowledgeResource(resource, + type, + configuration); } else { - throw new RuntimeException( "Unknown resource type: " + type ); + throw new RuntimeException("Unknown resource type: " + type); } } public void addPackageFromPMML(Resource resource, - ResourceType type, - ResourceConfiguration configuration) throws Exception { + ResourceType type, + ResourceConfiguration configuration) throws Exception { PMMLCompiler compiler = getPMMLCompiler(); - if ( compiler != null ) { - if ( compiler.getResults().isEmpty() ) { + if (compiler != null) { + if (compiler.getResults().isEmpty()) { this.resource = resource; PackageDescr descr = pmmlModelToPackageDescr(compiler, resource); - if ( descr != null ) { - addPackage( descr ); + if (descr != null) { + addPackage(descr); } this.resource = null; } else { - this.results.addAll( compiler.getResults() ); + this.results.addAll(compiler.getResults()); } compiler.clearResults(); } else { - addPackageForExternalType( resource, type, configuration ); + addPackageForExternalType(resource, type, configuration); } } PackageDescr pmmlModelToPackageDescr(PMMLCompiler compiler, - Resource resource) throws DroolsParserException, - IOException { - String theory = compiler.compile( resource.getInputStream(), - getPackageRegistry() ); + Resource resource) throws DroolsParserException, + IOException { + String theory = compiler.compile(resource.getInputStream(), + getPackageRegistry()); - if ( ! compiler.getResults().isEmpty() ) { - this.results.addAll( compiler.getResults() ); + if (!compiler.getResults().isEmpty()) { + this.results.addAll(compiler.getResults()); return null; } - DrlParser parser = new DrlParser( configuration.getLanguageLevel() ); - PackageDescr pkg = parser.parse( resource, new StringReader( theory ) ); - this.results.addAll( parser.getErrors() ); - if ( pkg == null ) { - this.results.add( new ParserError( resource, "Parser returned a null Package", 0, 0 ) ); + DrlParser parser = new DrlParser(configuration.getLanguageLevel()); + PackageDescr pkg = parser.parse(resource, new StringReader(theory)); + this.results.addAll(parser.getErrors()); + if (pkg == null) { + this.results.add(new ParserError(resource, "Parser returned a null Package", 0, 0)); return pkg; } else { return parser.hasErrors() ? null : pkg; @@ -812,90 +814,91 @@ PackageDescr pmmlModelToPackageDescr(PMMLCompiler compiler, } void addPackageFromXSD(Resource resource, - JaxbConfigurationImpl configuration) throws IOException { - String[] classes = DroolsJaxbHelperProviderImpl.addXsdModel( resource, - this, - configuration.getXjcOpts(), - configuration.getSystemId() ); - for ( String cls : classes ) { - configuration.getClasses().add( cls ); + JaxbConfigurationImpl configuration) throws IOException { + String[] classes = DroolsJaxbHelperProviderImpl.addXsdModel(resource, + this, + configuration.getXjcOpts(), + configuration.getSystemId()); + for (String cls : classes) { + configuration.getClasses().add(cls); } } void addPackageFromChangeSet(Resource resource) throws SAXException, - IOException { - XmlChangeSetReader reader = new XmlChangeSetReader( this.configuration.getSemanticModules() ); - if ( resource instanceof ClassPathResource ) { - reader.setClassLoader( ((ClassPathResource) resource).getClassLoader(), - ((ClassPathResource) resource).getClazz() ); + IOException { + XmlChangeSetReader reader = new XmlChangeSetReader(this.configuration.getSemanticModules()); + if (resource instanceof ClassPathResource) { + reader.setClassLoader(((ClassPathResource) resource).getClassLoader(), + ((ClassPathResource) resource).getClazz()); } else { - reader.setClassLoader( this.configuration.getClassLoader(), - null ); + reader.setClassLoader(this.configuration.getClassLoader(), + null); } Reader resourceReader = null; try { resourceReader = resource.getReader(); - ChangeSet changeSet = reader.read( resourceReader ); - if ( changeSet == null ) { + ChangeSet changeSet = reader.read(resourceReader); + if (changeSet == null) { // @TODO should log an error } - for ( Resource nestedResource : changeSet.getResourcesAdded() ) { + for (Resource nestedResource : changeSet.getResourcesAdded()) { InternalResource iNestedResourceResource = (InternalResource) nestedResource; - if ( iNestedResourceResource.isDirectory() ) { - for ( Resource childResource : iNestedResourceResource.listResources() ) { - if ( ((InternalResource) childResource).isDirectory() ) { + if (iNestedResourceResource.isDirectory()) { + for (Resource childResource : iNestedResourceResource.listResources()) { + if (((InternalResource) childResource).isDirectory()) { continue; // ignore sub directories } - ((InternalResource) childResource).setResourceType( iNestedResourceResource.getResourceType() ); - addKnowledgeResource( childResource, - iNestedResourceResource.getResourceType(), - iNestedResourceResource.getConfiguration() ); + ((InternalResource) childResource).setResourceType(iNestedResourceResource.getResourceType()); + addKnowledgeResource(childResource, + iNestedResourceResource.getResourceType(), + iNestedResourceResource.getConfiguration()); } } else { - addKnowledgeResource( iNestedResourceResource, - iNestedResourceResource.getResourceType(), - iNestedResourceResource.getConfiguration() ); + addKnowledgeResource(iNestedResourceResource, + iNestedResourceResource.getResourceType(), + iNestedResourceResource.getConfiguration()); } } } finally { - if ( resourceReader != null ) { + if (resourceReader != null) { resourceReader.close(); } } } void addPackageFromInputStream(final Resource resource) throws IOException, - ClassNotFoundException { + ClassNotFoundException { InputStream is = resource.getInputStream(); - Object object = DroolsStreamUtils.streamIn( is, this.configuration.getClassLoader() ); + Object object = DroolsStreamUtils.streamIn(is, this.configuration.getClassLoader()); is.close(); - if ( object instanceof Collection ) { + if (object instanceof Collection) { // KnowledgeBuilder API @SuppressWarnings("unchecked") Collection<KnowledgePackage> pkgs = (Collection<KnowledgePackage>) object; - for ( KnowledgePackage kpkg : pkgs ) { - overrideReSource( ((KnowledgePackageImp) kpkg).pkg, resource ); - addPackage( ((KnowledgePackageImp) kpkg).pkg ); + for (KnowledgePackage kpkg : pkgs) { + overrideReSource(((KnowledgePackageImp) kpkg).pkg, resource); + addPackage(((KnowledgePackageImp) kpkg).pkg); } - } else if ( object instanceof KnowledgePackageImp ) { + } else if (object instanceof KnowledgePackageImp) { // KnowledgeBuilder API KnowledgePackageImp kpkg = (KnowledgePackageImp) object; - overrideReSource( kpkg.pkg, resource ); - addPackage( kpkg.pkg ); - } else if ( object instanceof Package ) { + overrideReSource(kpkg.pkg, resource); + addPackage(kpkg.pkg); + } else if (object instanceof Package) { // Old Drools 4 API Package pkg = (Package) object; - overrideReSource( pkg, resource ); - addPackage( pkg ); - } else if ( object instanceof Package[] ) { + overrideReSource(pkg, resource); + addPackage(pkg); + } else if (object instanceof Package[]) { // Old Drools 4 API Package[] pkgs = (Package[]) object; - for ( Package pkg : pkgs ) { - overrideReSource( pkg, resource ); - addPackage( pkg ); + for (Package pkg : pkgs) { + overrideReSource(pkg, resource); + addPackage(pkg); } } else { - results.add( new DroolsError( resource ) { + results.add(new DroolsError(resource) { + @Override public String getMessage() { return "Unknown binary format trying to load resource " + resource.toString(); @@ -905,38 +908,38 @@ public String getMessage() { public int[] getLines() { return new int[0]; } - } ); + }); } } private void overrideReSource(Package pkg, - Resource res) { - for ( Rule r : pkg.getRules() ) { - if ( isSwappable( r.getResource(), res ) ) { - r.setResource( res ); + Resource res) { + for (Rule r : pkg.getRules()) { + if (isSwappable(r.getResource(), res)) { + r.setResource(res); } } - for ( TypeDeclaration d : pkg.getTypeDeclarations().values() ) { - if ( isSwappable( d.getResource(), res ) ) { - d.setResource( res ); + for (TypeDeclaration d : pkg.getTypeDeclarations().values()) { + if (isSwappable(d.getResource(), res)) { + d.setResource(res); } } - for ( Function f : pkg.getFunctions().values() ) { - if ( isSwappable( f.getResource(), res ) ) { - f.setResource( res ); + for (Function f : pkg.getFunctions().values()) { + if (isSwappable(f.getResource(), res)) { + f.setResource(res); } } - for ( Process p : pkg.getRuleFlows().values() ) { - if ( isSwappable( p.getResource(), res ) ) { - p.setResource( res ); + for (Process p : pkg.getRuleFlows().values()) { + if (isSwappable(p.getResource(), res)) { + p.setResource(res); } } } private boolean isSwappable(Resource original, - Resource source) { + Resource source) { return original == null - || (original instanceof ReaderResource && ((ReaderResource) original).getReader() == null); + || (original instanceof ReaderResource && ((ReaderResource) original).getReader() == null); } /** @@ -944,121 +947,127 @@ private boolean isSwappable(Resource original, * there are any generated classes to compile of course. */ public void addPackage(final PackageDescr packageDescr) { - PackageRegistry pkgRegistry = initPackageRegistry( packageDescr ); - if ( pkgRegistry == null ) { + PackageRegistry pkgRegistry = initPackageRegistry(packageDescr); + if (pkgRegistry == null) { return; } currentRulePackage = pkgRegistryMap.size() - 1; // merge into existing package - mergePackage( pkgRegistry, packageDescr ); + mergePackage(pkgRegistry, packageDescr); - compileAllRules( packageDescr, pkgRegistry ); + compileAllRules(packageDescr, pkgRegistry); } void compileAllRules(PackageDescr packageDescr, - PackageRegistry pkgRegistry) { - pkgRegistry.setDialect( getPackageDialect( packageDescr ) ); + PackageRegistry pkgRegistry) { + pkgRegistry.setDialect(getPackageDialect(packageDescr)); // only try to compile if there are no parse errors - if ( !hasErrors() ) { - compileRules( packageDescr, pkgRegistry ); + if (!hasErrors()) { + compileRules(packageDescr, pkgRegistry); } compileAll(); try { reloadAll(); - } catch ( Exception e ) { - this.results.add( new DialectError( null, "Unable to wire compiled classes, probably related to compilation failures:" + e.getMessage() ) ); + } catch (Exception e) { + this.results.add(new DialectError(null, "Unable to wire compiled classes, probably related to compilation failures:" + e.getMessage())); } updateResults(); // iterate and compile - if ( !hasErrors() && this.ruleBase != null ) { - for ( RuleDescr ruleDescr : packageDescr.getRules() ) { - pkgRegistry = this.pkgRegistryMap.get( ruleDescr.getNamespace() ); - this.ruleBase.addRule( pkgRegistry.getPackage(), pkgRegistry.getPackage().getRule( ruleDescr.getName() ) ); + if (!hasErrors() && this.ruleBase != null) { + for (RuleDescr ruleDescr : packageDescr.getRules()) { + if( filterAccepts( ruleDescr.getNamespace(), ruleDescr.getName() ) ) { + pkgRegistry = this.pkgRegistryMap.get(ruleDescr.getNamespace()); + this.ruleBase.addRule(pkgRegistry.getPackage(), pkgRegistry.getPackage().getRule(ruleDescr.getName())); + } } } } PackageRegistry initPackageRegistry(PackageDescr packageDescr) { - if ( packageDescr == null ) { + if (packageDescr == null) { return null; } //Derive namespace - if ( isEmpty( packageDescr.getNamespace() ) ) { - packageDescr.setNamespace( this.configuration.getDefaultPackageName() ); + if (isEmpty(packageDescr.getNamespace())) { + packageDescr.setNamespace(this.configuration.getDefaultPackageName()); } - validateUniqueRuleNames( packageDescr ); - if ( !checkNamespace( packageDescr.getNamespace() ) ) { + validateUniqueRuleNames(packageDescr); + if (!checkNamespace(packageDescr.getNamespace())) { return null; } - initPackage( packageDescr ); + initPackage(packageDescr); - PackageRegistry pkgRegistry = this.pkgRegistryMap.get( packageDescr.getNamespace() ); - if ( pkgRegistry == null ) { + PackageRegistry pkgRegistry = this.pkgRegistryMap.get(packageDescr.getNamespace()); + if (pkgRegistry == null) { // initialise the package and namespace if it hasn't been used before - pkgRegistry = newPackage( packageDescr ); + pkgRegistry = newPackage(packageDescr); } return pkgRegistry; } private void compileRules(PackageDescr packageDescr, - PackageRegistry pkgRegistry) { + PackageRegistry pkgRegistry) { List<FunctionDescr> functions = packageDescr.getFunctions(); - if ( !functions.isEmpty() ) { + if (!functions.isEmpty()) { - for ( FunctionDescr functionDescr : functions ) { - if ( isEmpty( functionDescr.getNamespace() ) ) { - // make sure namespace is set on components - functionDescr.setNamespace( packageDescr.getNamespace() ); - } + for (FunctionDescr functionDescr : functions) { + if (filterAccepts(functionDescr.getNamespace(), functionDescr.getName()) ) { + if (isEmpty(functionDescr.getNamespace())) { + // make sure namespace is set on components + functionDescr.setNamespace(packageDescr.getNamespace()); + } - // make sure functions are compiled using java dialect - functionDescr.setDialect( "java" ); + // make sure functions are compiled using java dialect + functionDescr.setDialect("java"); - preCompileAddFunction( functionDescr ); + preCompileAddFunction(functionDescr); + } } // iterate and compile - for ( FunctionDescr functionDescr : functions ) { - // inherit the dialect from the package - addFunction( functionDescr ); + for (FunctionDescr functionDescr : functions) { + if (filterAccepts(functionDescr.getNamespace(), functionDescr.getName()) ) { + // inherit the dialect from the package + addFunction(functionDescr); + } } // We need to compile all the functions now, so scripting // languages like mvel can find them compileAll(); - for ( FunctionDescr functionDescr : functions ) { - postCompileAddFunction( functionDescr ); + for (FunctionDescr functionDescr : functions) { + if (filterAccepts(functionDescr.getNamespace(), functionDescr.getName()) ) { + postCompileAddFunction(functionDescr); + } } } // ensure that rules are ordered by dependency, so that dependent rules are built later - sortRulesByDependency( packageDescr ); - - + sortRulesByDependency(packageDescr); // iterate and prepare RuleDescr - for ( RuleDescr ruleDescr : packageDescr.getRules() ) { - if ( isEmpty( ruleDescr.getNamespace() ) ) { + for (RuleDescr ruleDescr : packageDescr.getRules()) { + if (isEmpty(ruleDescr.getNamespace())) { // make sure namespace is set on components - ruleDescr.setNamespace( packageDescr.getNamespace() ); + ruleDescr.setNamespace(packageDescr.getNamespace()); } - Map<String, AttributeDescr> pkgAttributes = packageAttributes.get( packageDescr.getNamespace() ); - inheritPackageAttributes( pkgAttributes, - ruleDescr ); + Map<String, AttributeDescr> pkgAttributes = packageAttributes.get(packageDescr.getNamespace()); + inheritPackageAttributes(pkgAttributes, + ruleDescr); - if ( isEmpty( ruleDescr.getDialect() ) ) { - ruleDescr.addAttribute( new AttributeDescr( "dialect", - pkgRegistry.getDialect() ) ); + if (isEmpty(ruleDescr.getDialect())) { + ruleDescr.addAttribute(new AttributeDescr("dialect", + pkgRegistry.getDialect())); } } @@ -1066,32 +1075,54 @@ private void compileRules(PackageDescr packageDescr, Map<String, RuleBuildContext> ruleCxts = preProcessRules(packageDescr, pkgRegistry); // iterate and compile - for ( RuleDescr ruleDescr : packageDescr.getRules() ) { - addRule( ruleCxts.get( ruleDescr.getName() ) ); + for (RuleDescr ruleDescr : packageDescr.getRules()) { + if (filterAccepts(ruleDescr.getNamespace(), ruleDescr.getName()) ) { + addRule(ruleCxts.get(ruleDescr.getName())); + } } } + private boolean filterAccepts( String namespace, String name ) { + return assetFilter == null || ! Action.DO_NOTHING.equals( assetFilter.accept( namespace, name ) ); + } + + private boolean filterAcceptsRemoval( String namespace, String name ) { + return assetFilter != null && Action.REMOVE.equals( assetFilter.accept( namespace, name ) ); + } + private Map<String, RuleBuildContext> preProcessRules(PackageDescr packageDescr, PackageRegistry pkgRegistry) { - Map<String, RuleBuildContext> ruleCxts = buildRuleBuilderContext( packageDescr.getRules() ); + Map<String, RuleBuildContext> ruleCxts = buildRuleBuilderContext(packageDescr.getRules()); Package pkg = pkgRegistry.getPackage(); - if ( this.ruleBase != null ) { + if (this.ruleBase != null) { + // first, remove any rules that are no longer there + for( Rule rule : pkg.getRules() ) { + if (filterAcceptsRemoval( rule.getPackageName(), rule.getName() ) ) { + this.ruleBase.removeRule(pkg, pkg.getRule(rule.getName())); + pkg.removeRule(rule); + } + } + boolean needsRemoval = false; - for ( RuleDescr ruleDescr : packageDescr.getRules() ) { - if ( pkg.getRule( ruleDescr.getName() ) != null ) { - needsRemoval = true; - break; + for (RuleDescr ruleDescr : packageDescr.getRules()) { + if (filterAccepts(ruleDescr.getNamespace(), ruleDescr.getName()) ) { + if (pkg.getRule(ruleDescr.getName()) != null) { + needsRemoval = true; + break; + } } } - if ( needsRemoval ) { + if (needsRemoval) { try { this.ruleBase.lock(); - for ( RuleDescr ruleDescr : packageDescr.getRules() ) { - if ( pkg.getRule( ruleDescr.getName() ) != null ) { - // XXX: this one notifies listeners - this.ruleBase.removeRule( pkg, pkg.getRule( ruleDescr.getName() ) ); + for (RuleDescr ruleDescr : packageDescr.getRules()) { + if (filterAccepts(ruleDescr.getNamespace(), ruleDescr.getName()) ) { + if (pkg.getRule(ruleDescr.getName()) != null) { + // XXX: this one notifies listeners + this.ruleBase.removeRule(pkg, pkg.getRule(ruleDescr.getName())); + } } } } finally { @@ -1101,10 +1132,12 @@ private Map<String, RuleBuildContext> preProcessRules(PackageDescr packageDescr, } // Pre Process each rule, needed for Query signuture registration - for ( RuleDescr ruleDescr : packageDescr.getRules() ) { - RuleBuildContext ruleBuildContext = ruleCxts.get( ruleDescr.getName() ); - ruleBuilder.preProcess( ruleBuildContext ); - pkg.addRule( ruleBuildContext.getRule() ); + for (RuleDescr ruleDescr : packageDescr.getRules()) { + if (filterAccepts(ruleDescr.getNamespace(), ruleDescr.getName()) ) { + RuleBuildContext ruleBuildContext = ruleCxts.get(ruleDescr.getName()); + ruleBuilder.preProcess(ruleBuildContext); + pkg.addRule(ruleBuildContext.getRule()); + } } return ruleCxts; } @@ -1113,7 +1146,7 @@ private void sortRulesByDependency(PackageDescr packageDescr) { // Using a topological sorting algorithm // see http://en.wikipedia.org/wiki/Topological_sorting - PackageRegistry pkgRegistry = this.pkgRegistryMap.get( packageDescr.getNamespace() ); + PackageRegistry pkgRegistry = this.pkgRegistryMap.get(packageDescr.getNamespace()); Package pkg = pkgRegistry.getPackage(); List<RuleDescr> roots = new LinkedList<RuleDescr>(); @@ -1121,117 +1154,117 @@ private void sortRulesByDependency(PackageDescr packageDescr) { LinkedHashMap<String, RuleDescr> sorted = new LinkedHashMap<String, RuleDescr>(); List<RuleDescr> queries = new ArrayList<RuleDescr>(); - for ( RuleDescr ruleDescr : packageDescr.getRules() ) { - if ( ruleDescr.isQuery() ) { + for (RuleDescr ruleDescr : packageDescr.getRules()) { + if (ruleDescr.isQuery()) { queries.add(ruleDescr); - } else if ( !ruleDescr.hasParent() ) { + } else if (!ruleDescr.hasParent()) { roots.add(ruleDescr); - } else if ( pkg.getRule( ruleDescr.getParentName() ) != null ) { + } else if (pkg.getRule(ruleDescr.getParentName()) != null) { // The parent of this rule has been already compiled - sorted.put( ruleDescr.getName(), ruleDescr ); + sorted.put(ruleDescr.getName(), ruleDescr); } else { - List<RuleDescr> childz = children.get( ruleDescr.getParentName() ); - if ( childz == null ) { + List<RuleDescr> childz = children.get(ruleDescr.getParentName()); + if (childz == null) { childz = new ArrayList<RuleDescr>(); - children.put( ruleDescr.getParentName(), childz ); + children.put(ruleDescr.getParentName(), childz); } - childz.add( ruleDescr ); + childz.add(ruleDescr); } } - if ( children.isEmpty() ) { // Sorting not necessary - if ( !queries.isEmpty() ) { // Build all queries first + if (children.isEmpty()) { // Sorting not necessary + if (!queries.isEmpty()) { // Build all queries first packageDescr.getRules().removeAll(queries); packageDescr.getRules().addAll(0, queries); } return; } - while ( !roots.isEmpty() ) { - RuleDescr root = roots.remove( 0 ); - sorted.put( root.getName(), root ); - List<RuleDescr> childz = children.remove( root.getName() ); - if ( childz != null ) { - roots.addAll( childz ); + while (!roots.isEmpty()) { + RuleDescr root = roots.remove(0); + sorted.put(root.getName(), root); + List<RuleDescr> childz = children.remove(root.getName()); + if (childz != null) { + roots.addAll(childz); } } - reportHierarchyErrors( children, sorted ); + reportHierarchyErrors(children, sorted); packageDescr.getRules().clear(); packageDescr.getRules().addAll(queries); - for ( RuleDescr descr : sorted.values() ) { - packageDescr.getRules().add( descr ); + for (RuleDescr descr : sorted.values()) { + packageDescr.getRules().add(descr); } } private void reportHierarchyErrors(Map<String, List<RuleDescr>> parents, - Map<String, RuleDescr> sorted) { + Map<String, RuleDescr> sorted) { boolean circularDep = false; - for ( List<RuleDescr> rds : parents.values() ) { - for ( RuleDescr ruleDescr : rds ) { - if ( parents.get( ruleDescr.getParentName() ) != null - && (sorted.containsKey( ruleDescr.getName() ) || parents.containsKey( ruleDescr.getName() )) ) { + for (List<RuleDescr> rds : parents.values()) { + for (RuleDescr ruleDescr : rds) { + if (parents.get(ruleDescr.getParentName()) != null + && (sorted.containsKey(ruleDescr.getName()) || parents.containsKey(ruleDescr.getName()))) { circularDep = true; - results.add( new RuleBuildError( new Rule( ruleDescr.getName() ), ruleDescr, null, - "Circular dependency in rules hierarchy" ) ); + results.add(new RuleBuildError(new Rule(ruleDescr.getName()), ruleDescr, null, + "Circular dependency in rules hierarchy")); break; } - manageUnresolvedExtension( ruleDescr, sorted.values() ); + manageUnresolvedExtension(ruleDescr, sorted.values()); } - if ( circularDep ) { + if (circularDep) { break; } } } private void manageUnresolvedExtension(RuleDescr ruleDescr, - Collection<RuleDescr> candidates) { + Collection<RuleDescr> candidates) { List<String> candidateRules = new LinkedList<String>(); - for ( RuleDescr r : candidates ) { - if ( StringUtils.stringSimilarity( ruleDescr.getParentName(), r.getName(), StringUtils.SIMILARITY_STRATS.DICE ) >= 0.75 ) { - candidateRules.add( r.getName() ); + for (RuleDescr r : candidates) { + if (StringUtils.stringSimilarity(ruleDescr.getParentName(), r.getName(), StringUtils.SIMILARITY_STRATS.DICE) >= 0.75) { + candidateRules.add(r.getName()); } } String msg = "Unresolved parent name " + ruleDescr.getParentName(); - if ( candidateRules.size() > 0 ) { + if (candidateRules.size() > 0) { msg += " >> did you mean any of :" + candidateRules; } - results.add( new RuleBuildError( new Rule( ruleDescr.getName() ), ruleDescr, msg, - "Unable to resolve parent rule, please check that both rules are in the same package" ) ); + results.add(new RuleBuildError(new Rule(ruleDescr.getName()), ruleDescr, msg, + "Unable to resolve parent rule, please check that both rules are in the same package")); } private void initPackage(PackageDescr packageDescr) { //Gather all imports for all PackageDescrs for the current package and replicate into //all PackageDescrs for the current package, thus maintaining a complete list of //ImportDescrs for all PackageDescrs for the current package. - List<PackageDescr> packageDescrsForPackage = packages.get( packageDescr.getName() ); - if ( packageDescrsForPackage == null ) { + List<PackageDescr> packageDescrsForPackage = packages.get(packageDescr.getName()); + if (packageDescrsForPackage == null) { packageDescrsForPackage = new ArrayList<PackageDescr>(); - packages.put( packageDescr.getName(), - packageDescrsForPackage ); + packages.put(packageDescr.getName(), + packageDescrsForPackage); } - packageDescrsForPackage.add( packageDescr ); + packageDescrsForPackage.add(packageDescr); Set<ImportDescr> imports = new HashSet<ImportDescr>(); - for ( PackageDescr pd : packageDescrsForPackage ) { - imports.addAll( pd.getImports() ); + for (PackageDescr pd : packageDescrsForPackage) { + imports.addAll(pd.getImports()); } - for ( PackageDescr pd : packageDescrsForPackage ) { + for (PackageDescr pd : packageDescrsForPackage) { pd.getImports().clear(); - pd.addAllImports( imports ); + pd.addAllImports(imports); } //Copy package level attributes for inclusion on individual rules - if ( !packageDescr.getAttributes().isEmpty() ) { - Map<String, AttributeDescr> pkgAttributes = packageAttributes.get( packageDescr.getNamespace() ); - if ( pkgAttributes == null ) { + if (!packageDescr.getAttributes().isEmpty()) { + Map<String, AttributeDescr> pkgAttributes = packageAttributes.get(packageDescr.getNamespace()); + if (pkgAttributes == null) { pkgAttributes = new HashMap<String, AttributeDescr>(); - this.packageAttributes.put( packageDescr.getNamespace(), - pkgAttributes ); + this.packageAttributes.put(packageDescr.getNamespace(), + pkgAttributes); } - for ( AttributeDescr attr : packageDescr.getAttributes() ) { - pkgAttributes.put( attr.getName(), - attr ); + for (AttributeDescr attr : packageDescr.getAttributes()) { + pkgAttributes.put(attr.getName(), + attr); } } } @@ -1239,8 +1272,8 @@ private void initPackage(PackageDescr packageDescr) { private String getPackageDialect(PackageDescr packageDescr) { String dialectName = this.defaultDialect; // see if this packageDescr overrides the current default dialect - for ( AttributeDescr value : packageDescr.getAttributes() ) { - if ( "dialect".equals( value.getName() ) ) { + for (AttributeDescr value : packageDescr.getAttributes()) { + if ("dialect".equals(value.getName())) { dialectName = value.getValue(); break; } @@ -1254,8 +1287,9 @@ private String getPackageDialect(PackageDescr packageDescr) { * This checks to see if it should all be in the one namespace. */ private boolean checkNamespace(String newName) { - if ( this.configuration == null ) return true; - if ( (!this.pkgRegistryMap.isEmpty()) && (!this.pkgRegistryMap.containsKey( newName )) ) { + if (this.configuration == null) + return true; + if ((!this.pkgRegistryMap.isEmpty()) && (!this.pkgRegistryMap.containsKey(newName))) { return this.configuration.isAllowMultipleNamespaces(); } return true; @@ -1267,80 +1301,80 @@ public boolean isEmpty(String string) { public void updateResults() { // some of the rules and functions may have been redefined - updateResults( this.results ); + updateResults(this.results); } public void updateResults(List<KnowledgeBuilderResult> results) { - this.results = getResults( results ); + this.results = getResults(results); } public void compileAll() { - for ( PackageRegistry pkgRegistry : this.pkgRegistryMap.values() ) { + for (PackageRegistry pkgRegistry : this.pkgRegistryMap.values()) { pkgRegistry.compileAll(); } } public void reloadAll() { - for ( PackageRegistry pkgRegistry : this.pkgRegistryMap.values() ) { + for (PackageRegistry pkgRegistry : this.pkgRegistryMap.values()) { pkgRegistry.getDialectRuntimeRegistry().onBeforeExecute(); } } private List<KnowledgeBuilderResult> getResults(List<KnowledgeBuilderResult> results) { - for ( PackageRegistry pkgRegistry : this.pkgRegistryMap.values() ) { - results = pkgRegistry.getDialectCompiletimeRegistry().addResults( results ); + for (PackageRegistry pkgRegistry : this.pkgRegistryMap.values()) { + results = pkgRegistry.getDialectCompiletimeRegistry().addResults(results); } return results; } public synchronized void addPackage(final Package newPkg) { - PackageRegistry pkgRegistry = this.pkgRegistryMap.get( newPkg.getName() ); + PackageRegistry pkgRegistry = this.pkgRegistryMap.get(newPkg.getName()); Package pkg = null; - if ( pkgRegistry != null ) { + if (pkgRegistry != null) { pkg = pkgRegistry.getPackage(); } - if ( pkg == null ) { - PackageDescr packageDescr = new PackageDescr( newPkg.getName() ); - pkgRegistry = newPackage( packageDescr ); - mergePackage( this.pkgRegistryMap.get( packageDescr.getNamespace() ), packageDescr ); + if (pkg == null) { + PackageDescr packageDescr = new PackageDescr(newPkg.getName()); + pkgRegistry = newPackage(packageDescr); + mergePackage(this.pkgRegistryMap.get(packageDescr.getNamespace()), packageDescr); pkg = pkgRegistry.getPackage(); } // first merge anything related to classloader re-wiring - pkg.getDialectRuntimeRegistry().merge( newPkg.getDialectRuntimeRegistry(), - this.rootClassLoader ); - if ( newPkg.getFunctions() != null ) { - for ( Map.Entry<String, Function> entry : newPkg.getFunctions().entrySet() ) { - if ( pkg.getFunctions().containsKey( entry.getKey() ) ) { - this.results.add( new DuplicateFunction( entry.getValue(), - this.configuration ) ); + pkg.getDialectRuntimeRegistry().merge(newPkg.getDialectRuntimeRegistry(), + this.rootClassLoader); + if (newPkg.getFunctions() != null) { + for (Map.Entry<String, Function> entry : newPkg.getFunctions().entrySet()) { + if (pkg.getFunctions().containsKey(entry.getKey())) { + this.results.add(new DuplicateFunction(entry.getValue(), + this.configuration)); } - pkg.addFunction( entry.getValue() ); + pkg.addFunction(entry.getValue()); } } - pkg.getClassFieldAccessorStore().merge( newPkg.getClassFieldAccessorStore() ); + pkg.getClassFieldAccessorStore().merge(newPkg.getClassFieldAccessorStore()); pkg.getDialectRuntimeRegistry().onBeforeExecute(); // we have to do this before the merging, as it does some classloader resolving TypeDeclaration lastType = null; try { // Resolve the class for the type declaation - if ( newPkg.getTypeDeclarations() != null ) { + if (newPkg.getTypeDeclarations() != null) { // add type declarations - for ( TypeDeclaration type : newPkg.getTypeDeclarations().values() ) { + for (TypeDeclaration type : newPkg.getTypeDeclarations().values()) { lastType = type; - type.setTypeClass( this.rootClassLoader.loadClass( type.getTypeClassName() ) ); + type.setTypeClass(this.rootClassLoader.loadClass(type.getTypeClassName())); } } - } catch ( ClassNotFoundException e ) { - throw new RuntimeDroolsException( "unable to resolve Type Declaration class '" + lastType.getTypeName() + - "'" ); + } catch (ClassNotFoundException e) { + throw new RuntimeDroolsException("unable to resolve Type Declaration class '" + lastType.getTypeName() + + "'"); } // now merge the new package into the existing one - mergePackage( pkg, - newPkg ); + mergePackage(pkg, + newPkg); } @@ -1351,59 +1385,59 @@ public synchronized void addPackage(final Package newPkg) { * into the package). */ private void mergePackage(final Package pkg, - final Package newPkg) { + final Package newPkg) { // Merge imports final Map<String, ImportDeclaration> imports = pkg.getImports(); - imports.putAll( newPkg.getImports() ); + imports.putAll(newPkg.getImports()); String lastType = null; try { // merge globals - if ( newPkg.getGlobals() != null && newPkg.getGlobals() != Collections.EMPTY_MAP ) { + if (newPkg.getGlobals() != null && newPkg.getGlobals() != Collections.EMPTY_MAP) { Map<String, String> globals = pkg.getGlobals(); // Add globals - for ( final Map.Entry<String, String> entry : newPkg.getGlobals().entrySet() ) { + for (final Map.Entry<String, String> entry : newPkg.getGlobals().entrySet()) { final String identifier = entry.getKey(); final String type = entry.getValue(); lastType = type; - if ( globals.containsKey( identifier ) && !globals.get( identifier ).equals( type ) ) { - throw new PackageIntegrationException( pkg ); + if (globals.containsKey(identifier) && !globals.get(identifier).equals(type)) { + throw new PackageIntegrationException(pkg); } else { - pkg.addGlobal( identifier, - this.rootClassLoader.loadClass( type ) ); + pkg.addGlobal(identifier, + this.rootClassLoader.loadClass(type)); // this isn't a package merge, it's adding to the rulebase, but I've put it here for convenience - this.globals.put( identifier, - this.rootClassLoader.loadClass( type ) ); + this.globals.put(identifier, + this.rootClassLoader.loadClass(type)); } } } - } catch ( ClassNotFoundException e ) { - throw new RuntimeDroolsException( "Unable to resolve class '" + lastType + "'" ); + } catch (ClassNotFoundException e) { + throw new RuntimeDroolsException("Unable to resolve class '" + lastType + "'"); } // merge the type declarations - if ( newPkg.getTypeDeclarations() != null ) { + if (newPkg.getTypeDeclarations() != null) { // add type declarations - for ( TypeDeclaration type : newPkg.getTypeDeclarations().values() ) { + for (TypeDeclaration type : newPkg.getTypeDeclarations().values()) { // @TODO should we allow overrides? only if the class is not in use. - if ( !pkg.getTypeDeclarations().containsKey( type.getTypeName() ) ) { + if (!pkg.getTypeDeclarations().containsKey(type.getTypeName())) { // add to package list of type declarations - pkg.addTypeDeclaration( type ); + pkg.addTypeDeclaration(type); } } } final Rule[] newRules = newPkg.getRules(); - for ( final Rule newRule : newRules ) { - pkg.addRule( newRule ); + for (final Rule newRule : newRules) { + pkg.addRule(newRule); } //Merge The Rule Flows - if ( newPkg.getRuleFlows() != null ) { + if (newPkg.getRuleFlows() != null) { final Map flows = newPkg.getRuleFlows(); - for ( Object o : flows.values() ) { + for (Object o : flows.values()) { final Process flow = (Process) o; - pkg.addProcess( flow ); + pkg.addProcess(flow); } } @@ -1422,166 +1456,166 @@ private void mergePackage(final Package pkg, private void validateUniqueRuleNames(final PackageDescr packageDescr) { final Set<String> names = new HashSet<String>(); - PackageRegistry packageRegistry = this.pkgRegistryMap.get( packageDescr.getNamespace() ); + PackageRegistry packageRegistry = this.pkgRegistryMap.get(packageDescr.getNamespace()); Package pkg = null; - if ( packageRegistry != null ) { + if (packageRegistry != null) { pkg = packageRegistry.getPackage(); } - for ( final RuleDescr rule : packageDescr.getRules() ) { - validateRule( packageDescr, rule ); + for (final RuleDescr rule : packageDescr.getRules()) { + validateRule(packageDescr, rule); final String name = rule.getName(); - if ( names.contains( name ) ) { - this.results.add( new ParserError( rule.getResource(), - "Duplicate rule name: " + name, - rule.getLine(), - rule.getColumn(), - packageDescr.getNamespace() ) ); - } - if ( pkg != null ) { - Rule duplicatedRule = pkg.getRule( name ); - if ( duplicatedRule != null ) { + if (names.contains(name)) { + this.results.add(new ParserError(rule.getResource(), + "Duplicate rule name: " + name, + rule.getLine(), + rule.getColumn(), + packageDescr.getNamespace())); + } + if (pkg != null) { + Rule duplicatedRule = pkg.getRule(name); + if (duplicatedRule != null) { Resource resource = rule.getResource(); Resource duplicatedResource = duplicatedRule.getResource(); - if ( resource == null || duplicatedResource == null || duplicatedResource.getSourcePath() == null || - duplicatedResource.getSourcePath().equals( resource.getSourcePath() ) ) { - this.results.add( new DuplicateRule( rule, - packageDescr, - this.configuration ) ); + if (resource == null || duplicatedResource == null || duplicatedResource.getSourcePath() == null || + duplicatedResource.getSourcePath().equals(resource.getSourcePath())) { + this.results.add(new DuplicateRule(rule, + packageDescr, + this.configuration)); } else { - this.results.add( new ParserError( rule.getResource(), - "Duplicate rule name: " + name, - rule.getLine(), - rule.getColumn(), - packageDescr.getNamespace() ) ); + this.results.add(new ParserError(rule.getResource(), + "Duplicate rule name: " + name, + rule.getLine(), + rule.getColumn(), + packageDescr.getNamespace())); } } } - names.add( name ); + names.add(name); } } private void validateRule(PackageDescr packageDescr, - RuleDescr rule) { - if ( rule.hasErrors() ) { - for ( String error : rule.getErrors() ) { - this.results.add( new ParserError( rule.getResource(), - error + " in rule " + rule.getName(), - rule.getLine(), - rule.getColumn(), - packageDescr.getNamespace() ) ); + RuleDescr rule) { + if (rule.hasErrors()) { + for (String error : rule.getErrors()) { + this.results.add(new ParserError(rule.getResource(), + error + " in rule " + rule.getName(), + rule.getLine(), + rule.getColumn(), + packageDescr.getNamespace())); } } } private PackageRegistry newPackage(final PackageDescr packageDescr) { Package pkg; - if ( this.ruleBase == null || (pkg = this.ruleBase.getPackage( packageDescr.getName() )) == null ) { + if (this.ruleBase == null || (pkg = this.ruleBase.getPackage(packageDescr.getName())) == null) { // there is no rulebase or it does not define this package so define it - pkg = new Package( packageDescr.getName() ); - pkg.setClassFieldAccessorCache( new ClassFieldAccessorCache( this.rootClassLoader ) ); + pkg = new Package(packageDescr.getName()); + pkg.setClassFieldAccessorCache(new ClassFieldAccessorCache(this.rootClassLoader)); // if there is a rulebase then add the package. - if ( this.ruleBase != null ) { + if (this.ruleBase != null) { // Must lock here, otherwise the assumption about addPackage/getPackage behavior below might be violated this.ruleBase.lock(); try { - this.ruleBase.addPackage( pkg ); - pkg = this.ruleBase.getPackage( packageDescr.getName() ); + this.ruleBase.addPackage(pkg); + pkg = this.ruleBase.getPackage(packageDescr.getName()); } finally { this.ruleBase.unlock(); } } else { // the RuleBase will also initialise the - pkg.getDialectRuntimeRegistry().onAdd( this.rootClassLoader ); + pkg.getDialectRuntimeRegistry().onAdd(this.rootClassLoader); } } - PackageRegistry pkgRegistry = new PackageRegistry( this, - pkg ); + PackageRegistry pkgRegistry = new PackageRegistry(this, + pkg); // add default import for this namespace - pkgRegistry.addImport( new ImportDescr( packageDescr.getNamespace() + ".*" ) ); + pkgRegistry.addImport(new ImportDescr(packageDescr.getNamespace() + ".*")); - this.pkgRegistryMap.put( packageDescr.getName(), - pkgRegistry ); + this.pkgRegistryMap.put(packageDescr.getName(), + pkgRegistry); return pkgRegistry; } private void mergePackage(PackageRegistry pkgRegistry, - PackageDescr packageDescr) { - for ( final ImportDescr importDescr : packageDescr.getImports() ) { - pkgRegistry.addImport( importDescr ); + PackageDescr packageDescr) { + for (final ImportDescr importDescr : packageDescr.getImports()) { + pkgRegistry.addImport(importDescr); } - processEntryPointDeclarations( pkgRegistry, packageDescr ); + processEntryPointDeclarations(pkgRegistry, packageDescr); // process types in 2 steps to deal with circular and recursive declarations - processUnresolvedTypes( pkgRegistry, processTypeDeclarations( pkgRegistry, packageDescr, new ArrayList<TypeDefinition>() ) ); + processUnresolvedTypes(pkgRegistry, processTypeDeclarations(pkgRegistry, packageDescr, new ArrayList<TypeDefinition>())); - processOtherDeclarations( pkgRegistry, packageDescr ); + processOtherDeclarations(pkgRegistry, packageDescr); } void processOtherDeclarations(PackageRegistry pkgRegistry, - PackageDescr packageDescr) { - processWindowDeclarations( pkgRegistry, packageDescr ); - processFunctions( pkgRegistry, packageDescr ); - processGlobals( pkgRegistry, packageDescr ); + PackageDescr packageDescr) { + processWindowDeclarations(pkgRegistry, packageDescr); + processFunctions(pkgRegistry, packageDescr); + processGlobals(pkgRegistry, packageDescr); // need to reinsert this to ensure that the package is the first/last one in the ordered map // this feature is exploited by the knowledgeAgent Package current = getPackage(); - this.pkgRegistryMap.remove( packageDescr.getName() ); - this.pkgRegistryMap.put( packageDescr.getName(), pkgRegistry ); - if ( !current.getName().equals( packageDescr.getName() ) ) { + this.pkgRegistryMap.remove(packageDescr.getName()); + this.pkgRegistryMap.put(packageDescr.getName(), pkgRegistry); + if (!current.getName().equals(packageDescr.getName())) { currentRulePackage = pkgRegistryMap.size() - 1; } } private void processGlobals(PackageRegistry pkgRegistry, - PackageDescr packageDescr) { - for ( final GlobalDescr global : packageDescr.getGlobals() ) { + PackageDescr packageDescr) { + for (final GlobalDescr global : packageDescr.getGlobals()) { final String identifier = global.getIdentifier(); String className = global.getType(); // JBRULES-3039: can't handle type name with generic params - while ( className.indexOf( '<' ) >= 0 ) { - className = className.replaceAll( "<[^<>]+?>", "" ); + while (className.indexOf('<') >= 0) { + className = className.replaceAll("<[^<>]+?>", ""); } try { - Class< ? > clazz = pkgRegistry.getTypeResolver().resolveType( className ); - if ( clazz.isPrimitive() ) { - this.results.add( new GlobalError( global, " Primitive types are not allowed in globals : " + className ) ); + Class<?> clazz = pkgRegistry.getTypeResolver().resolveType(className); + if (clazz.isPrimitive()) { + this.results.add(new GlobalError(global, " Primitive types are not allowed in globals : " + className)); return; } - pkgRegistry.getPackage().addGlobal( identifier, - clazz ); - this.globals.put( identifier, - clazz ); - } catch ( final ClassNotFoundException e ) { - this.results.add( new GlobalError( global, e.getMessage() ) ); + pkgRegistry.getPackage().addGlobal(identifier, + clazz); + this.globals.put(identifier, + clazz); + } catch (final ClassNotFoundException e) { + this.results.add(new GlobalError(global, e.getMessage())); e.printStackTrace(); } } } private void processFunctions(PackageRegistry pkgRegistry, - PackageDescr packageDescr) { - for ( FunctionDescr function : packageDescr.getFunctions() ) { - Function existingFunc = pkgRegistry.getPackage().getFunctions().get( function.getName() ); - if ( existingFunc != null && function.getNamespace().equals( existingFunc.getNamespace() ) ) { + PackageDescr packageDescr) { + for (FunctionDescr function : packageDescr.getFunctions()) { + Function existingFunc = pkgRegistry.getPackage().getFunctions().get(function.getName()); + if (existingFunc != null && function.getNamespace().equals(existingFunc.getNamespace())) { this.results.add( - new DuplicateFunction( function, - this.configuration ) ); + new DuplicateFunction(function, + this.configuration)); } } - for ( final FunctionImportDescr functionImport : packageDescr.getFunctionImports() ) { + for (final FunctionImportDescr functionImport : packageDescr.getFunctionImports()) { String importEntry = functionImport.getTarget(); - pkgRegistry.addStaticImport( functionImport ); - pkgRegistry.getPackage().addStaticImport( importEntry ); + pkgRegistry.addStaticImport(functionImport); + pkgRegistry.getPackage().addStaticImport(importEntry); } } @@ -1597,212 +1631,213 @@ void processUnresolvedType(PackageRegistry pkgRegistry, TypeDefinition unresolve processTypeFields(pkgRegistry, unresolvedTypeDefinition.typeDescr, unresolvedTypeDefinition.type, false); } - public TypeDeclaration getAndRegisterTypeDeclaration( Class<?> cls, String packageName ) { + public TypeDeclaration getAndRegisterTypeDeclaration(Class<?> cls, String packageName) { if (cls.isPrimitive() || cls.isArray()) { return null; } - TypeDeclaration typeDeclaration = getCachedTypeDeclaration( cls ); - if ( typeDeclaration != null ) { - registerTypeDeclaration( packageName, typeDeclaration ); + TypeDeclaration typeDeclaration = getCachedTypeDeclaration(cls); + if (typeDeclaration != null) { + registerTypeDeclaration(packageName, typeDeclaration); return typeDeclaration; } - typeDeclaration = getExistingTypeDeclaration( cls ); - if ( typeDeclaration != null ) { - initTypeDeclaration( cls, typeDeclaration ); + typeDeclaration = getExistingTypeDeclaration(cls); + if (typeDeclaration != null) { + initTypeDeclaration(cls, typeDeclaration); return typeDeclaration; } - typeDeclaration = createTypeDeclarationForBean( cls ); - initTypeDeclaration( cls, typeDeclaration ); - registerTypeDeclaration( packageName, typeDeclaration ); + typeDeclaration = createTypeDeclarationForBean(cls); + initTypeDeclaration(cls, typeDeclaration); + registerTypeDeclaration(packageName, typeDeclaration); return typeDeclaration; } private void registerTypeDeclaration(String packageName, - TypeDeclaration typeDeclaration) { - if ( typeDeclaration.getNature() == TypeDeclaration.Nature.DECLARATION || packageName.equals( typeDeclaration.getTypeClass().getPackage().getName() ) ) { - PackageRegistry packageRegistry = pkgRegistryMap.get( packageName ); - if ( packageRegistry != null ) { - packageRegistry.getPackage().addTypeDeclaration( typeDeclaration ); + TypeDeclaration typeDeclaration) { + if (typeDeclaration.getNature() == TypeDeclaration.Nature.DECLARATION || packageName.equals(typeDeclaration.getTypeClass().getPackage().getName())) { + PackageRegistry packageRegistry = pkgRegistryMap.get(packageName); + if (packageRegistry != null) { + packageRegistry.getPackage().addTypeDeclaration(typeDeclaration); } else { - newPackage( new PackageDescr( packageName, "" ) ); - pkgRegistryMap.get( packageName ).getPackage().addTypeDeclaration( typeDeclaration ); + newPackage(new PackageDescr(packageName, "")); + pkgRegistryMap.get(packageName).getPackage().addTypeDeclaration(typeDeclaration); } } } - public TypeDeclaration getTypeDeclaration(Class< ? > cls) { - if ( cls.isPrimitive() || cls.isArray() ) return null; + public TypeDeclaration getTypeDeclaration(Class<?> cls) { + if (cls.isPrimitive() || cls.isArray()) + return null; // If this class has already been accessed, it'll be in the cache - TypeDeclaration tdecl = getCachedTypeDeclaration( cls ); - return tdecl != null ? tdecl : createTypeDeclaration( cls ); + TypeDeclaration tdecl = getCachedTypeDeclaration(cls); + return tdecl != null ? tdecl : createTypeDeclaration(cls); } - private TypeDeclaration createTypeDeclaration(Class< ? > cls) { - TypeDeclaration typeDeclaration = getExistingTypeDeclaration( cls ); + private TypeDeclaration createTypeDeclaration(Class<?> cls) { + TypeDeclaration typeDeclaration = getExistingTypeDeclaration(cls); - if ( typeDeclaration == null ) { - typeDeclaration = createTypeDeclarationForBean( cls ); + if (typeDeclaration == null) { + typeDeclaration = createTypeDeclarationForBean(cls); } - initTypeDeclaration( cls, typeDeclaration ); + initTypeDeclaration(cls, typeDeclaration); return typeDeclaration; } - private TypeDeclaration getCachedTypeDeclaration(Class< ? > cls) { - if ( this.cacheTypes == null ) { + private TypeDeclaration getCachedTypeDeclaration(Class<?> cls) { + if (this.cacheTypes == null) { this.cacheTypes = new HashMap<String, TypeDeclaration>(); return null; } else { - return cacheTypes.get( cls.getName() ); + return cacheTypes.get(cls.getName()); } } - private TypeDeclaration getExistingTypeDeclaration(Class< ? > cls) { + private TypeDeclaration getExistingTypeDeclaration(Class<?> cls) { // Check if we are in the built-ins - TypeDeclaration typeDeclaration = this.builtinTypes.get( (cls.getName()) ); - if ( typeDeclaration == null ) { + TypeDeclaration typeDeclaration = this.builtinTypes.get((cls.getName())); + if (typeDeclaration == null) { // No built-in // Check if there is a user specified typedeclr - PackageRegistry pkgReg = this.pkgRegistryMap.get( ClassUtils.getPackage( cls ) ); - if ( pkgReg != null ) { + PackageRegistry pkgReg = this.pkgRegistryMap.get(ClassUtils.getPackage(cls)); + if (pkgReg != null) { String className = cls.getName(); - String typeName = className.substring( className.lastIndexOf( "." ) + 1 ); - typeDeclaration = pkgReg.getPackage().getTypeDeclaration( typeName ); + String typeName = className.substring(className.lastIndexOf(".") + 1); + typeDeclaration = pkgReg.getPackage().getTypeDeclaration(typeName); } } return typeDeclaration; } - private void initTypeDeclaration(Class< ? > cls, - TypeDeclaration typeDeclaration) { + private void initTypeDeclaration(Class<?> cls, + TypeDeclaration typeDeclaration) { ClassDefinition clsDef = typeDeclaration.getTypeClassDef(); - if ( clsDef == null ) { + if (clsDef == null) { clsDef = new ClassDefinition(); - typeDeclaration.setTypeClassDef( clsDef ); + typeDeclaration.setTypeClassDef(clsDef); } - if ( typeDeclaration.isPropertyReactive() ) { - processModifiedProps( cls, clsDef ); + if (typeDeclaration.isPropertyReactive()) { + processModifiedProps(cls, clsDef); } - processFieldsPosition( cls, clsDef ); + processFieldsPosition(cls, clsDef); // build up a set of all the super classes and interfaces Set<TypeDeclaration> tdecls = new LinkedHashSet<TypeDeclaration>(); - tdecls.add( typeDeclaration ); - buildTypeDeclarations( cls, - tdecls ); + tdecls.add(typeDeclaration); + buildTypeDeclarations(cls, + tdecls); // Iterate and for each typedeclr assign it's value if it's not already set // We start from the rear as those are the furthest away classes and interfaces - TypeDeclaration[] tarray = tdecls.toArray( new TypeDeclaration[tdecls.size()] ); - for ( int i = tarray.length - 1; i >= 0; i-- ) { + TypeDeclaration[] tarray = tdecls.toArray(new TypeDeclaration[tdecls.size()]); + for (int i = tarray.length - 1; i >= 0; i--) { TypeDeclaration currentTDecl = tarray[i]; - if ( !isSet( typeDeclaration.getSetMask(), - TypeDeclaration.ROLE_BIT ) && isSet( currentTDecl.getSetMask(), - TypeDeclaration.ROLE_BIT ) ) { - typeDeclaration.setRole( currentTDecl.getRole() ); + if (!isSet(typeDeclaration.getSetMask(), + TypeDeclaration.ROLE_BIT) && isSet(currentTDecl.getSetMask(), + TypeDeclaration.ROLE_BIT)) { + typeDeclaration.setRole(currentTDecl.getRole()); } - if ( !isSet( typeDeclaration.getSetMask(), - TypeDeclaration.FORMAT_BIT ) && isSet( currentTDecl.getSetMask(), - TypeDeclaration.FORMAT_BIT ) ) { - typeDeclaration.setFormat( currentTDecl.getFormat() ); + if (!isSet(typeDeclaration.getSetMask(), + TypeDeclaration.FORMAT_BIT) && isSet(currentTDecl.getSetMask(), + TypeDeclaration.FORMAT_BIT)) { + typeDeclaration.setFormat(currentTDecl.getFormat()); } - if ( !isSet( typeDeclaration.getSetMask(), - TypeDeclaration.TYPESAFE_BIT ) && isSet( currentTDecl.getSetMask(), - TypeDeclaration.TYPESAFE_BIT ) ) { - typeDeclaration.setTypesafe( currentTDecl.isTypesafe() ); + if (!isSet(typeDeclaration.getSetMask(), + TypeDeclaration.TYPESAFE_BIT) && isSet(currentTDecl.getSetMask(), + TypeDeclaration.TYPESAFE_BIT)) { + typeDeclaration.setTypesafe(currentTDecl.isTypesafe()); } } - this.cacheTypes.put( cls.getName(), - typeDeclaration ); + this.cacheTypes.put(cls.getName(), + typeDeclaration); } - private TypeDeclaration createTypeDeclarationForBean(Class< ? > cls) { - TypeDeclaration typeDeclaration = new TypeDeclaration( cls ); + private TypeDeclaration createTypeDeclarationForBean(Class<?> cls) { + TypeDeclaration typeDeclaration = new TypeDeclaration(cls); - PropertySpecificOption propertySpecificOption = configuration.getOption( PropertySpecificOption.class ); - boolean propertyReactive = propertySpecificOption.isPropSpecific( cls.isAnnotationPresent( PropertyReactive.class ), - cls.isAnnotationPresent( ClassReactive.class ) ); + PropertySpecificOption propertySpecificOption = configuration.getOption(PropertySpecificOption.class); + boolean propertyReactive = propertySpecificOption.isPropSpecific(cls.isAnnotationPresent(PropertyReactive.class), + cls.isAnnotationPresent(ClassReactive.class)); - setPropertyReactive( null, typeDeclaration, propertyReactive ); + setPropertyReactive(null, typeDeclaration, propertyReactive); - Role role = cls.getAnnotation( Role.class ); - if ( role != null && role.value() == Role.Type.EVENT) { + Role role = cls.getAnnotation(Role.class); + if (role != null && role.value() == Role.Type.EVENT) { typeDeclaration.setRole(TypeDeclaration.Role.EVENT); } return typeDeclaration; } - private void processModifiedProps(Class< ? > cls, - ClassDefinition clsDef) { - for ( Method method : cls.getDeclaredMethods() ) { - Modifies modifies = method.getAnnotation( Modifies.class ); - if ( modifies != null ) { + private void processModifiedProps(Class<?> cls, + ClassDefinition clsDef) { + for (Method method : cls.getDeclaredMethods()) { + Modifies modifies = method.getAnnotation(Modifies.class); + if (modifies != null) { String[] props = modifies.value(); - List<String> properties = new ArrayList<String>( props.length ); - for ( String prop : props ) { - properties.add( prop.trim() ); + List<String> properties = new ArrayList<String>(props.length); + for (String prop : props) { + properties.add(prop.trim()); } - clsDef.addModifiedPropsByMethod( method, - properties ); + clsDef.addModifiedPropsByMethod(method, + properties); } } } - private void processFieldsPosition(Class< ? > cls, - ClassDefinition clsDef) { + private void processFieldsPosition(Class<?> cls, + ClassDefinition clsDef) { // it's a new type declaration, so generate the @Position for it Collection<Field> fields = new LinkedList<Field>(); - Class< ? > tempKlass = cls; - while ( tempKlass != null && tempKlass != Object.class ) { - Collections.addAll( fields, tempKlass.getDeclaredFields() ); + Class<?> tempKlass = cls; + while (tempKlass != null && tempKlass != Object.class) { + Collections.addAll(fields, tempKlass.getDeclaredFields()); tempKlass = tempKlass.getSuperclass(); } - List<FieldDefinition> orderedFields = new ArrayList<FieldDefinition>( fields.size() ); - for ( int i = 0; i < fields.size(); i++ ) { + List<FieldDefinition> orderedFields = new ArrayList<FieldDefinition>(fields.size()); + for (int i = 0; i < fields.size(); i++) { // as these could be set in any order, initialise first, to allow setting later. - orderedFields.add( null ); + orderedFields.add(null); } - for ( Field fld : fields ) { - Position pos = fld.getAnnotation( Position.class ); - if ( pos != null ) { + for (Field fld : fields) { + Position pos = fld.getAnnotation(Position.class); + if (pos != null) { FieldDefinition fldDef = clsDef.getField(fld.getName()); if (fldDef == null) { - fldDef = new FieldDefinition( fld.getName(), fld.getType().getName() ); + fldDef = new FieldDefinition(fld.getName(), fld.getType().getName()); } - fldDef.setIndex( pos.value() ); - orderedFields.set( pos.value(), fldDef ); + fldDef.setIndex(pos.value()); + orderedFields.set(pos.value(), fldDef); } } - for ( FieldDefinition fld : orderedFields ) { - if ( fld != null ) { + for (FieldDefinition fld : orderedFields) { + if (fld != null) { // it's null if there is no @Position - clsDef.addField( fld ); + clsDef.addField(fld); } } } - public void buildTypeDeclarations(Class< ? > cls, - Set<TypeDeclaration> tdecls) { + public void buildTypeDeclarations(Class<?> cls, + Set<TypeDeclaration> tdecls) { // Process current interfaces - Class< ? >[] intfs = cls.getInterfaces(); - for ( Class< ? > intf : intfs ) { - buildTypeDeclarationInterfaces( intf, - tdecls ); + Class<?>[] intfs = cls.getInterfaces(); + for (Class<?> intf : intfs) { + buildTypeDeclarationInterfaces(intf, + tdecls); } // Process super classes and their interfaces cls = cls.getSuperclass(); - while ( cls != null && cls != Object.class ) { - if ( !buildTypeDeclarationInterfaces( cls, - tdecls ) ) { + while (cls != null && cls != Object.class) { + if (!buildTypeDeclarationInterfaces(cls, + tdecls)) { break; } cls = cls.getSuperclass(); @@ -1811,36 +1846,36 @@ public void buildTypeDeclarations(Class< ? > cls, } public boolean buildTypeDeclarationInterfaces(Class cls, - Set<TypeDeclaration> tdecls) { + Set<TypeDeclaration> tdecls) { PackageRegistry pkgReg; - TypeDeclaration tdecl = this.builtinTypes.get( (cls.getName()) ); - if ( tdecl == null ) { - pkgReg = this.pkgRegistryMap.get( ClassUtils.getPackage( cls ) ); - if ( pkgReg != null ) { - tdecl = pkgReg.getPackage().getTypeDeclaration( cls.getSimpleName() ); + TypeDeclaration tdecl = this.builtinTypes.get((cls.getName())); + if (tdecl == null) { + pkgReg = this.pkgRegistryMap.get(ClassUtils.getPackage(cls)); + if (pkgReg != null) { + tdecl = pkgReg.getPackage().getTypeDeclaration(cls.getSimpleName()); } } - if ( tdecl != null ) { - if ( !tdecls.add( tdecl ) ) { + if (tdecl != null) { + if (!tdecls.add(tdecl)) { return false; // the interface already exists, return to stop recursion } } - Class< ? >[] intfs = cls.getInterfaces(); - for ( Class< ? > intf : intfs ) { - pkgReg = this.pkgRegistryMap.get( ClassUtils.getPackage( intf ) ); - if ( pkgReg != null ) { - tdecl = pkgReg.getPackage().getTypeDeclaration( intf.getSimpleName() ); + Class<?>[] intfs = cls.getInterfaces(); + for (Class<?> intf : intfs) { + pkgReg = this.pkgRegistryMap.get(ClassUtils.getPackage(intf)); + if (pkgReg != null) { + tdecl = pkgReg.getPackage().getTypeDeclaration(intf.getSimpleName()); } - if ( tdecl != null ) { - tdecls.add( tdecl ); + if (tdecl != null) { + tdecls.add(tdecl); } } - for ( Class< ? > intf : intfs ) { - if ( !buildTypeDeclarationInterfaces( intf, - tdecls ) ) { + for (Class<?> intf : intfs) { + if (!buildTypeDeclarationInterfaces(intf, + tdecls)) { return false; } } @@ -1864,12 +1899,12 @@ public boolean buildTypeDeclarationInterfaces(Class cls, * @return the fully qualified name of the superclass */ private String resolveType(String sup, - PackageDescr packageDescr, - PackageRegistry pkgRegistry) { + PackageDescr packageDescr, + PackageRegistry pkgRegistry) { //look among imports - for ( ImportDescr id : packageDescr.getImports() ) { - if ( id.getTarget().endsWith( "." + sup ) ) { + for (ImportDescr id : packageDescr.getImports()) { + if (id.getTarget().endsWith("." + sup)) { //logger.info("Replace supertype " + sup + " with full name " + id.getTarget()); return id.getTarget(); @@ -1877,15 +1912,17 @@ private String resolveType(String sup, } //look among local declarations - if ( pkgRegistry != null ) { - for ( String declaredName : pkgRegistry.getPackage().getTypeDeclarations().keySet() ) { - if ( declaredName.equals( sup ) ) sup = pkgRegistry.getPackage().getTypeDeclaration( declaredName ).getTypeClass().getName(); + if (pkgRegistry != null) { + for (String declaredName : pkgRegistry.getPackage().getTypeDeclarations().keySet()) { + if (declaredName.equals(sup)) + sup = pkgRegistry.getPackage().getTypeDeclaration(declaredName).getTypeClass().getName(); } } - if ( (sup != null) && (!sup.contains( "." )) && (packageDescr.getNamespace() != null && !packageDescr.getNamespace().isEmpty()) ) { - for ( AbstractClassTypeDeclarationDescr td : packageDescr.getClassAndEnumDeclarationDescrs() ) { - if ( sup.equals( td.getTypeName() ) ) sup = packageDescr.getNamespace() + "." + sup; + if ((sup != null) && (!sup.contains(".")) && (packageDescr.getNamespace() != null && !packageDescr.getNamespace().isEmpty())) { + for (AbstractClassTypeDeclarationDescr td : packageDescr.getClassAndEnumDeclarationDescrs()) { + if (sup.equals(td.getTypeName())) + sup = packageDescr.getNamespace() + "." + sup; } } @@ -1906,34 +1943,34 @@ private String resolveType(String sup, * the descriptor of the package the class is declared in */ private void fillSuperType(TypeDeclarationDescr typeDescr, - PackageDescr packageDescr) { + PackageDescr packageDescr) { - for ( QualifiedName qname : typeDescr.getSuperTypes() ) { + for (QualifiedName qname : typeDescr.getSuperTypes()) { String declaredSuperType = qname.getFullName(); - if ( declaredSuperType != null ) { - int separator = declaredSuperType.lastIndexOf( "." ); + if (declaredSuperType != null) { + int separator = declaredSuperType.lastIndexOf("."); boolean qualified = separator > 0; // check if a simple name corresponds to a f.q.n. - if ( !qualified ) { + if (!qualified) { declaredSuperType = - resolveType( declaredSuperType, - packageDescr, - this.pkgRegistryMap.get( typeDescr.getNamespace() ) ); + resolveType(declaredSuperType, + packageDescr, + this.pkgRegistryMap.get(typeDescr.getNamespace())); - declaredSuperType = typeName2ClassName( declaredSuperType ); + declaredSuperType = typeName2ClassName(declaredSuperType); // sets supertype name and supertype package - separator = declaredSuperType.lastIndexOf( "." ); - if ( separator < 0 ) { - this.results.add( new TypeDeclarationError( typeDescr, - "Cannot resolve supertype '" + declaredSuperType + "'" ) ); - qname.setName( null ); - qname.setNamespace( null ); + separator = declaredSuperType.lastIndexOf("."); + if (separator < 0) { + this.results.add(new TypeDeclarationError(typeDescr, + "Cannot resolve supertype '" + declaredSuperType + "'")); + qname.setName(null); + qname.setNamespace(null); } else { - qname.setName( declaredSuperType.substring( separator + 1 ) ); - qname.setNamespace( declaredSuperType.substring( 0, - separator ) ); + qname.setName(declaredSuperType.substring(separator + 1)); + qname.setNamespace(declaredSuperType.substring(0, + separator)); } } } @@ -1941,45 +1978,45 @@ private void fillSuperType(TypeDeclarationDescr typeDescr, } private String typeName2ClassName(String type) { - Class< ? > cls = getClassForType( type ); + Class<?> cls = getClassForType(type); return cls != null ? cls.getName() : type; } - private Class< ? > getClassForType(String type) { - Class< ? > cls = null; + private Class<?> getClassForType(String type) { + Class<?> cls = null; String superType = type; - while ( true ) { + while (true) { try { - cls = Class.forName( superType, true, this.rootClassLoader ); + cls = Class.forName(superType, true, this.rootClassLoader); break; - } catch ( ClassNotFoundException e ) { + } catch (ClassNotFoundException e) { } - int separator = superType.lastIndexOf( '.' ); - if ( separator < 0 ) { + int separator = superType.lastIndexOf('.'); + if (separator < 0) { break; } - superType = superType.substring( 0, separator ) + "$" + superType.substring( separator + 1 ); + superType = superType.substring(0, separator) + "$" + superType.substring(separator + 1); } return cls; } private void fillFieldTypes(AbstractClassTypeDeclarationDescr typeDescr, - PackageDescr packageDescr) { + PackageDescr packageDescr) { - for ( TypeFieldDescr field : typeDescr.getFields().values() ) { + for (TypeFieldDescr field : typeDescr.getFields().values()) { String declaredType = field.getPattern().getObjectType(); - if ( declaredType != null ) { - int separator = declaredType.lastIndexOf( "." ); + if (declaredType != null) { + int separator = declaredType.lastIndexOf("."); boolean qualified = separator > 0; // check if a simple name corresponds to a f.q.n. - if ( !qualified ) { + if (!qualified) { declaredType = - resolveType( declaredType, - packageDescr, - this.pkgRegistryMap.get( typeDescr.getNamespace() ) ); + resolveType(declaredType, + packageDescr, + this.pkgRegistryMap.get(typeDescr.getNamespace())); - field.getPattern().setObjectType( declaredType ); + field.getPattern().setObjectType(declaredType); } } } @@ -2008,40 +2045,41 @@ private void fillFieldTypes(AbstractClassTypeDeclarationDescr typeDescr, */ private boolean mergeInheritedFields(TypeDeclarationDescr typeDescr) { - if ( typeDescr.getSuperTypes().isEmpty() ) return false; + if (typeDescr.getSuperTypes().isEmpty()) + return false; boolean merge = false; - for ( int j = typeDescr.getSuperTypes().size() - 1; j >= 0; j-- ) { - QualifiedName qname = typeDescr.getSuperTypes().get( j ); + for (int j = typeDescr.getSuperTypes().size() - 1; j >= 0; j--) { + QualifiedName qname = typeDescr.getSuperTypes().get(j); String simpleSuperTypeName = qname.getName(); String superTypePackageName = qname.getNamespace(); String fullSuper = qname.getFullName(); - merge = mergeInheritedFields( simpleSuperTypeName, - superTypePackageName, - fullSuper, - typeDescr ) || merge; + merge = mergeInheritedFields(simpleSuperTypeName, + superTypePackageName, + fullSuper, + typeDescr) || merge; } return merge; } private boolean mergeInheritedFields(String simpleSuperTypeName, - String superTypePackageName, - String fullSuper, - TypeDeclarationDescr typeDescr) { + String superTypePackageName, + String fullSuper, + TypeDeclarationDescr typeDescr) { Map<String, TypeFieldDescr> fieldMap = new LinkedHashMap<String, TypeFieldDescr>(); - PackageRegistry registry = this.pkgRegistryMap.get( superTypePackageName ); + PackageRegistry registry = this.pkgRegistryMap.get(superTypePackageName); Package pack; - if ( registry != null ) { + if (registry != null) { pack = registry.getPackage(); } else { // If there is no regisrty the type isn't a DRL-declared type, which is forbidden. // Avoid NPE JIRA-3041 when trying to access the registry. Avoid subsequent problems. - this.results.add( new TypeDeclarationError( typeDescr, "Cannot extend supertype '" + fullSuper + "' (not a declared type)" ) ); - typeDescr.setType( null, null ); + this.results.add(new TypeDeclarationError(typeDescr, "Cannot extend supertype '" + fullSuper + "' (not a declared type)")); + typeDescr.setType(null, null); return false; } @@ -2049,18 +2087,18 @@ private boolean mergeInheritedFields(String simpleSuperTypeName, boolean isSuperClassTagged = false; boolean isSuperClassDeclared = true; //in the same package, or in a previous one - if ( pack != null ) { + if (pack != null) { // look for the supertype declaration in available packages - TypeDeclaration superTypeDeclaration = pack.getTypeDeclaration( simpleSuperTypeName ); + TypeDeclaration superTypeDeclaration = pack.getTypeDeclaration(simpleSuperTypeName); - if ( superTypeDeclaration != null ) { + if (superTypeDeclaration != null) { ClassDefinition classDef = superTypeDeclaration.getTypeClassDef(); // inherit fields - for ( FactField fld : classDef.getFields() ) { - TypeFieldDescr inheritedFlDescr = buildInheritedFieldDescrFromDefinition( fld, typeDescr ); - fieldMap.put( inheritedFlDescr.getFieldName(), - inheritedFlDescr ); + for (FactField fld : classDef.getFields()) { + TypeFieldDescr inheritedFlDescr = buildInheritedFieldDescrFromDefinition(fld, typeDescr); + fieldMap.put(inheritedFlDescr.getFieldName(), + inheritedFlDescr); } // new classes are already distinguished from tagged external classes @@ -2074,113 +2112,114 @@ private boolean mergeInheritedFields(String simpleSuperTypeName, } // look for the class externally - if ( !isSuperClassDeclared || isSuperClassTagged ) { + if (!isSuperClassDeclared || isSuperClassTagged) { try { - Class superKlass = registry.getTypeResolver().resolveType( fullSuper ); - ClassFieldInspector inspector = new ClassFieldInspector( superKlass ); - for ( String name : inspector.getGetterMethods().keySet() ) { + Class superKlass = registry.getTypeResolver().resolveType(fullSuper); + ClassFieldInspector inspector = new ClassFieldInspector(superKlass); + for (String name : inspector.getGetterMethods().keySet()) { // classFieldAccessor requires both getter and setter - if ( inspector.getSetterMethods().containsKey( name ) ) { - if ( !inspector.isNonGetter( name ) && !"class".equals( name ) ) { + if (inspector.getSetterMethods().containsKey(name)) { + if (!inspector.isNonGetter(name) && !"class".equals(name)) { TypeFieldDescr inheritedFlDescr = new TypeFieldDescr( - name, - new PatternDescr( - inspector.getFieldTypes().get( name ).getName() ) ); + name, + new PatternDescr( + inspector.getFieldTypes().get(name).getName())); inheritedFlDescr.setInherited(!Modifier.isAbstract(inspector.getGetterMethods().get(name).getModifiers())); - if ( !fieldMap.containsKey( inheritedFlDescr.getFieldName() ) ) fieldMap.put( inheritedFlDescr.getFieldName(), - inheritedFlDescr ); + if (!fieldMap.containsKey(inheritedFlDescr.getFieldName())) + fieldMap.put(inheritedFlDescr.getFieldName(), + inheritedFlDescr); } } } - } catch ( ClassNotFoundException cnfe ) { - throw new RuntimeDroolsException( "Unable to resolve Type Declaration superclass '" + fullSuper + "'" ); - } catch ( IOException e ) { + } catch (ClassNotFoundException cnfe) { + throw new RuntimeDroolsException("Unable to resolve Type Declaration superclass '" + fullSuper + "'"); + } catch (IOException e) { } } // finally, locally declared fields are merged. The map swap ensures that super-fields are added in order, before the subclass' ones // notice that it is not possible to override a field changing its type - for ( String fieldName : typeDescr.getFields().keySet() ) { - if ( fieldMap.containsKey( fieldName ) ) { - String type1 = fieldMap.get( fieldName ).getPattern().getObjectType(); - String type2 = typeDescr.getFields().get( fieldName ).getPattern().getObjectType(); - if ( type2.lastIndexOf( "." ) < 0 ) { + for (String fieldName : typeDescr.getFields().keySet()) { + if (fieldMap.containsKey(fieldName)) { + String type1 = fieldMap.get(fieldName).getPattern().getObjectType(); + String type2 = typeDescr.getFields().get(fieldName).getPattern().getObjectType(); + if (type2.lastIndexOf(".") < 0) { try { - TypeResolver typeResolver = pkgRegistryMap.get( pack.getName() ).getTypeResolver(); - type1 = typeResolver.resolveType( type1 ).getName(); - type2 = typeResolver.resolveType( type2 ).getName(); + TypeResolver typeResolver = pkgRegistryMap.get(pack.getName()).getTypeResolver(); + type1 = typeResolver.resolveType(type1).getName(); + type2 = typeResolver.resolveType(type2).getName(); // now that we are at it... this will be needed later anyway - fieldMap.get( fieldName ).getPattern().setObjectType( type1 ); - typeDescr.getFields().get( fieldName ).getPattern().setObjectType( type2 ); - } catch ( ClassNotFoundException cnfe ) { + fieldMap.get(fieldName).getPattern().setObjectType(type1); + typeDescr.getFields().get(fieldName).getPattern().setObjectType(type2); + } catch (ClassNotFoundException cnfe) { // will fail later } } - if ( !type1.equals( type2 ) ) { - this.results.add( new TypeDeclarationError( typeDescr, - "Cannot redeclare field '" + fieldName + " from " + type1 + " to " + type2 ) ); - typeDescr.setType( null, - null ); + if (!type1.equals(type2)) { + this.results.add(new TypeDeclarationError(typeDescr, + "Cannot redeclare field '" + fieldName + " from " + type1 + " to " + type2)); + typeDescr.setType(null, + null); return false; } else { - String initVal = fieldMap.get( fieldName ).getInitExpr(); - if ( typeDescr.getFields().get( fieldName ).getInitExpr() == null ) { - typeDescr.getFields().get( fieldName ).setInitExpr( initVal ); + String initVal = fieldMap.get(fieldName).getInitExpr(); + if (typeDescr.getFields().get(fieldName).getInitExpr() == null) { + typeDescr.getFields().get(fieldName).setInitExpr(initVal); } - typeDescr.getFields().get( fieldName ).setInherited( fieldMap.get( fieldName ).isInherited() ); + typeDescr.getFields().get(fieldName).setInherited(fieldMap.get(fieldName).isInherited()); - for ( String key : fieldMap.get( fieldName ).getAnnotationNames() ) { - if ( typeDescr.getFields().get( fieldName ).getAnnotation( key ) == null ) { - typeDescr.getFields().get( fieldName ).addAnnotation( fieldMap.get( fieldName ).getAnnotation( key ) ); + for (String key : fieldMap.get(fieldName).getAnnotationNames()) { + if (typeDescr.getFields().get(fieldName).getAnnotation(key) == null) { + typeDescr.getFields().get(fieldName).addAnnotation(fieldMap.get(fieldName).getAnnotation(key)); } } - if ( typeDescr.getFields().get( fieldName ).getIndex() < 0 ) { - typeDescr.getFields().get( fieldName ).setIndex( fieldMap.get( fieldName ).getIndex() ); + if (typeDescr.getFields().get(fieldName).getIndex() < 0) { + typeDescr.getFields().get(fieldName).setIndex(fieldMap.get(fieldName).getIndex()); } } } - fieldMap.put( fieldName, - typeDescr.getFields().get( fieldName ) ); + fieldMap.put(fieldName, + typeDescr.getFields().get(fieldName)); } - typeDescr.setFields( fieldMap ); + typeDescr.setFields(fieldMap); return true; } - protected TypeFieldDescr buildInheritedFieldDescrFromDefinition( FactField fld, TypeDeclarationDescr typeDescr ) { + protected TypeFieldDescr buildInheritedFieldDescrFromDefinition(FactField fld, TypeDeclarationDescr typeDescr) { PatternDescr fldType = new PatternDescr(); TypeFieldDescr inheritedFldDescr = new TypeFieldDescr(); - inheritedFldDescr.setFieldName( fld.getName() ); - fldType.setObjectType( ((FieldDefinition) fld).getFieldAccessor().getExtractToClassName() ); - inheritedFldDescr.setPattern( fldType ); - if ( fld.isKey() ) { - inheritedFldDescr.getAnnotations().put( TypeDeclaration.ATTR_KEY, - new AnnotationDescr( TypeDeclaration.ATTR_KEY ) ); - } - inheritedFldDescr.setIndex( ( (FieldDefinition) fld ).getDeclIndex() ); - inheritedFldDescr.setInherited( true ); - - String initExprOverride = ( (FieldDefinition) fld ).getInitExpr(); - int overrideCount = 0; - // only @aliasing local fields may override defaults. - for ( TypeFieldDescr localField : typeDescr.getFields().values() ) { - AnnotationDescr ann = localField.getAnnotation( "Alias" ); - if ( ann != null && fld.getName().equals( ann.getSingleValue().replaceAll( "\"", "" ) ) && localField.getInitExpr() != null ) { - overrideCount++; - initExprOverride = localField.getInitExpr(); - } - } - if ( overrideCount > 1 ) { - // however, only one is allowed - initExprOverride = null; - } - inheritedFldDescr.setInitExpr( initExprOverride ); + inheritedFldDescr.setFieldName(fld.getName()); + fldType.setObjectType(((FieldDefinition) fld).getFieldAccessor().getExtractToClassName()); + inheritedFldDescr.setPattern(fldType); + if (fld.isKey()) { + inheritedFldDescr.getAnnotations().put(TypeDeclaration.ATTR_KEY, + new AnnotationDescr(TypeDeclaration.ATTR_KEY)); + } + inheritedFldDescr.setIndex(((FieldDefinition) fld).getDeclIndex()); + inheritedFldDescr.setInherited(true); + + String initExprOverride = ((FieldDefinition) fld).getInitExpr(); + int overrideCount = 0; + // only @aliasing local fields may override defaults. + for (TypeFieldDescr localField : typeDescr.getFields().values()) { + AnnotationDescr ann = localField.getAnnotation("Alias"); + if (ann != null && fld.getName().equals(ann.getSingleValue().replaceAll("\"", "")) && localField.getInitExpr() != null) { + overrideCount++; + initExprOverride = localField.getInitExpr(); + } + } + if (overrideCount > 1) { + // however, only one is allowed + initExprOverride = null; + } + inheritedFldDescr.setInitExpr(initExprOverride); return inheritedFldDescr; } @@ -2188,173 +2227,174 @@ protected TypeFieldDescr buildInheritedFieldDescrFromDefinition( FactField fld, * @param packageDescr */ void processEntryPointDeclarations(PackageRegistry pkgRegistry, - PackageDescr packageDescr) { - for ( EntryPointDeclarationDescr epDescr : packageDescr.getEntryPointDeclarations() ) { - pkgRegistry.getPackage().addEntryPointId( epDescr.getEntryPointId() ); + PackageDescr packageDescr) { + for (EntryPointDeclarationDescr epDescr : packageDescr.getEntryPointDeclarations()) { + pkgRegistry.getPackage().addEntryPointId(epDescr.getEntryPointId()); } } private void processWindowDeclarations(PackageRegistry pkgRegistry, - PackageDescr packageDescr) { - for ( WindowDeclarationDescr wd : packageDescr.getWindowDeclarations() ) { - WindowDeclaration window = new WindowDeclaration( wd.getName(), packageDescr.getName() ); + PackageDescr packageDescr) { + for (WindowDeclarationDescr wd : packageDescr.getWindowDeclarations()) { + WindowDeclaration window = new WindowDeclaration(wd.getName(), packageDescr.getName()); // TODO: process annotations // process pattern Package pkg = pkgRegistry.getPackage(); DialectCompiletimeRegistry ctr = pkgRegistry.getDialectCompiletimeRegistry(); - RuleDescr dummy = new RuleDescr( wd.getName() + " Window Declaration" ); - dummy.addAttribute( new AttributeDescr( "dialect", "java" ) ); - RuleBuildContext context = new RuleBuildContext( this, - dummy, - ctr, - pkg, - ctr.getDialect( pkgRegistry.getDialect() ) ); - final RuleConditionBuilder builder = (RuleConditionBuilder) context.getDialect().getBuilder( wd.getPattern().getClass() ); - if ( builder != null ) { - final Pattern pattern = (Pattern) builder.build( context, - wd.getPattern(), - null ); - - window.setPattern( pattern ); + RuleDescr dummy = new RuleDescr(wd.getName() + " Window Declaration"); + dummy.addAttribute(new AttributeDescr("dialect", "java")); + RuleBuildContext context = new RuleBuildContext(this, + dummy, + ctr, + pkg, + ctr.getDialect(pkgRegistry.getDialect())); + final RuleConditionBuilder builder = (RuleConditionBuilder) context.getDialect().getBuilder(wd.getPattern().getClass()); + if (builder != null) { + final Pattern pattern = (Pattern) builder.build(context, + wd.getPattern(), + null); + + window.setPattern(pattern); } else { throw new RuntimeDroolsException( - "BUG: builder not found for descriptor class " + wd.getPattern().getClass() ); + "BUG: builder not found for descriptor class " + wd.getPattern().getClass()); } - if ( !context.getErrors().isEmpty() ) { - for ( DroolsError error : context.getErrors() ) { - this.results.add( error ); + if (!context.getErrors().isEmpty()) { + for (DroolsError error : context.getErrors()) { + this.results.add(error); } } else { - pkgRegistry.getPackage().addWindowDeclaration( window ); + pkgRegistry.getPackage().addWindowDeclaration(window); } } } void registerGeneratedType(AbstractClassTypeDeclarationDescr typeDescr) { String fullName = typeDescr.getType().getFullName(); - generatedTypes.add( fullName ); + generatedTypes.add(fullName); } /** * @param packageDescr */ List<TypeDefinition> processTypeDeclarations(PackageRegistry pkgRegistry, PackageDescr packageDescr, List<TypeDefinition> unresolvedTypes) { - for ( AbstractClassTypeDeclarationDescr typeDescr : packageDescr.getClassAndEnumDeclarationDescrs() ) { - - String qName = typeDescr.getType().getFullName(); - Class< ? > typeClass = getClassForType( qName ); - if ( typeClass == null ) { - typeClass = getClassForType( typeDescr.getTypeName() ); - } - if ( typeClass == null ) { - for ( ImportDescr id : packageDescr.getImports() ) { - String imp = id.getTarget(); - int separator = imp.lastIndexOf( '.' ); - String tail = imp.substring( separator + 1 ); - if ( tail.equals( typeDescr.getTypeName() ) ) { - typeDescr.setNamespace( imp.substring( 0, separator ) ); - typeClass = getClassForType( typeDescr.getType().getFullName() ); - break; - } else if ( tail.equals("*") ) { - typeClass = getClassForType( imp.substring(0, imp.length()-1) + typeDescr.getType().getName() ); - if (typeClass != null) { - typeDescr.setNamespace( imp.substring( 0, separator ) ); + for (AbstractClassTypeDeclarationDescr typeDescr : packageDescr.getClassAndEnumDeclarationDescrs()) { + if (filterAccepts(typeDescr.getNamespace(), typeDescr.getTypeName()) ) { + + String qName = typeDescr.getType().getFullName(); + Class<?> typeClass = getClassForType(qName); + if (typeClass == null) { + typeClass = getClassForType(typeDescr.getTypeName()); + } + if (typeClass == null) { + for (ImportDescr id : packageDescr.getImports()) { + String imp = id.getTarget(); + int separator = imp.lastIndexOf('.'); + String tail = imp.substring(separator + 1); + if (tail.equals(typeDescr.getTypeName())) { + typeDescr.setNamespace(imp.substring(0, separator)); + typeClass = getClassForType(typeDescr.getType().getFullName()); break; + } else if (tail.equals("*")) { + typeClass = getClassForType(imp.substring(0, imp.length() - 1) + typeDescr.getType().getName()); + if (typeClass != null) { + typeDescr.setNamespace(imp.substring(0, separator)); + break; + } } } } - } - String className = typeClass != null ? typeClass.getName() : qName; - int dotPos = className.lastIndexOf( '.' ); - if ( dotPos >= 0 ) { - typeDescr.setNamespace( className.substring( 0, dotPos ) ); - typeDescr.setTypeName( className.substring( dotPos + 1 ) ); - } + String className = typeClass != null ? typeClass.getName() : qName; + int dotPos = className.lastIndexOf('.'); + if (dotPos >= 0) { + typeDescr.setNamespace(className.substring(0, dotPos)); + typeDescr.setTypeName(className.substring(dotPos + 1)); + } - if ( isEmpty( typeDescr.getNamespace() ) && typeDescr.getFields().isEmpty() ) { - // might be referencing a class imported with a package import (.*) - PackageRegistry pkgReg = this.pkgRegistryMap.get( packageDescr.getName() ); - if ( pkgReg != null ) { - try { - Class< ? > clz = pkgReg.getTypeResolver().resolveType( typeDescr.getTypeName() ); - java.lang.Package pkg = clz.getPackage(); - if ( pkg != null ) { - typeDescr.setNamespace( pkg.getName() ); - int index = typeDescr.getNamespace() != null && !typeDescr.getNamespace().isEmpty() ? typeDescr.getNamespace().length() + 1 : 0; - typeDescr.setTypeName( clz.getCanonicalName().substring( index ) ); + if (isEmpty(typeDescr.getNamespace()) && typeDescr.getFields().isEmpty()) { + // might be referencing a class imported with a package import (.*) + PackageRegistry pkgReg = this.pkgRegistryMap.get(packageDescr.getName()); + if (pkgReg != null) { + try { + Class<?> clz = pkgReg.getTypeResolver().resolveType(typeDescr.getTypeName()); + java.lang.Package pkg = clz.getPackage(); + if (pkg != null) { + typeDescr.setNamespace(pkg.getName()); + int index = typeDescr.getNamespace() != null && !typeDescr.getNamespace().isEmpty() ? typeDescr.getNamespace().length() + 1 : 0; + typeDescr.setTypeName(clz.getCanonicalName().substring(index)); + } + } catch (Exception e) { + // intentionally eating the exception as we will fallback to default namespace } - } catch ( Exception e ) { - // intentionally eating the exception as we will fallback to default namespace } } - } - - if ( isEmpty( typeDescr.getNamespace() ) ) { - typeDescr.setNamespace( packageDescr.getNamespace() ); // set the default namespace - } - - //identify superclass type and namespace - if ( typeDescr instanceof TypeDeclarationDescr ) { - fillSuperType( (TypeDeclarationDescr) typeDescr, - packageDescr ); - } - - //identify field types as well - fillFieldTypes( typeDescr, - packageDescr ); - if ( !typeDescr.getNamespace().equals( packageDescr.getNamespace() ) ) { - // If the type declaration is for a different namespace, process that separately. - PackageDescr altDescr = new PackageDescr( typeDescr.getNamespace() ); - if ( typeDescr instanceof TypeDeclarationDescr ) { - altDescr.addTypeDeclaration( (TypeDeclarationDescr) typeDescr ); - } else if ( typeDescr instanceof EnumDeclarationDescr ) { - altDescr.addEnumDeclaration( (EnumDeclarationDescr) typeDescr ); + if (isEmpty(typeDescr.getNamespace())) { + typeDescr.setNamespace(packageDescr.getNamespace()); // set the default namespace } - for ( ImportDescr imp : packageDescr.getImports() ) { - altDescr.addImport( imp ); + //identify superclass type and namespace + if (typeDescr instanceof TypeDeclarationDescr) { + fillSuperType((TypeDeclarationDescr) typeDescr, + packageDescr); } - if ( !getPackageRegistry().containsKey( altDescr.getNamespace() ) ) { - newPackage( altDescr ); + + //identify field types as well + fillFieldTypes(typeDescr, + packageDescr); + + if (!typeDescr.getNamespace().equals(packageDescr.getNamespace())) { + // If the type declaration is for a different namespace, process that separately. + PackageDescr altDescr = new PackageDescr(typeDescr.getNamespace()); + if (typeDescr instanceof TypeDeclarationDescr) { + altDescr.addTypeDeclaration((TypeDeclarationDescr) typeDescr); + } else if (typeDescr instanceof EnumDeclarationDescr) { + altDescr.addEnumDeclaration((EnumDeclarationDescr) typeDescr); + } + + for (ImportDescr imp : packageDescr.getImports()) { + altDescr.addImport(imp); + } + if (!getPackageRegistry().containsKey(altDescr.getNamespace())) { + newPackage(altDescr); + } + mergePackage(this.pkgRegistryMap.get(altDescr.getNamespace()), altDescr); } - mergePackage( this.pkgRegistryMap.get( altDescr.getNamespace() ), altDescr ); } - } // sort declarations : superclasses must be generated first - Collection<AbstractClassTypeDeclarationDescr> sortedTypeDescriptors = sortByHierarchy( packageDescr.getClassAndEnumDeclarationDescrs() ); + Collection<AbstractClassTypeDeclarationDescr> sortedTypeDescriptors = sortByHierarchy(packageDescr.getClassAndEnumDeclarationDescrs()); - for ( AbstractClassTypeDeclarationDescr typeDescr : sortedTypeDescriptors ) { - registerGeneratedType( typeDescr ); + for (AbstractClassTypeDeclarationDescr typeDescr : sortedTypeDescriptors) { + registerGeneratedType(typeDescr); } - if ( hasErrors() ) { + if (hasErrors()) { return Collections.emptyList(); } - for ( AbstractClassTypeDeclarationDescr typeDescr : sortedTypeDescriptors ) { + for (AbstractClassTypeDeclarationDescr typeDescr : sortedTypeDescriptors) { - if ( !typeDescr.getNamespace().equals( packageDescr.getNamespace() ) ) { + if (!typeDescr.getNamespace().equals(packageDescr.getNamespace())) { continue; } //descriptor needs fields inherited from superclass - if ( typeDescr instanceof TypeDeclarationDescr ) { + if (typeDescr instanceof TypeDeclarationDescr) { TypeDeclarationDescr tDescr = (TypeDeclarationDescr) typeDescr; - for ( QualifiedName qname : tDescr.getSuperTypes() ) { + for (QualifiedName qname : tDescr.getSuperTypes()) { //descriptor needs fields inherited from superclass - if ( mergeInheritedFields( tDescr ) ) { + if (mergeInheritedFields(tDescr)) { //descriptor also needs metadata from superclass - for ( AbstractClassTypeDeclarationDescr descr : sortedTypeDescriptors ) { + for (AbstractClassTypeDeclarationDescr descr : sortedTypeDescriptors) { // sortedTypeDescriptors are sorted by inheritance order, so we'll always find the superClass (if any) before the subclass - if ( qname.equals( descr.getType() ) ) { - typeDescr.getAnnotations().putAll( descr.getAnnotations() ); + if (qname.equals(descr.getType())) { + typeDescr.getAnnotations().putAll(descr.getAnnotations()); break; - } else if ( typeDescr.getType().equals( descr.getType() ) ) { + } else if (typeDescr.getType().equals(descr.getType())) { break; } @@ -2364,66 +2404,66 @@ List<TypeDefinition> processTypeDeclarations(PackageRegistry pkgRegistry, Packag } // Go on with the build - TypeDeclaration type = new TypeDeclaration( typeDescr.getTypeName() ); - if ( typeDescr.getResource() == null ) { - typeDescr.setResource( resource ); + TypeDeclaration type = new TypeDeclaration(typeDescr.getTypeName()); + if (typeDescr.getResource() == null) { + typeDescr.setResource(resource); } - type.setResource( typeDescr.getResource() ); + type.setResource(typeDescr.getResource()); TypeDeclaration parent = null; - if ( !typeDescr.getSuperTypes().isEmpty() ) { + if (!typeDescr.getSuperTypes().isEmpty()) { // parent might have inheritable properties - PackageRegistry sup = pkgRegistryMap.get( typeDescr.getSuperTypeNamespace() ); - if ( sup != null ) { - parent = sup.getPackage().getTypeDeclaration( typeDescr.getSuperTypeName() ); - if ( parent == null ) { - this.results.add( new TypeDeclarationError( typeDescr, "Declared class " + typeDescr.getTypeName() + " can't extend class " + typeDescr.getSuperTypeName() + ", it should be declared" ) ); + PackageRegistry sup = pkgRegistryMap.get(typeDescr.getSuperTypeNamespace()); + if (sup != null) { + parent = sup.getPackage().getTypeDeclaration(typeDescr.getSuperTypeName()); + if (parent == null) { + this.results.add(new TypeDeclarationError(typeDescr, "Declared class " + typeDescr.getTypeName() + " can't extend class " + typeDescr.getSuperTypeName() + ", it should be declared")); } else { - if ( parent.getNature() == TypeDeclaration.Nature.DECLARATION && ruleBase != null ) { + if (parent.getNature() == TypeDeclaration.Nature.DECLARATION && ruleBase != null) { // trying to find a definition - parent = ruleBase.getPackagesMap().get( typeDescr.getSuperTypeNamespace() ).getTypeDeclaration( typeDescr.getSuperTypeName() ); + parent = ruleBase.getPackagesMap().get(typeDescr.getSuperTypeNamespace()).getTypeDeclaration(typeDescr.getSuperTypeName()); } } } } // is it a regular fact or an event? - AnnotationDescr annotationDescr = typeDescr.getAnnotation( TypeDeclaration.Role.ID ); + AnnotationDescr annotationDescr = typeDescr.getAnnotation(TypeDeclaration.Role.ID); String role = (annotationDescr != null) ? annotationDescr.getSingleValue() : null; - if ( role != null ) { - type.setRole( TypeDeclaration.Role.parseRole( role ) ); - } else if ( parent != null ) { - type.setRole( parent.getRole() ); + if (role != null) { + type.setRole(TypeDeclaration.Role.parseRole(role)); + } else if (parent != null) { + type.setRole(parent.getRole()); } - annotationDescr = typeDescr.getAnnotation( TypeDeclaration.ATTR_TYPESAFE ); + annotationDescr = typeDescr.getAnnotation(TypeDeclaration.ATTR_TYPESAFE); String typesafe = (annotationDescr != null) ? annotationDescr.getSingleValue() : null; - if ( typesafe != null ) { - type.setTypesafe( Boolean.parseBoolean( typesafe ) ); - } else if ( parent != null ) { - type.setTypesafe( parent.isTypesafe() ); + if (typesafe != null) { + type.setTypesafe(Boolean.parseBoolean(typesafe)); + } else if (parent != null) { + type.setTypesafe(parent.isTypesafe()); } // is it a pojo or a template? - annotationDescr = typeDescr.getAnnotation( TypeDeclaration.Format.ID ); + annotationDescr = typeDescr.getAnnotation(TypeDeclaration.Format.ID); String format = (annotationDescr != null) ? annotationDescr.getSingleValue() : null; - if ( format != null ) { - type.setFormat( TypeDeclaration.Format.parseFormat( format ) ); + if (format != null) { + type.setFormat(TypeDeclaration.Format.parseFormat(format)); } // is it a class, a trait or an enum? - annotationDescr = typeDescr.getAnnotation( TypeDeclaration.Kind.ID ); + annotationDescr = typeDescr.getAnnotation(TypeDeclaration.Kind.ID); String kind = (annotationDescr != null) ? annotationDescr.getSingleValue() : null; - if ( kind != null ) { - type.setKind( TypeDeclaration.Kind.parseKind( kind ) ); + if (kind != null) { + type.setKind(TypeDeclaration.Kind.parseKind(kind)); } - if ( typeDescr instanceof EnumDeclarationDescr ) { - type.setKind( TypeDeclaration.Kind.ENUM ); + if (typeDescr instanceof EnumDeclarationDescr) { + type.setKind(TypeDeclaration.Kind.ENUM); } - annotationDescr = typeDescr.getAnnotation( TypeDeclaration.ATTR_CLASS ); + annotationDescr = typeDescr.getAnnotation(TypeDeclaration.ATTR_CLASS); String className = (annotationDescr != null) ? annotationDescr.getSingleValue() : null; - if ( StringUtils.isEmpty( className ) ) { + if (StringUtils.isEmpty(className)) { className = type.getTypeName(); } @@ -2431,26 +2471,26 @@ List<TypeDefinition> processTypeDeclarations(PackageRegistry pkgRegistry, Packag // the type declaration is generated in any case (to be used by subclasses, if any) // the actual class will be generated only if needed - if ( ! hasErrors() ) { - generateDeclaredBean( typeDescr, - type, - pkgRegistry, - unresolvedTypes ); - - Class< ? > clazz = pkgRegistry.getTypeResolver().resolveType( typeDescr.getType().getFullName() ); - type.setTypeClass( clazz ); + if (!hasErrors()) { + generateDeclaredBean(typeDescr, + type, + pkgRegistry, + unresolvedTypes); + + Class<?> clazz = pkgRegistry.getTypeResolver().resolveType(typeDescr.getType().getFullName()); + type.setTypeClass(clazz); } - } catch ( final ClassNotFoundException e ) { - this.results.add( new TypeDeclarationError( typeDescr, - "Class '" + className + - "' not found for type declaration of '" + - type.getTypeName() + "'" ) ); + } catch (final ClassNotFoundException e) { + this.results.add(new TypeDeclarationError(typeDescr, + "Class '" + className + + "' not found for type declaration of '" + + type.getTypeName() + "'")); continue; } - if ( ! processTypeFields( pkgRegistry, typeDescr, type, true ) ) { - unresolvedTypes.add( new TypeDefinition( type, typeDescr ) ); + if (!processTypeFields(pkgRegistry, typeDescr, type, true)) { + unresolvedTypes.add(new TypeDefinition(type, typeDescr)); } } @@ -2458,138 +2498,138 @@ List<TypeDefinition> processTypeDeclarations(PackageRegistry pkgRegistry, Packag } private boolean processTypeFields(PackageRegistry pkgRegistry, - AbstractClassTypeDeclarationDescr typeDescr, - TypeDeclaration type, - boolean firstAttempt) { - if ( type.getTypeClassDef() != null ) { + AbstractClassTypeDeclarationDescr typeDescr, + TypeDeclaration type, + boolean firstAttempt) { + if (type.getTypeClassDef() != null) { try { - buildFieldAccessors( type, pkgRegistry ); - } catch ( Throwable e ) { - if ( !firstAttempt ) { - this.results.add( new TypeDeclarationError( typeDescr, - "Error creating field accessors for TypeDeclaration '" + type.getTypeName() + - "' for type '" + - type.getTypeName() + - "'" ) ); + buildFieldAccessors(type, pkgRegistry); + } catch (Throwable e) { + if (!firstAttempt) { + this.results.add(new TypeDeclarationError(typeDescr, + "Error creating field accessors for TypeDeclaration '" + type.getTypeName() + + "' for type '" + + type.getTypeName() + + "'")); } return false; } } - AnnotationDescr annotationDescr = typeDescr.getAnnotation( TypeDeclaration.ATTR_TIMESTAMP ); + AnnotationDescr annotationDescr = typeDescr.getAnnotation(TypeDeclaration.ATTR_TIMESTAMP); String timestamp = (annotationDescr != null) ? annotationDescr.getSingleValue() : null; - if ( timestamp != null ) { - type.setTimestampAttribute( timestamp ); + if (timestamp != null) { + type.setTimestampAttribute(timestamp); Package pkg = pkgRegistry.getPackage(); - MVELDialect dialect = (MVELDialect) pkgRegistry.getDialectCompiletimeRegistry().getDialect( "mvel" ); + MVELDialect dialect = (MVELDialect) pkgRegistry.getDialectCompiletimeRegistry().getDialect("mvel"); PackageBuildContext context = new PackageBuildContext(); - context.init( this, pkg, typeDescr, pkgRegistry.getDialectCompiletimeRegistry(), dialect, null ); - if ( !type.isTypesafe() ) { - context.setTypesafe( false ); + context.init(this, pkg, typeDescr, pkgRegistry.getDialectCompiletimeRegistry(), dialect, null); + if (!type.isTypesafe()) { + context.setTypesafe(false); } MVELAnalysisResult results = (MVELAnalysisResult) - context.getDialect().analyzeExpression( context, - typeDescr, - timestamp, - new BoundIdentifiers( Collections.EMPTY_MAP, - Collections.EMPTY_MAP, - Collections.EMPTY_MAP, - type.getTypeClass() ) ); - - if ( results != null ) { - InternalReadAccessor reader = pkg.getClassFieldAccessorStore().getMVELReader( ClassUtils.getPackage( type.getTypeClass() ), - type.getTypeClass().getName(), - timestamp, - type.isTypesafe(), - results.getReturnType() ); - - MVELDialectRuntimeData data = (MVELDialectRuntimeData) pkg.getDialectRuntimeRegistry().getDialectData( "mvel" ); - data.addCompileable( (MVELCompileable) reader ); - ((MVELCompileable) reader).compile( data ); - type.setTimestampExtractor( reader ); + context.getDialect().analyzeExpression(context, + typeDescr, + timestamp, + new BoundIdentifiers(Collections.EMPTY_MAP, + Collections.EMPTY_MAP, + Collections.EMPTY_MAP, + type.getTypeClass())); + + if (results != null) { + InternalReadAccessor reader = pkg.getClassFieldAccessorStore().getMVELReader(ClassUtils.getPackage(type.getTypeClass()), + type.getTypeClass().getName(), + timestamp, + type.isTypesafe(), + results.getReturnType()); + + MVELDialectRuntimeData data = (MVELDialectRuntimeData) pkg.getDialectRuntimeRegistry().getDialectData("mvel"); + data.addCompileable((MVELCompileable) reader); + ((MVELCompileable) reader).compile(data); + type.setTimestampExtractor(reader); } else { - this.results.add( new TypeDeclarationError( typeDescr, - "Error creating field accessors for timestamp field '" + timestamp + - "' for type '" + - type.getTypeName() + - "'" ) ); + this.results.add(new TypeDeclarationError(typeDescr, + "Error creating field accessors for timestamp field '" + timestamp + + "' for type '" + + type.getTypeName() + + "'")); } } - annotationDescr = typeDescr.getAnnotation( TypeDeclaration.ATTR_DURATION ); + annotationDescr = typeDescr.getAnnotation(TypeDeclaration.ATTR_DURATION); String duration = (annotationDescr != null) ? annotationDescr.getSingleValue() : null; - if ( duration != null ) { - type.setDurationAttribute( duration ); + if (duration != null) { + type.setDurationAttribute(duration); Package pkg = pkgRegistry.getPackage(); - MVELDialect dialect = (MVELDialect) pkgRegistry.getDialectCompiletimeRegistry().getDialect( "mvel" ); + MVELDialect dialect = (MVELDialect) pkgRegistry.getDialectCompiletimeRegistry().getDialect("mvel"); PackageBuildContext context = new PackageBuildContext(); - context.init( this, pkg, typeDescr, pkgRegistry.getDialectCompiletimeRegistry(), dialect, null ); - if ( !type.isTypesafe() ) { - context.setTypesafe( false ); + context.init(this, pkg, typeDescr, pkgRegistry.getDialectCompiletimeRegistry(), dialect, null); + if (!type.isTypesafe()) { + context.setTypesafe(false); } MVELAnalysisResult results = (MVELAnalysisResult) - context.getDialect().analyzeExpression( context, - typeDescr, - duration, - new BoundIdentifiers( Collections.EMPTY_MAP, - Collections.EMPTY_MAP, - Collections.EMPTY_MAP, - type.getTypeClass() ) ); - - if ( results != null ) { - InternalReadAccessor reader = pkg.getClassFieldAccessorStore().getMVELReader( ClassUtils.getPackage( type.getTypeClass() ), - type.getTypeClass().getName(), - duration, - type.isTypesafe(), - results.getReturnType() ); - - MVELDialectRuntimeData data = (MVELDialectRuntimeData) pkg.getDialectRuntimeRegistry().getDialectData( "mvel" ); - data.addCompileable( (MVELCompileable) reader ); - ((MVELCompileable) reader).compile( data ); - type.setDurationExtractor( reader ); + context.getDialect().analyzeExpression(context, + typeDescr, + duration, + new BoundIdentifiers(Collections.EMPTY_MAP, + Collections.EMPTY_MAP, + Collections.EMPTY_MAP, + type.getTypeClass())); + + if (results != null) { + InternalReadAccessor reader = pkg.getClassFieldAccessorStore().getMVELReader(ClassUtils.getPackage(type.getTypeClass()), + type.getTypeClass().getName(), + duration, + type.isTypesafe(), + results.getReturnType()); + + MVELDialectRuntimeData data = (MVELDialectRuntimeData) pkg.getDialectRuntimeRegistry().getDialectData("mvel"); + data.addCompileable((MVELCompileable) reader); + ((MVELCompileable) reader).compile(data); + type.setDurationExtractor(reader); } else { - this.results.add( new TypeDeclarationError( typeDescr, - "Error processing @duration for TypeDeclaration '" + type.getFullName() + - "': cannot access the field '" + duration + "'" ) ); + this.results.add(new TypeDeclarationError(typeDescr, + "Error processing @duration for TypeDeclaration '" + type.getFullName() + + "': cannot access the field '" + duration + "'")); } } - annotationDescr = typeDescr.getAnnotation( TypeDeclaration.ATTR_EXPIRE ); + annotationDescr = typeDescr.getAnnotation(TypeDeclaration.ATTR_EXPIRE); String expiration = (annotationDescr != null) ? annotationDescr.getSingleValue() : null; - if ( expiration != null ) { - if ( timeParser == null ) { + if (expiration != null) { + if (timeParser == null) { timeParser = new TimeIntervalParser(); } - type.setExpirationOffset( timeParser.parse( expiration )[0] ); + type.setExpirationOffset(timeParser.parse(expiration)[0]); } - boolean dynamic = typeDescr.getAnnotationNames().contains( TypeDeclaration.ATTR_PROP_CHANGE_SUPPORT ); - type.setDynamic( dynamic ); + boolean dynamic = typeDescr.getAnnotationNames().contains(TypeDeclaration.ATTR_PROP_CHANGE_SUPPORT); + type.setDynamic(dynamic); - PropertySpecificOption propertySpecificOption = configuration.getOption( PropertySpecificOption.class ); - boolean propertyReactive = propertySpecificOption.isPropSpecific( typeDescr.getAnnotationNames().contains( TypeDeclaration.ATTR_PROP_SPECIFIC ), - typeDescr.getAnnotationNames().contains( TypeDeclaration.ATTR_NOT_PROP_SPECIFIC ) ); + PropertySpecificOption propertySpecificOption = configuration.getOption(PropertySpecificOption.class); + boolean propertyReactive = propertySpecificOption.isPropSpecific(typeDescr.getAnnotationNames().contains(TypeDeclaration.ATTR_PROP_SPECIFIC), + typeDescr.getAnnotationNames().contains(TypeDeclaration.ATTR_NOT_PROP_SPECIFIC)); - setPropertyReactive( typeDescr.getResource(), type, propertyReactive ); + setPropertyReactive(typeDescr.getResource(), type, propertyReactive); - if ( type.isValid() ) { + if (type.isValid()) { // prefer definitions where possible - if ( type.getNature() == TypeDeclaration.Nature.DEFINITION ) { - pkgRegistry.getPackage().addTypeDeclaration( type ); + if (type.getNature() == TypeDeclaration.Nature.DEFINITION) { + pkgRegistry.getPackage().addTypeDeclaration(type); } else { - TypeDeclaration oldType = pkgRegistry.getPackage().getTypeDeclaration( type.getTypeName() ); - if ( oldType == null ) { - pkgRegistry.getPackage().addTypeDeclaration( type ); + TypeDeclaration oldType = pkgRegistry.getPackage().getTypeDeclaration(type.getTypeName()); + if (oldType == null) { + pkgRegistry.getPackage().addTypeDeclaration(type); } else { - if ( type.getRole() == TypeDeclaration.Role.EVENT ) { - oldType.setRole( TypeDeclaration.Role.EVENT ); + if (type.getRole() == TypeDeclaration.Role.EVENT) { + oldType.setRole(TypeDeclaration.Role.EVENT); } - if ( type.isPropertyReactive() ) { - oldType.setPropertyReactive( true ); + if (type.isPropertyReactive()) { + oldType.setPropertyReactive(true); } } } @@ -2599,47 +2639,47 @@ private boolean processTypeFields(PackageRegistry pkgRegistry, } private void setPropertyReactive(Resource resource, - TypeDeclaration type, - boolean propertyReactive) { - if ( propertyReactive && type.getSettableProperties().size() >= 64 ) { - this.results.add( new DisabledPropertyReactiveWarning( resource, type.getTypeName() ) ); - type.setPropertyReactive( false ); + TypeDeclaration type, + boolean propertyReactive) { + if (propertyReactive && type.getSettableProperties().size() >= 64) { + this.results.add(new DisabledPropertyReactiveWarning(resource, type.getTypeName())); + type.setPropertyReactive(false); } else { - type.setPropertyReactive( propertyReactive ); + type.setPropertyReactive(propertyReactive); } } private void updateTraitDefinition(TypeDeclaration type, - Class concrete) { + Class concrete) { try { - ClassFieldInspector inspector = new ClassFieldInspector( concrete ); + ClassFieldInspector inspector = new ClassFieldInspector(concrete); Map<String, Method> methods = inspector.getGetterMethods(); Map<String, Method> setters = inspector.getSetterMethods(); int j = 0; - for ( String fieldName : methods.keySet() ) { - if ( "core".equals( fieldName ) || "fields".equals( fieldName ) ) { + for (String fieldName : methods.keySet()) { + if ("core".equals(fieldName) || "fields".equals(fieldName)) { continue; } - if ( !inspector.isNonGetter( fieldName ) && setters.keySet().contains( fieldName ) ) { + if (!inspector.isNonGetter(fieldName) && setters.keySet().contains(fieldName)) { - Class ret = methods.get( fieldName ).getReturnType(); + Class ret = methods.get(fieldName).getReturnType(); FieldDefinition field = new FieldDefinition(); - field.setName( fieldName ); - field.setTypeName( ret.getName() ); - field.setIndex( j++ ); - type.getTypeClassDef().addField( field ); + field.setName(fieldName); + field.setTypeName(ret.getName()); + field.setIndex(j++); + type.getTypeClassDef().addField(field); } } Set<String> interfaces = new HashSet<String>(); - Collections.addAll( interfaces, type.getTypeClassDef().getInterfaces() ); - for ( Class iKlass : concrete.getInterfaces() ) { - interfaces.add( iKlass.getName() ); + Collections.addAll(interfaces, type.getTypeClassDef().getInterfaces()); + for (Class iKlass : concrete.getInterfaces()) { + interfaces.add(iKlass.getName()); } - type.getTypeClassDef().setInterfaces( interfaces.toArray( new String[interfaces.size()] ) ); + type.getTypeClassDef().setInterfaces(interfaces.toArray(new String[interfaces.size()])); - } catch ( IOException e ) { + } catch (IOException e) { e.printStackTrace(); } @@ -2653,18 +2693,18 @@ private void updateTraitDefinition(TypeDeclaration type, * @return */ private boolean isNovelClass(AbstractClassTypeDeclarationDescr typeDescr) { - return getExistingDeclarationClass( typeDescr ) == null; + return getExistingDeclarationClass(typeDescr) == null; } - private Class< ? > getExistingDeclarationClass(AbstractClassTypeDeclarationDescr typeDescr) { - PackageRegistry reg = this.pkgRegistryMap.get( typeDescr.getNamespace() ); - if ( reg == null ) { + private Class<?> getExistingDeclarationClass(AbstractClassTypeDeclarationDescr typeDescr) { + PackageRegistry reg = this.pkgRegistryMap.get(typeDescr.getNamespace()); + if (reg == null) { return null; } String availableName = typeDescr.getType().getFullName(); try { - return reg.getTypeResolver().resolveType( availableName ); - } catch ( ClassNotFoundException e ) { + return reg.getTypeResolver().resolveType(availableName); + } catch (ClassNotFoundException e) { return null; } } @@ -2680,30 +2720,30 @@ private boolean isNovelClass(AbstractClassTypeDeclarationDescr typeDescr) { * @return */ private Class resolveAnnotation(String annotation, - TypeResolver resolver) { + TypeResolver resolver) { // do not waste time with @format - if ( TypeDeclaration.Format.ID.equals( annotation ) ) { + if (TypeDeclaration.Format.ID.equals(annotation)) { return null; } // known conflicting annotation - if ( TypeDeclaration.ATTR_CLASS.equals( annotation ) ) { + if (TypeDeclaration.ATTR_CLASS.equals(annotation)) { return null; } try { - return resolver.resolveType( annotation.indexOf( '.' ) < 0 ? - annotation.substring( 0, 1 ).toUpperCase() + annotation.substring( 1 ) : - annotation ); - } catch ( ClassNotFoundException e ) { + return resolver.resolveType(annotation.indexOf('.') < 0 ? + annotation.substring(0, 1).toUpperCase() + annotation.substring(1) : + annotation); + } catch (ClassNotFoundException e) { // internal annotation, or annotation which can't be resolved. - if ( TypeDeclaration.Role.ID.equals( annotation ) ) { + if (TypeDeclaration.Role.ID.equals(annotation)) { return Role.class; } - if ( "key".equals( annotation ) ) { + if ("key".equals(annotation)) { return Key.class; } - if ( "position".equals( annotation ) ) { + if ("position".equals(annotation)) { return Position.class; } return null; @@ -2725,22 +2765,22 @@ private Class resolveAnnotation(String annotation, * @throws NoSuchFieldException */ private void buildFieldAccessors(final TypeDeclaration type, - final PackageRegistry pkgRegistry) throws SecurityException, - IllegalArgumentException, - InstantiationException, - IllegalAccessException, - IOException, - IntrospectionException, - ClassNotFoundException, - NoSuchMethodException, - InvocationTargetException, - NoSuchFieldException { + final PackageRegistry pkgRegistry) throws SecurityException, + IllegalArgumentException, + InstantiationException, + IllegalAccessException, + IOException, + IntrospectionException, + ClassNotFoundException, + NoSuchMethodException, + InvocationTargetException, + NoSuchFieldException { ClassDefinition cd = type.getTypeClassDef(); ClassFieldAccessorStore store = pkgRegistry.getPackage().getClassFieldAccessorStore(); - for ( FieldDefinition attrDef : cd.getFieldsDefinitions() ) { - ClassFieldAccessor accessor = store.getAccessor( cd.getDefinedClass().getName(), - attrDef.getName() ); - attrDef.setReadWriteAccessor( accessor ); + for (FieldDefinition attrDef : cd.getFieldsDefinitions()) { + ClassFieldAccessor accessor = store.getAccessor(cd.getDefinedClass().getName(), + attrDef.getName()); + attrDef.setReadWriteAccessor(accessor); } } @@ -2749,201 +2789,201 @@ private void buildFieldAccessors(final TypeDeclaration type, * everything is using. */ private void generateDeclaredBean(AbstractClassTypeDeclarationDescr typeDescr, - TypeDeclaration type, - PackageRegistry pkgRegistry, - List<TypeDefinition> unresolvedTypeDefinitions) { + TypeDeclaration type, + PackageRegistry pkgRegistry, + List<TypeDefinition> unresolvedTypeDefinitions) { // extracts type, supertype and interfaces String fullName = typeDescr.getType().getFullName(); - if ( type.getKind().equals( TypeDeclaration.Kind.CLASS ) ) { + if (type.getKind().equals(TypeDeclaration.Kind.CLASS)) { TypeDeclarationDescr tdescr = (TypeDeclarationDescr) typeDescr; - if ( tdescr.getSuperTypes().size() > 1 ) { - this.results.add( new TypeDeclarationError( typeDescr, "Declared class " + fullName + " - has more than one supertype;" ) ); + if (tdescr.getSuperTypes().size() > 1) { + this.results.add(new TypeDeclarationError(typeDescr, "Declared class " + fullName + " - has more than one supertype;")); return; - } else if ( tdescr.getSuperTypes().isEmpty() ) { - tdescr.addSuperType( "java.lang.Object" ); + } else if (tdescr.getSuperTypes().isEmpty()) { + tdescr.addSuperType("java.lang.Object"); } } - AnnotationDescr traitableAnn = typeDescr.getAnnotation( Traitable.class.getSimpleName() ); + AnnotationDescr traitableAnn = typeDescr.getAnnotation(Traitable.class.getSimpleName()); boolean traitable = traitableAnn != null; String[] fullSuperTypes = new String[typeDescr.getSuperTypes().size() + 1]; int j = 0; - for ( QualifiedName qname : typeDescr.getSuperTypes() ) { + for (QualifiedName qname : typeDescr.getSuperTypes()) { fullSuperTypes[j++] = qname.getFullName(); } fullSuperTypes[j] = Thing.class.getName(); List<String> interfaceList = new ArrayList<String>(); - interfaceList.add( traitable ? Externalizable.class.getName() : Serializable.class.getName() ); - if ( traitable ) { - interfaceList.add( TraitableBean.class.getName() ); + interfaceList.add(traitable ? Externalizable.class.getName() : Serializable.class.getName()); + if (traitable) { + interfaceList.add(TraitableBean.class.getName()); } - String[] interfaces = interfaceList.toArray( new String[interfaceList.size()] ); + String[] interfaces = interfaceList.toArray(new String[interfaceList.size()]); // prepares a class definition ClassDefinition def; - switch ( type.getKind() ) { - case TRAIT : - def = new ClassDefinition( fullName, - "java.lang.Object", - fullSuperTypes ); + switch (type.getKind()) { + case TRAIT: + def = new ClassDefinition(fullName, + "java.lang.Object", + fullSuperTypes); break; - case ENUM : - def = new EnumClassDefinition( fullName, - fullSuperTypes[0], - null ); + case ENUM: + def = new EnumClassDefinition(fullName, + fullSuperTypes[0], + null); break; - case CLASS : - default : - def = new ClassDefinition( fullName, - fullSuperTypes[0], - interfaces ); - def.setTraitable( traitable, traitableAnn != null && - traitableAnn.getValue( "logical" ) != null && - Boolean.valueOf( traitableAnn.getValue( "logical" ) ) ); - } - - for ( String annotationName : typeDescr.getAnnotationNames() ) { - Class annotation = resolveAnnotation( annotationName, - pkgRegistry.getTypeResolver() ); - if ( annotation != null ) { + case CLASS: + default: + def = new ClassDefinition(fullName, + fullSuperTypes[0], + interfaces); + def.setTraitable(traitable, traitableAnn != null && + traitableAnn.getValue("logical") != null && + Boolean.valueOf(traitableAnn.getValue("logical"))); + } + + for (String annotationName : typeDescr.getAnnotationNames()) { + Class annotation = resolveAnnotation(annotationName, + pkgRegistry.getTypeResolver()); + if (annotation != null) { try { - AnnotationDefinition annotationDefinition = AnnotationDefinition.build( annotation, - typeDescr.getAnnotations().get( annotationName ).getValueMap(), - pkgRegistry.getTypeResolver() ); - def.addAnnotation( annotationDefinition ); - } catch ( NoSuchMethodException nsme ) { - this.results.add( new TypeDeclarationError( typeDescr, - "Annotated type " + fullName + - " - undefined property in @annotation " + - annotationName + ": " + - nsme.getMessage() + ";" ) ); + AnnotationDefinition annotationDefinition = AnnotationDefinition.build(annotation, + typeDescr.getAnnotations().get(annotationName).getValueMap(), + pkgRegistry.getTypeResolver()); + def.addAnnotation(annotationDefinition); + } catch (NoSuchMethodException nsme) { + this.results.add(new TypeDeclarationError(typeDescr, + "Annotated type " + fullName + + " - undefined property in @annotation " + + annotationName + ": " + + nsme.getMessage() + ";")); } } if (annotation == null || annotation == Role.class) { - def.addMetaData( annotationName, typeDescr.getAnnotation( annotationName ).getSingleValue() ); + def.addMetaData(annotationName, typeDescr.getAnnotation(annotationName).getSingleValue()); } } // add enum literals, if appropriate - if ( type.getKind() == TypeDeclaration.Kind.ENUM ) { - for ( EnumLiteralDescr lit : ((EnumDeclarationDescr) typeDescr).getLiterals() ) { + if (type.getKind() == TypeDeclaration.Kind.ENUM) { + for (EnumLiteralDescr lit : ((EnumDeclarationDescr) typeDescr).getLiterals()) { ((EnumClassDefinition) def).addLiteral( - new EnumLiteralDefinition( lit.getName(), lit.getConstructorArgs() ) + new EnumLiteralDefinition(lit.getName(), lit.getConstructorArgs()) ); } } // fields definitions are created. will be used by subclasses, if any. // Fields are SORTED in the process - if ( !typeDescr.getFields().isEmpty() ) { - PriorityQueue<FieldDefinition> fieldDefs = sortFields( typeDescr.getFields(), - pkgRegistry ); + if (!typeDescr.getFields().isEmpty()) { + PriorityQueue<FieldDefinition> fieldDefs = sortFields(typeDescr.getFields(), + pkgRegistry); int n = fieldDefs.size(); - for ( int k = 0; k < n; k++ ) { + for (int k = 0; k < n; k++) { FieldDefinition fld = fieldDefs.poll(); - if ( unresolvedTypeDefinitions != null ) { - for ( TypeDefinition typeDef : unresolvedTypeDefinitions ) { - if ( fld.getTypeName().equals( typeDef.getTypeClassName() ) ) { - fld.setRecursive( true ); + if (unresolvedTypeDefinitions != null) { + for (TypeDefinition typeDef : unresolvedTypeDefinitions) { + if (fld.getTypeName().equals(typeDef.getTypeClassName())) { + fld.setRecursive(true); break; } } } - fld.setIndex( k ); - def.addField( fld ); + fld.setIndex(k); + def.addField(fld); } } // check whether it is necessary to build the class or not - Class< ? > existingDeclarationClass = getExistingDeclarationClass( typeDescr ); - type.setNovel( existingDeclarationClass == null ); + Class<?> existingDeclarationClass = getExistingDeclarationClass(typeDescr); + type.setNovel(existingDeclarationClass == null); // attach the class definition, it will be completed later - type.setTypeClassDef( def ); + type.setTypeClassDef(def); //if is not new, search the already existing declaration and //compare them o see if they are at least compatibles - if ( !type.isNovel() ) { - TypeDeclaration previousTypeDeclaration = this.pkgRegistryMap.get( typeDescr.getNamespace() ).getPackage().getTypeDeclaration( typeDescr.getTypeName() ); + if (!type.isNovel()) { + TypeDeclaration previousTypeDeclaration = this.pkgRegistryMap.get(typeDescr.getNamespace()).getPackage().getTypeDeclaration(typeDescr.getTypeName()); try { - if ( !type.getTypeClassDef().getFields().isEmpty() ) { + if (!type.getTypeClassDef().getFields().isEmpty()) { //since the declaration defines one or more fields, it is a DEFINITION - type.setNature( TypeDeclaration.Nature.DEFINITION ); + type.setNature(TypeDeclaration.Nature.DEFINITION); } else { //The declaration doesn't define any field, it is a DECLARATION - type.setNature( TypeDeclaration.Nature.DECLARATION ); + type.setNature(TypeDeclaration.Nature.DECLARATION); } //if there is no previous declaration, then the original declaration was a POJO //to the behavior previous these changes - if ( previousTypeDeclaration == null ) { + if (previousTypeDeclaration == null) { // new declarations of a POJO can't declare new fields, // except if the POJO was previously generated/compiled and saved into the kjar - if ( !configuration.isPreCompiled() && - !GeneratedFact.class.isAssignableFrom( existingDeclarationClass ) && !type.getTypeClassDef().getFields().isEmpty() ) { - type.setValid( false ); - this.results.add( new TypeDeclarationError( typeDescr, "New declaration of " + typeDescr.getType().getFullName() - + " can't declare new fields" ) ); + if (!configuration.isPreCompiled() && + !GeneratedFact.class.isAssignableFrom(existingDeclarationClass) && !type.getTypeClassDef().getFields().isEmpty()) { + type.setValid(false); + this.results.add(new TypeDeclarationError(typeDescr, "New declaration of " + typeDescr.getType().getFullName() + + " can't declare new fields")); } } else { - int typeComparisonResult = this.compareTypeDeclarations( previousTypeDeclaration, type ); + int typeComparisonResult = this.compareTypeDeclarations(previousTypeDeclaration, type); - if ( typeComparisonResult < 0 ) { + if (typeComparisonResult < 0) { //oldDeclaration is "less" than newDeclaration -> error - this.results.add( new TypeDeclarationError( typeDescr, typeDescr.getType().getFullName() - + " declares more fields than the already existing version" ) ); - type.setValid( false ); - } else if ( typeComparisonResult > 0 && !type.getTypeClassDef().getFields().isEmpty() ) { + this.results.add(new TypeDeclarationError(typeDescr, typeDescr.getType().getFullName() + + " declares more fields than the already existing version")); + type.setValid(false); + } else if (typeComparisonResult > 0 && !type.getTypeClassDef().getFields().isEmpty()) { //oldDeclaration is "grater" than newDeclaration -> error - this.results.add( new TypeDeclarationError( typeDescr, typeDescr.getType().getFullName() - + " declares less fields than the already existing version" ) ); - type.setValid( false ); + this.results.add(new TypeDeclarationError(typeDescr, typeDescr.getType().getFullName() + + " declares less fields than the already existing version")); + type.setValid(false); } //if they are "equal" -> no problem // in the case of a declaration, we need to copy all the // fields present in the previous declaration - if ( type.getNature() == TypeDeclaration.Nature.DECLARATION ) { - this.mergeTypeDeclarations( previousTypeDeclaration, type ); + if (type.getNature() == TypeDeclaration.Nature.DECLARATION) { + this.mergeTypeDeclarations(previousTypeDeclaration, type); } } - } catch ( IncompatibleClassChangeError error ) { + } catch (IncompatibleClassChangeError error) { //if the types are incompatible -> error - this.results.add( new TypeDeclarationError( typeDescr, error.getMessage() ) ); + this.results.add(new TypeDeclarationError(typeDescr, error.getMessage())); } } else { //if the declaration is novel, then it is a DEFINITION - type.setNature( TypeDeclaration.Nature.DEFINITION ); + type.setNature(TypeDeclaration.Nature.DEFINITION); } - generateDeclaredBean( typeDescr, - type, - pkgRegistry, - expandImportsInFieldInitExpr( def, pkgRegistry ) ); + generateDeclaredBean(typeDescr, + type, + pkgRegistry, + expandImportsInFieldInitExpr(def, pkgRegistry)); } private ClassDefinition expandImportsInFieldInitExpr(ClassDefinition def, - PackageRegistry pkgRegistry) { + PackageRegistry pkgRegistry) { TypeResolver typeResolver = pkgRegistry.getPackage().getTypeResolver(); - for ( FieldDefinition field : def.getFieldsDefinitions() ) { - field.setInitExpr( rewriteInitExprWithImports( field.getInitExpr(), typeResolver ) ); + for (FieldDefinition field : def.getFieldsDefinitions()) { + field.setInitExpr(rewriteInitExprWithImports(field.getInitExpr(), typeResolver)); } return def; } private String rewriteInitExprWithImports(String expr, - TypeResolver typeResolver) { - if ( expr == null ) { + TypeResolver typeResolver) { + if (expr == null) { return null; } StringBuilder sb = new StringBuilder(); @@ -2951,178 +2991,178 @@ private String rewriteInitExprWithImports(String expr, boolean inTypeName = false; boolean afterDot = false; int typeStart = 0; - for ( int i = 0; i < expr.length(); i++ ) { - char ch = expr.charAt( i ); - if ( Character.isJavaIdentifierStart( ch ) ) { - if ( !inTypeName && !inQuotes && !afterDot ) { + for (int i = 0; i < expr.length(); i++) { + char ch = expr.charAt(i); + if (Character.isJavaIdentifierStart(ch)) { + if (!inTypeName && !inQuotes && !afterDot) { typeStart = i; inTypeName = true; } - } else if ( !Character.isJavaIdentifierPart( ch ) ) { - if ( ch == '"' ) { + } else if (!Character.isJavaIdentifierPart(ch)) { + if (ch == '"') { inQuotes = !inQuotes; - } else if ( ch == '.' && !inQuotes ) { + } else if (ch == '.' && !inQuotes) { afterDot = true; - } else if ( !Character.isSpaceChar( ch ) ) { + } else if (!Character.isSpaceChar(ch)) { afterDot = false; } - if ( inTypeName ) { + if (inTypeName) { inTypeName = false; - String type = expr.substring( typeStart, i ); - sb.append( getFullTypeName( type, typeResolver ) ); + String type = expr.substring(typeStart, i); + sb.append(getFullTypeName(type, typeResolver)); } } - if ( !inTypeName ) { - sb.append( ch ); + if (!inTypeName) { + sb.append(ch); } } - if ( inTypeName ) { - String type = expr.substring( typeStart ); - sb.append( getFullTypeName( type, typeResolver ) ); + if (inTypeName) { + String type = expr.substring(typeStart); + sb.append(getFullTypeName(type, typeResolver)); } return sb.toString(); } private String getFullTypeName(String type, - TypeResolver typeResolver) { - if ( type.equals( "new" ) ) { + TypeResolver typeResolver) { + if (type.equals("new")) { return type; } try { - return typeResolver.getFullTypeName( type ); - } catch ( ClassNotFoundException e ) { + return typeResolver.getFullTypeName(type); + } catch (ClassNotFoundException e) { return type; } } private void generateDeclaredBean(AbstractClassTypeDeclarationDescr typeDescr, - TypeDeclaration type, - PackageRegistry pkgRegistry, - ClassDefinition def) { - - if ( typeDescr.getAnnotation( Traitable.class.getSimpleName() ) != null - || (!type.getKind().equals( TypeDeclaration.Kind.TRAIT ) && - pkgRegistryMap.containsKey( def.getSuperClass() ) && - pkgRegistryMap.get( def.getSuperClass() ).getTraitRegistry().getTraitables().containsKey( def.getSuperClass() ) - ) ) { - if ( !isNovelClass( typeDescr ) ) { + TypeDeclaration type, + PackageRegistry pkgRegistry, + ClassDefinition def) { + + if (typeDescr.getAnnotation(Traitable.class.getSimpleName()) != null + || (!type.getKind().equals(TypeDeclaration.Kind.TRAIT) && + pkgRegistryMap.containsKey(def.getSuperClass()) && + pkgRegistryMap.get(def.getSuperClass()).getTraitRegistry().getTraitables().containsKey(def.getSuperClass()) + )) { + if (!isNovelClass(typeDescr)) { try { - PackageRegistry reg = this.pkgRegistryMap.get( typeDescr.getNamespace() ); + PackageRegistry reg = this.pkgRegistryMap.get(typeDescr.getNamespace()); String availableName = typeDescr.getType().getFullName(); - Class< ? > resolvedType = reg.getTypeResolver().resolveType( availableName ); - updateTraitDefinition( type, - resolvedType ); - } catch ( ClassNotFoundException cnfe ) { + Class<?> resolvedType = reg.getTypeResolver().resolveType(availableName); + updateTraitDefinition(type, + resolvedType); + } catch (ClassNotFoundException cnfe) { // we already know the class exists } } - pkgRegistry.getTraitRegistry().addTraitable( def ); - } else if ( type.getKind().equals( TypeDeclaration.Kind.TRAIT ) - || typeDescr.getAnnotation( Trait.class.getSimpleName() ) != null ) { + pkgRegistry.getTraitRegistry().addTraitable(def); + } else if (type.getKind().equals(TypeDeclaration.Kind.TRAIT) + || typeDescr.getAnnotation(Trait.class.getSimpleName()) != null) { - if ( !type.isNovel() ) { + if (!type.isNovel()) { try { - PackageRegistry reg = this.pkgRegistryMap.get( typeDescr.getNamespace() ); + PackageRegistry reg = this.pkgRegistryMap.get(typeDescr.getNamespace()); String availableName = typeDescr.getType().getFullName(); - Class< ? > resolvedType = reg.getTypeResolver().resolveType( availableName ); - if ( !Thing.class.isAssignableFrom( resolvedType ) ) { - updateTraitDefinition( type, - resolvedType ); + Class<?> resolvedType = reg.getTypeResolver().resolveType(availableName); + if (!Thing.class.isAssignableFrom(resolvedType)) { + updateTraitDefinition(type, + resolvedType); String target = typeDescr.getTypeName() + TraitFactory.SUFFIX; TypeDeclarationDescr tempDescr = new TypeDeclarationDescr(); - tempDescr.setNamespace( typeDescr.getNamespace() ); - tempDescr.setFields( typeDescr.getFields() ); - tempDescr.setType( target, - typeDescr.getNamespace() ); - tempDescr.addSuperType( typeDescr.getType() ); - TypeDeclaration tempDeclr = new TypeDeclaration( target ); - tempDeclr.setKind( TypeDeclaration.Kind.TRAIT ); - tempDeclr.setTypesafe( type.isTypesafe() ); - tempDeclr.setNovel( true ); - tempDeclr.setTypeClassName( tempDescr.getType().getFullName() ); - tempDeclr.setResource( type.getResource() ); - - ClassDefinition tempDef = new ClassDefinition( target ); - tempDef.setClassName( tempDescr.getType().getFullName() ); - tempDef.setTraitable( false ); - for ( FieldDefinition fld : def.getFieldsDefinitions() ) { - tempDef.addField( fld ); + tempDescr.setNamespace(typeDescr.getNamespace()); + tempDescr.setFields(typeDescr.getFields()); + tempDescr.setType(target, + typeDescr.getNamespace()); + tempDescr.addSuperType(typeDescr.getType()); + TypeDeclaration tempDeclr = new TypeDeclaration(target); + tempDeclr.setKind(TypeDeclaration.Kind.TRAIT); + tempDeclr.setTypesafe(type.isTypesafe()); + tempDeclr.setNovel(true); + tempDeclr.setTypeClassName(tempDescr.getType().getFullName()); + tempDeclr.setResource(type.getResource()); + + ClassDefinition tempDef = new ClassDefinition(target); + tempDef.setClassName(tempDescr.getType().getFullName()); + tempDef.setTraitable(false); + for (FieldDefinition fld : def.getFieldsDefinitions()) { + tempDef.addField(fld); } - tempDef.setInterfaces( def.getInterfaces() ); - tempDef.setSuperClass( def.getClassName() ); - tempDef.setDefinedClass( resolvedType ); - tempDef.setAbstrakt( true ); - tempDeclr.setTypeClassDef( tempDef ); - - type.setKind( TypeDeclaration.Kind.CLASS ); - - generateDeclaredBean( tempDescr, - tempDeclr, - pkgRegistry, - tempDef ); + tempDef.setInterfaces(def.getInterfaces()); + tempDef.setSuperClass(def.getClassName()); + tempDef.setDefinedClass(resolvedType); + tempDef.setAbstrakt(true); + tempDeclr.setTypeClassDef(tempDef); + + type.setKind(TypeDeclaration.Kind.CLASS); + + generateDeclaredBean(tempDescr, + tempDeclr, + pkgRegistry, + tempDef); try { - Class< ? > clazz = pkgRegistry.getTypeResolver().resolveType( tempDescr.getType().getFullName() ); - tempDeclr.setTypeClass( clazz ); - } catch ( ClassNotFoundException cnfe ) { - this.results.add( new TypeDeclarationError( typeDescr, - "Internal Trait extension Class '" + target + - "' could not be generated correctly'" ) ); + Class<?> clazz = pkgRegistry.getTypeResolver().resolveType(tempDescr.getType().getFullName()); + tempDeclr.setTypeClass(clazz); + } catch (ClassNotFoundException cnfe) { + this.results.add(new TypeDeclarationError(typeDescr, + "Internal Trait extension Class '" + target + + "' could not be generated correctly'")); } finally { - pkgRegistry.getPackage().addTypeDeclaration( tempDeclr ); + pkgRegistry.getPackage().addTypeDeclaration(tempDeclr); } } else { - updateTraitDefinition( type, - resolvedType ); - pkgRegistry.getTraitRegistry().addTrait( def ); + updateTraitDefinition(type, + resolvedType); + pkgRegistry.getTraitRegistry().addTrait(def); } - } catch ( ClassNotFoundException cnfe ) { + } catch (ClassNotFoundException cnfe) { // we already know the class exists } } else { - if ( def.getClassName().endsWith( TraitFactory.SUFFIX ) ) { - pkgRegistry.getTraitRegistry().addTrait( def.getClassName().replace( TraitFactory.SUFFIX, - "" ), - def ); + if (def.getClassName().endsWith(TraitFactory.SUFFIX)) { + pkgRegistry.getTraitRegistry().addTrait(def.getClassName().replace(TraitFactory.SUFFIX, + ""), + def); } else { - pkgRegistry.getTraitRegistry().addTrait( def ); + pkgRegistry.getTraitRegistry().addTrait(def); } } } - if ( type.isNovel() ) { + if (type.isNovel()) { String fullName = typeDescr.getType().getFullName(); - JavaDialectRuntimeData dialect = (JavaDialectRuntimeData) pkgRegistry.getDialectRuntimeRegistry().getDialectData( "java" ); - switch ( type.getKind() ) { - case TRAIT : + JavaDialectRuntimeData dialect = (JavaDialectRuntimeData) pkgRegistry.getDialectRuntimeRegistry().getDialectData("java"); + switch (type.getKind()) { + case TRAIT: try { buildClass(def, fullName, dialect, configuration.getClassBuilderFactory().getTraitBuilder()); - } catch ( Exception e ) { - this.results.add( new TypeDeclarationError( typeDescr, - "Unable to compile declared trait " + fullName + - ": " + e.getMessage() + ";" ) ); + } catch (Exception e) { + this.results.add(new TypeDeclarationError(typeDescr, + "Unable to compile declared trait " + fullName + + ": " + e.getMessage() + ";")); } break; - case ENUM : + case ENUM: try { buildClass(def, fullName, dialect, configuration.getClassBuilderFactory().getEnumClassBuilder()); - } catch ( Exception e ) { + } catch (Exception e) { e.printStackTrace(); - this.results.add( new TypeDeclarationError( typeDescr, - "Unable to compile declared enum " + fullName + - ": " + e.getMessage() + ";" ) ); + this.results.add(new TypeDeclarationError(typeDescr, + "Unable to compile declared enum " + fullName + + ": " + e.getMessage() + ";")); } break; - case CLASS : - default : + case CLASS: + default: try { buildClass(def, fullName, dialect, configuration.getClassBuilderFactory().getBeanClassBuilder()); - } catch ( Exception e ) { - this.results.add( new TypeDeclarationError( typeDescr, - "Unable to create a class for declared type " + fullName + - ": " + e.getMessage() + ";" ) ); + } catch (Exception e) { + this.results.add(new TypeDeclarationError(typeDescr, + "Unable to create a class for declared type " + fullName + + ": " + e.getMessage() + ";")); } break; } @@ -3132,16 +3172,16 @@ private void generateDeclaredBean(AbstractClassTypeDeclarationDescr typeDescr, } private void buildClass(ClassDefinition def, String fullName, JavaDialectRuntimeData dialect, ClassBuilder cb) throws Exception { - byte[] bytecode = cb.buildClass( def ); - String resourceName = JavaDialectRuntimeData.convertClassToResourcePath( fullName ); - dialect.putClassDefinition( resourceName, bytecode ); - if ( ruleBase != null ) { - ruleBase.registerAndLoadTypeDefinition( fullName, bytecode ); + byte[] bytecode = cb.buildClass(def); + String resourceName = JavaDialectRuntimeData.convertClassToResourcePath(fullName); + dialect.putClassDefinition(resourceName, bytecode); + if (ruleBase != null) { + ruleBase.registerAndLoadTypeDefinition(fullName, bytecode); } else { if (rootClassLoader instanceof ProjectClassLoader) { - ((ProjectClassLoader)rootClassLoader).defineClass(fullName, resourceName, bytecode); + ((ProjectClassLoader) rootClassLoader).defineClass(fullName, resourceName, bytecode); } else { - dialect.write( resourceName, bytecode ); + dialect.write(resourceName, bytecode); } } } @@ -3157,71 +3197,71 @@ private void buildClass(ClassDefinition def, String fullName, JavaDialectRuntime * @return */ private PriorityQueue<FieldDefinition> sortFields(Map<String, TypeFieldDescr> flds, - PackageRegistry pkgRegistry) { - PriorityQueue<FieldDefinition> queue = new PriorityQueue<FieldDefinition>( flds.size() ); + PackageRegistry pkgRegistry) { + PriorityQueue<FieldDefinition> queue = new PriorityQueue<FieldDefinition>(flds.size()); int maxDeclaredPos = 0; int curr = 0; - BitSet occupiedPositions = new BitSet( flds.size() ); - for( TypeFieldDescr field : flds.values() ) { + BitSet occupiedPositions = new BitSet(flds.size()); + for (TypeFieldDescr field : flds.values()) { int pos = field.getIndex(); - if ( pos >= 0 ) { - occupiedPositions.set( pos ); + if (pos >= 0) { + occupiedPositions.set(pos); } - maxDeclaredPos = Math.max( maxDeclaredPos, pos ); + maxDeclaredPos = Math.max(maxDeclaredPos, pos); } - for ( TypeFieldDescr field : flds.values() ) { + for (TypeFieldDescr field : flds.values()) { try { String typeName = field.getPattern().getObjectType(); - String fullFieldType = generatedTypes.contains( typeName ) ? typeName : pkgRegistry.getTypeResolver().resolveType( typeName ).getName(); + String fullFieldType = generatedTypes.contains(typeName) ? typeName : pkgRegistry.getTypeResolver().resolveType(typeName).getName(); - FieldDefinition fieldDef = new FieldDefinition( field.getFieldName(), - fullFieldType ); + FieldDefinition fieldDef = new FieldDefinition(field.getFieldName(), + fullFieldType); // field is marked as PK - boolean isKey = field.getAnnotation( TypeDeclaration.ATTR_KEY ) != null; - fieldDef.setKey( isKey ); - - fieldDef.setDeclIndex( field.getIndex() ); - if ( field.getIndex() < 0 ) { - int freePos = occupiedPositions.nextClearBit( 0 ); - if ( freePos < maxDeclaredPos ) { - occupiedPositions.set( freePos ); + boolean isKey = field.getAnnotation(TypeDeclaration.ATTR_KEY) != null; + fieldDef.setKey(isKey); + + fieldDef.setDeclIndex(field.getIndex()); + if (field.getIndex() < 0) { + int freePos = occupiedPositions.nextClearBit(0); + if (freePos < maxDeclaredPos) { + occupiedPositions.set(freePos); } else { freePos = maxDeclaredPos + 1; } - fieldDef.setPriority( freePos * 256 + curr++ ); + fieldDef.setPriority(freePos * 256 + curr++); } else { - fieldDef.setPriority( field.getIndex() * 256 + curr++ ); + fieldDef.setPriority(field.getIndex() * 256 + curr++); } - fieldDef.setInherited( field.isInherited() ); - fieldDef.setInitExpr( field.getInitExpr() ); + fieldDef.setInherited(field.isInherited()); + fieldDef.setInitExpr(field.getInitExpr()); - for ( String annotationName : field.getAnnotationNames() ) { - Class annotation = resolveAnnotation( annotationName, - pkgRegistry.getTypeResolver() ); - if ( annotation != null ) { + for (String annotationName : field.getAnnotationNames()) { + Class annotation = resolveAnnotation(annotationName, + pkgRegistry.getTypeResolver()); + if (annotation != null) { try { - AnnotationDefinition annotationDefinition = AnnotationDefinition.build( annotation, - field.getAnnotations().get( annotationName ).getValueMap(), - pkgRegistry.getTypeResolver() ); - fieldDef.addAnnotation( annotationDefinition ); - } catch ( NoSuchMethodException nsme ) { - this.results.add( new TypeDeclarationError( field, - "Annotated field " + field.getFieldName() + - " - undefined property in @annotation " + - annotationName + ": " + nsme.getMessage() + ";" ) ); + AnnotationDefinition annotationDefinition = AnnotationDefinition.build(annotation, + field.getAnnotations().get(annotationName).getValueMap(), + pkgRegistry.getTypeResolver()); + fieldDef.addAnnotation(annotationDefinition); + } catch (NoSuchMethodException nsme) { + this.results.add(new TypeDeclarationError(field, + "Annotated field " + field.getFieldName() + + " - undefined property in @annotation " + + annotationName + ": " + nsme.getMessage() + ";")); } } if (annotation == null || annotation == Key.class || annotation == Position.class) { - fieldDef.addMetaData( annotationName, field.getAnnotation( annotationName ).getSingleValue() ); + fieldDef.addMetaData(annotationName, field.getAnnotation(annotationName).getSingleValue()); } } - queue.add( fieldDef ); - } catch ( ClassNotFoundException cnfe ) { - this.results.add( new TypeDeclarationError( field, cnfe.getMessage() ) ); + queue.add(fieldDef); + } catch (ClassNotFoundException cnfe) { + this.results.add(new TypeDeclarationError(field, cnfe.getMessage())); } } @@ -3230,45 +3270,45 @@ private PriorityQueue<FieldDefinition> sortFields(Map<String, TypeFieldDescr> fl } private void addFunction(final FunctionDescr functionDescr) { - functionDescr.setResource( this.resource ); - PackageRegistry pkgRegistry = this.pkgRegistryMap.get( functionDescr.getNamespace() ); - Dialect dialect = pkgRegistry.getDialectCompiletimeRegistry().getDialect( functionDescr.getDialect() ); - dialect.addFunction( functionDescr, - pkgRegistry.getTypeResolver(), - this.resource ); + functionDescr.setResource(this.resource); + PackageRegistry pkgRegistry = this.pkgRegistryMap.get(functionDescr.getNamespace()); + Dialect dialect = pkgRegistry.getDialectCompiletimeRegistry().getDialect(functionDescr.getDialect()); + dialect.addFunction(functionDescr, + pkgRegistry.getTypeResolver(), + this.resource); } private void preCompileAddFunction(final FunctionDescr functionDescr) { - PackageRegistry pkgRegistry = this.pkgRegistryMap.get( functionDescr.getNamespace() ); - Dialect dialect = pkgRegistry.getDialectCompiletimeRegistry().getDialect( functionDescr.getDialect() ); - dialect.preCompileAddFunction( functionDescr, - pkgRegistry.getTypeResolver() ); + PackageRegistry pkgRegistry = this.pkgRegistryMap.get(functionDescr.getNamespace()); + Dialect dialect = pkgRegistry.getDialectCompiletimeRegistry().getDialect(functionDescr.getDialect()); + dialect.preCompileAddFunction(functionDescr, + pkgRegistry.getTypeResolver()); } private void postCompileAddFunction(final FunctionDescr functionDescr) { - PackageRegistry pkgRegistry = this.pkgRegistryMap.get( functionDescr.getNamespace() ); - Dialect dialect = pkgRegistry.getDialectCompiletimeRegistry().getDialect( functionDescr.getDialect() ); - dialect.postCompileAddFunction( functionDescr, - pkgRegistry.getTypeResolver() ); + PackageRegistry pkgRegistry = this.pkgRegistryMap.get(functionDescr.getNamespace()); + Dialect dialect = pkgRegistry.getDialectCompiletimeRegistry().getDialect(functionDescr.getDialect()); + dialect.postCompileAddFunction(functionDescr, + pkgRegistry.getTypeResolver()); } private Map<String, RuleBuildContext> buildRuleBuilderContext(List<RuleDescr> rules) { Map<String, RuleBuildContext> map = new HashMap<String, RuleBuildContext>(); - for ( RuleDescr ruleDescr : rules ) { - if ( ruleDescr.getResource() == null ) { - ruleDescr.setResource( resource ); + for (RuleDescr ruleDescr : rules) { + if (ruleDescr.getResource() == null) { + ruleDescr.setResource(resource); } - PackageRegistry pkgRegistry = this.pkgRegistryMap.get( ruleDescr.getNamespace() ); + PackageRegistry pkgRegistry = this.pkgRegistryMap.get(ruleDescr.getNamespace()); Package pkg = pkgRegistry.getPackage(); DialectCompiletimeRegistry ctr = pkgRegistry.getDialectCompiletimeRegistry(); - RuleBuildContext context = new RuleBuildContext( this, - ruleDescr, - ctr, - pkg, - ctr.getDialect( pkgRegistry.getDialect() ) ); - map.put( ruleDescr.getName(), context ); + RuleBuildContext context = new RuleBuildContext(this, + ruleDescr, + ctr, + pkg, + ctr.getDialect(pkgRegistry.getDialect())); + map.put(ruleDescr.getName(), context); } return map; @@ -3279,16 +3319,16 @@ private void addRule(RuleBuildContext context) { Package pkg = context.getPkg(); - ruleBuilder.build( context ); + ruleBuilder.build(context); - this.results.addAll( context.getErrors() ); - this.results.addAll( context.getWarnings() ); + this.results.addAll(context.getErrors()); + this.results.addAll(context.getWarnings()); - context.getRule().setResource( ruleDescr.getResource() ); + context.getRule().setResource(ruleDescr.getResource()); - context.getDialect().addRule( context ); + context.getDialect().addRule(context); - if ( context.needsStreamMode() ) { + if (context.needsStreamMode()) { pkg.setNeedStreamMode(); } } @@ -3303,15 +3343,15 @@ private void addRule(RuleBuildContext context) { */ public Package getPackage() { PackageRegistry pkgRegistry = null; - if ( !this.pkgRegistryMap.isEmpty() ) { + if (!this.pkgRegistryMap.isEmpty()) { pkgRegistry = (PackageRegistry) this.pkgRegistryMap.values().toArray()[currentRulePackage]; } Package pkg = null; - if ( pkgRegistry != null ) { + if (pkgRegistry != null) { pkg = pkgRegistry.getPackage(); } - if ( hasErrors() && pkg != null ) { - pkg.setError( getErrors().toString() ); + if (hasErrors() && pkg != null) { + pkg.setError(getErrors().toString()); } return pkg; } @@ -3319,15 +3359,15 @@ public Package getPackage() { public Package[] getPackages() { Package[] pkgs = new Package[this.pkgRegistryMap.size()]; String errors = null; - if ( !getErrors().isEmpty() ) { + if (!getErrors().isEmpty()) { errors = getErrors().toString(); } int i = 0; - for ( PackageRegistry pkgRegistry : this.pkgRegistryMap.values() ) { + for (PackageRegistry pkgRegistry : this.pkgRegistryMap.values()) { Package pkg = pkgRegistry.getPackage(); pkg.getDialectRuntimeRegistry().onBeforeExecute(); - if ( errors != null ) { - pkg.setError( errors ); + if (errors != null) { + pkg.setError(errors); } pkgs[i++] = pkg; } @@ -3345,7 +3385,7 @@ public PackageBuilderConfiguration getPackageBuilderConfiguration() { } public PackageRegistry getPackageRegistry(String name) { - return this.pkgRegistryMap.get( name ); + return this.pkgRegistryMap.get(name); } public Map<String, PackageRegistry> getPackageRegistry() { @@ -3361,7 +3401,7 @@ public Collection<String> getPackageNames() { } public List<PackageDescr> getPackageDescrs(String packageName) { - return packages.get( packageName ); + return packages.get(packageName); } /** @@ -3370,16 +3410,16 @@ public List<PackageDescr> getPackageDescrs(String packageName) { */ public DefaultExpander getDslExpander() { DefaultExpander expander = new DefaultExpander(); - if ( this.dslFiles == null || this.dslFiles.isEmpty() ) { + if (this.dslFiles == null || this.dslFiles.isEmpty()) { return null; } - for ( DSLMappingFile file : this.dslFiles ) { - expander.addDSLMapping( file.getMapping() ); + for (DSLMappingFile file : this.dslFiles) { + expander.addDSLMapping(file.getMapping()); } return expander; } - public Map<String, Class< ? >> getGlobals() { + public Map<String, Class<?>> getGlobals() { return this.globals; } @@ -3392,8 +3432,8 @@ public boolean hasErrors() { } public KnowledgeBuilderResults getProblems(ResultSeverity... problemTypes) { - List<KnowledgeBuilderResult> problems = getResultList( problemTypes ); - return new PackageBuilderResults( problems.toArray( new BaseKnowledgeBuilderResultImpl[problems.size()] ) ); + List<KnowledgeBuilderResult> problems = getResultList(problemTypes); + return new PackageBuilderResults(problems.toArray(new BaseKnowledgeBuilderResultImpl[problems.size()])); } /** @@ -3401,28 +3441,28 @@ public KnowledgeBuilderResults getProblems(ResultSeverity... problemTypes) { * @return */ private List<KnowledgeBuilderResult> getResultList(ResultSeverity... severities) { - List<ResultSeverity> typesToFetch = Arrays.asList( severities ); + List<ResultSeverity> typesToFetch = Arrays.asList(severities); ArrayList<KnowledgeBuilderResult> problems = new ArrayList<KnowledgeBuilderResult>(); - for ( KnowledgeBuilderResult problem : results ) { - if ( typesToFetch.contains( problem.getSeverity() ) ) { - problems.add( problem ); + for (KnowledgeBuilderResult problem : results) { + if (typesToFetch.contains(problem.getSeverity())) { + problems.add(problem); } } return problems; } public boolean hasProblems(ResultSeverity... problemTypes) { - return !getResultList( problemTypes ).isEmpty(); + return !getResultList(problemTypes).isEmpty(); } private List<DroolsError> getErrorList() { List<DroolsError> errors = new ArrayList<DroolsError>(); - for ( KnowledgeBuilderResult problem : results ) { - if ( problem.getSeverity() == ResultSeverity.ERROR ) { - if ( problem instanceof ConfigurableSeverityResult ) { - errors.add( new DroolsErrorWrapper( problem ) ); + for (KnowledgeBuilderResult problem : results) { + if (problem.getSeverity() == ResultSeverity.ERROR) { + if (problem instanceof ConfigurableSeverityResult) { + errors.add(new DroolsErrorWrapper(problem)); } else { - errors.add( (DroolsError) problem ); + errors.add((DroolsError) problem); } } } @@ -3439,12 +3479,12 @@ public boolean hasInfo() { public List<DroolsWarning> getWarningList() { List<DroolsWarning> warnings = new ArrayList<DroolsWarning>(); - for ( KnowledgeBuilderResult problem : results ) { - if ( problem.getSeverity() == ResultSeverity.WARNING ) { - if ( problem instanceof ConfigurableSeverityResult ) { - warnings.add( new DroolsWarningWrapper( problem ) ); + for (KnowledgeBuilderResult problem : results) { + if (problem.getSeverity() == ResultSeverity.WARNING) { + if (problem instanceof ConfigurableSeverityResult) { + warnings.add(new DroolsWarningWrapper(problem)); } else { - warnings.add( (DroolsWarning) problem ); + warnings.add((DroolsWarning) problem); } } } @@ -3452,7 +3492,7 @@ public List<DroolsWarning> getWarningList() { } private List<KnowledgeBuilderResult> getInfoList() { - return getResultList( ResultSeverity.INFO ); + return getResultList(ResultSeverity.INFO); } /** @@ -3461,7 +3501,7 @@ private List<KnowledgeBuilderResult> getInfoList() { */ public PackageBuilderErrors getErrors() { List<DroolsError> errors = getErrorList(); - return new PackageBuilderErrors( errors.toArray( new DroolsError[errors.size()] ) ); + return new PackageBuilderErrors(errors.toArray(new DroolsError[errors.size()])); } /** @@ -3471,21 +3511,21 @@ public PackageBuilderErrors getErrors() { * you will get spurious errors which will not be that helpful. */ protected void resetErrors() { - resetProblemType( ResultSeverity.ERROR ); + resetProblemType(ResultSeverity.ERROR); } protected void resetWarnings() { - resetProblemType( ResultSeverity.WARNING ); + resetProblemType(ResultSeverity.WARNING); } private void resetProblemType(ResultSeverity problemType) { List<KnowledgeBuilderResult> toBeDeleted = new ArrayList<KnowledgeBuilderResult>(); - for ( KnowledgeBuilderResult problem : results ) { - if ( problemType != null && problemType.equals( problem.getSeverity() ) ) { - toBeDeleted.add( problem ); + for (KnowledgeBuilderResult problem : results) { + if (problemType != null && problemType.equals(problem.getSeverity())) { + toBeDeleted.add(problem); } } - this.results.removeAll( toBeDeleted ); + this.results.removeAll(toBeDeleted); } @@ -3502,7 +3542,7 @@ public static class MissingPackageNameException extends IllegalArgumentException private static final long serialVersionUID = 510l; public MissingPackageNameException(final String message) { - super( message ); + super(message); } } @@ -3512,7 +3552,7 @@ public static class PackageMergeException extends IllegalArgumentException { private static final long serialVersionUID = 400L; public PackageMergeException(final String message) { - super( message ); + super(message); } } @@ -3542,7 +3582,7 @@ public boolean isInError() { } public void addError(final CompilationProblem err) { - this.errors.add( err ); + this.errors.add(err); this.inError = true; } @@ -3559,11 +3599,11 @@ public void addError(final CompilationProblem err) { * DroolsError instances. Its not 1 to 1 with reported errors. */ protected CompilationProblem[] collectCompilerProblems() { - if ( this.errors.isEmpty() ) { + if (this.errors.isEmpty()) { return null; } else { final CompilationProblem[] list = new CompilationProblem[this.errors.size()]; - this.errors.toArray( list ); + this.errors.toArray(list); return list; } } @@ -3576,18 +3616,18 @@ public static class RuleErrorHandler extends ErrorHandler { private Rule rule; public RuleErrorHandler(final BaseDescr ruleDescr, - final Rule rule, - final String message) { + final Rule rule, + final String message) { this.descr = ruleDescr; this.rule = rule; this.message = message; } public DroolsError getError() { - return new RuleBuildError( this.rule, - this.descr, - collectCompilerProblems(), - this.message ); + return new RuleBuildError(this.rule, + this.descr, + collectCompilerProblems(), + this.message); } } @@ -3598,11 +3638,11 @@ public DroolsError getError() { public static class RuleInvokerErrorHandler extends RuleErrorHandler { public RuleInvokerErrorHandler(final BaseDescr ruleDescr, - final Rule rule, - final String message) { - super( ruleDescr, - rule, - message ); + final Rule rule, + final String message) { + super(ruleDescr, + rule, + message); } } @@ -3611,15 +3651,15 @@ public static class FunctionErrorHandler extends ErrorHandler { private FunctionDescr descr; public FunctionErrorHandler(final FunctionDescr functionDescr, - final String message) { + final String message) { this.descr = functionDescr; this.message = message; } public DroolsError getError() { - return new FunctionError( this.descr, - collectCompilerProblems(), - this.message ); + return new FunctionError(this.descr, + collectCompilerProblems(), + this.message); } } @@ -3631,8 +3671,8 @@ public SrcErrorHandler(final String message) { } public DroolsError getError() { - return new SrcError( collectCompilerProblems(), - this.message ); + return new SrcError(collectCompilerProblems(), + this.message); } } @@ -3644,8 +3684,8 @@ public static class SrcError extends DroolsError { private int[] errorLines = new int[0]; public SrcError(Object object, - String message) { - super( null ); + String message) { + super(null); this.object = object; this.message = message; } @@ -3664,18 +3704,18 @@ public String getMessage() { public String toString() { final StringBuilder buf = new StringBuilder(); - buf.append( this.message ); - buf.append( " : " ); - buf.append( "\n" ); - if ( this.object instanceof CompilationProblem[] ) { + buf.append(this.message); + buf.append(" : "); + buf.append("\n"); + if (this.object instanceof CompilationProblem[]) { final CompilationProblem[] problem = (CompilationProblem[]) this.object; - for ( CompilationProblem aProblem : problem ) { - buf.append( "\t" ); - buf.append( aProblem ); - buf.append( "\n" ); + for (CompilationProblem aProblem : problem) { + buf.append("\t"); + buf.append(aProblem); + buf.append("\n"); } - } else if ( this.object != null ) { - buf.append( this.object ); + } else if (this.object != null) { + buf.append(this.object); } return buf.toString(); } @@ -3701,68 +3741,68 @@ public Collection<AbstractClassTypeDeclarationDescr> sortByHierarchy(List<Abstra Map<QualifiedName, Collection<QualifiedName>> taxonomy = new HashMap<QualifiedName, Collection<QualifiedName>>(); Map<QualifiedName, AbstractClassTypeDeclarationDescr> cache = new HashMap<QualifiedName, AbstractClassTypeDeclarationDescr>(); - for ( AbstractClassTypeDeclarationDescr tdescr : typeDeclarations ) { + for (AbstractClassTypeDeclarationDescr tdescr : typeDeclarations) { QualifiedName name = tdescr.getType(); - cache.put( name, tdescr ); + cache.put(name, tdescr); - if ( taxonomy.get( name ) == null ) { - taxonomy.put( name, new ArrayList<QualifiedName>() ); + if (taxonomy.get(name) == null) { + taxonomy.put(name, new ArrayList<QualifiedName>()); } else { - this.results.add( new TypeDeclarationError( tdescr, - "Found duplicate declaration for type " + tdescr.getTypeName() ) ); + this.results.add(new TypeDeclarationError(tdescr, + "Found duplicate declaration for type " + tdescr.getTypeName())); } - Collection<QualifiedName> supers = taxonomy.get( name ); + Collection<QualifiedName> supers = taxonomy.get(name); boolean circular = false; - for ( QualifiedName sup : tdescr.getSuperTypes() ) { - if ( !Object.class.getName().equals( name.getFullName() ) ) { - if ( !hasCircularDependency( tdescr.getType(), sup, taxonomy ) ) { - supers.add( sup ); + for (QualifiedName sup : tdescr.getSuperTypes()) { + if (!Object.class.getName().equals(name.getFullName())) { + if (!hasCircularDependency(tdescr.getType(), sup, taxonomy)) { + supers.add(sup); } else { circular = true; - this.results.add( new TypeDeclarationError( tdescr, - "Found circular dependency for type " + tdescr.getTypeName() ) ); + this.results.add(new TypeDeclarationError(tdescr, + "Found circular dependency for type " + tdescr.getTypeName())); break; } } } - if ( circular ) { + if (circular) { tdescr.getSuperTypes().clear(); } - for ( TypeFieldDescr field : tdescr.getFields().values() ) { - QualifiedName typeName = new QualifiedName( field.getPattern().getObjectType() ); - if ( !hasCircularDependency( name, typeName, taxonomy ) ) { - supers.add( typeName ); + for (TypeFieldDescr field : tdescr.getFields().values()) { + QualifiedName typeName = new QualifiedName(field.getPattern().getObjectType()); + if (!hasCircularDependency(name, typeName, taxonomy)) { + supers.add(typeName); } } } - List<QualifiedName> sorted = sorter.sort( taxonomy ); - ArrayList list = new ArrayList( sorted.size() ); - for ( QualifiedName name : sorted ) { - list.add( cache.get( name ) ); + List<QualifiedName> sorted = sorter.sort(taxonomy); + ArrayList list = new ArrayList(sorted.size()); + for (QualifiedName name : sorted) { + list.add(cache.get(name)); } return list; } private boolean hasCircularDependency(QualifiedName name, - QualifiedName typeName, - Map<QualifiedName, Collection<QualifiedName>> taxonomy) { - if ( name.equals( typeName ) ) { + QualifiedName typeName, + Map<QualifiedName, Collection<QualifiedName>> taxonomy) { + if (name.equals(typeName)) { return true; } - if ( taxonomy.containsKey( typeName ) ) { - Collection<QualifiedName> parents = taxonomy.get( typeName ); - if ( parents.contains( name ) ) { + if (taxonomy.containsKey(typeName)) { + Collection<QualifiedName> parents = taxonomy.get(typeName); + if (parents.contains(name)) { return true; } else { - for ( QualifiedName ancestor : parents ) { - if ( hasCircularDependency( name, ancestor, taxonomy ) ) { + for (QualifiedName ancestor : parents) { + if (hasCircularDependency(name, ancestor, taxonomy)) { return true; } } @@ -3773,55 +3813,55 @@ private boolean hasCircularDependency(QualifiedName name, //Entity rules inherit package attributes private void inheritPackageAttributes(Map<String, AttributeDescr> pkgAttributes, - RuleDescr ruleDescr) { - if ( pkgAttributes == null ) { + RuleDescr ruleDescr) { + if (pkgAttributes == null) { return; } - for ( AttributeDescr attrDescr : pkgAttributes.values() ) { + for (AttributeDescr attrDescr : pkgAttributes.values()) { String name = attrDescr.getName(); - AttributeDescr ruleAttrDescr = ruleDescr.getAttributes().get( name ); - if ( ruleAttrDescr == null ) { - ruleDescr.getAttributes().put( name, - attrDescr ); + AttributeDescr ruleAttrDescr = ruleDescr.getAttributes().get(name); + if (ruleAttrDescr == null) { + ruleDescr.getAttributes().put(name, + attrDescr); } } } private int compareTypeDeclarations(TypeDeclaration oldDeclaration, - TypeDeclaration newDeclaration) throws IncompatibleClassChangeError { + TypeDeclaration newDeclaration) throws IncompatibleClassChangeError { //different formats -> incompatible - if ( !oldDeclaration.getFormat().equals( newDeclaration.getFormat() ) ) { - throw new IncompatibleClassChangeError( "Type Declaration " + newDeclaration.getTypeName() + " has a different" - + " format that its previous definition: " + newDeclaration.getFormat() + "!=" + oldDeclaration.getFormat() ); + if (!oldDeclaration.getFormat().equals(newDeclaration.getFormat())) { + throw new IncompatibleClassChangeError("Type Declaration " + newDeclaration.getTypeName() + " has a different" + + " format that its previous definition: " + newDeclaration.getFormat() + "!=" + oldDeclaration.getFormat()); } //different superclasses -> Incompatible (TODO: check for hierarchy) - if ( !oldDeclaration.getTypeClassDef().getSuperClass().equals( newDeclaration.getTypeClassDef().getSuperClass() ) ) { - if ( oldDeclaration.getNature() == TypeDeclaration.Nature.DEFINITION - && newDeclaration.getNature() == TypeDeclaration.Nature.DECLARATION - && Object.class.getName().equals( newDeclaration.getTypeClassDef().getSuperClass() ) ) { + if (!oldDeclaration.getTypeClassDef().getSuperClass().equals(newDeclaration.getTypeClassDef().getSuperClass())) { + if (oldDeclaration.getNature() == TypeDeclaration.Nature.DEFINITION + && newDeclaration.getNature() == TypeDeclaration.Nature.DECLARATION + && Object.class.getName().equals(newDeclaration.getTypeClassDef().getSuperClass())) { // actually do nothing. The new declaration just recalls the previous definition, probably to extend it. } else { - throw new IncompatibleClassChangeError( "Type Declaration " + newDeclaration.getTypeName() + " has a different" - + " superclass that its previous definition: " + newDeclaration.getTypeClassDef().getSuperClass() - + " != " + oldDeclaration.getTypeClassDef().getSuperClass() ); + throw new IncompatibleClassChangeError("Type Declaration " + newDeclaration.getTypeName() + " has a different" + + " superclass that its previous definition: " + newDeclaration.getTypeClassDef().getSuperClass() + + " != " + oldDeclaration.getTypeClassDef().getSuperClass()); } } //different duration -> Incompatible - if ( !this.nullSafeEqualityComparison( oldDeclaration.getDurationAttribute(), newDeclaration.getDurationAttribute() ) ) { - throw new IncompatibleClassChangeError( "Type Declaration " + newDeclaration.getTypeName() + " has a different" - + " duration: " + newDeclaration.getDurationAttribute() - + " != " + oldDeclaration.getDurationAttribute() ); + if (!this.nullSafeEqualityComparison(oldDeclaration.getDurationAttribute(), newDeclaration.getDurationAttribute())) { + throw new IncompatibleClassChangeError("Type Declaration " + newDeclaration.getTypeName() + " has a different" + + " duration: " + newDeclaration.getDurationAttribute() + + " != " + oldDeclaration.getDurationAttribute()); } // //different masks -> incompatible - if ( newDeclaration.getNature().equals( TypeDeclaration.Nature.DEFINITION ) ) { - if ( oldDeclaration.getSetMask() != newDeclaration.getSetMask() ) { - throw new IncompatibleClassChangeError( "Type Declaration " + newDeclaration.getTypeName() + " is incompatible with" - + " the previous definition: " + newDeclaration - + " != " + oldDeclaration ); + if (newDeclaration.getNature().equals(TypeDeclaration.Nature.DEFINITION)) { + if (oldDeclaration.getSetMask() != newDeclaration.getSetMask()) { + throw new IncompatibleClassChangeError("Type Declaration " + newDeclaration.getTypeName() + " is incompatible with" + + " the previous definition: " + newDeclaration + + " != " + oldDeclaration); } } @@ -3830,24 +3870,24 @@ private int compareTypeDeclarations(TypeDeclaration oldDeclaration, //Field comparison List<FactField> oldFields = oldDeclaration.getTypeClassDef().getFields(); Map<String, FactField> newFieldsMap = new HashMap<String, FactField>(); - for ( FactField factField : newDeclaration.getTypeClassDef().getFields() ) { - newFieldsMap.put( factField.getName(), factField ); + for (FactField factField : newDeclaration.getTypeClassDef().getFields()) { + newFieldsMap.put(factField.getName(), factField); } //each of the fields in the old definition that are also present in the //new definition must have the same type. If not -> Incompatible boolean allFieldsInOldDeclarationAreStillPresent = true; - for ( FactField oldFactField : oldFields ) { - FactField newFactField = newFieldsMap.get( oldFactField.getName() ); + for (FactField oldFactField : oldFields) { + FactField newFactField = newFieldsMap.get(oldFactField.getName()); - if ( newFactField != null ) { + if (newFactField != null) { //we can't use newFactField.getType() since it throws a NPE at this point. String newFactType = ((FieldDefinition) newFactField).getTypeName(); - if ( !newFactType.equals( oldFactField.getType().getCanonicalName() ) ) { - throw new IncompatibleClassChangeError( "Type Declaration " + newDeclaration.getTypeName() + "." + newFactField.getName() + " has a different" - + " type that its previous definition: " + newFactType - + " != " + oldFactField.getType().getCanonicalName() ); + if (!newFactType.equals(oldFactField.getType().getCanonicalName())) { + throw new IncompatibleClassChangeError("Type Declaration " + newDeclaration.getTypeName() + "." + newFactField.getName() + " has a different" + + " type that its previous definition: " + newFactType + + " != " + oldFactField.getType().getCanonicalName()); } } else { allFieldsInOldDeclarationAreStillPresent = false; @@ -3856,12 +3896,12 @@ private int compareTypeDeclarations(TypeDeclaration oldDeclaration, } //If the old declaration has less fields than the new declaration, oldDefinition < newDefinition - if ( oldFields.size() < newFieldsMap.size() ) { + if (oldFields.size() < newFieldsMap.size()) { return -1; } //If the old declaration has more fields than the new declaration, oldDefinition > newDefinition - if ( oldFields.size() > newFieldsMap.size() ) { + if (oldFields.size() > newFieldsMap.size()) { return 1; } @@ -3869,14 +3909,14 @@ private int compareTypeDeclarations(TypeDeclaration oldDeclaration, //and all the fieds present in the old declaration are also present in //the new declaration, then they are considered "equal", otherwise //they are incompatible - if ( allFieldsInOldDeclarationAreStillPresent ) { + if (allFieldsInOldDeclarationAreStillPresent) { return 0; } //Both declarations have the same number of fields, but not all the //fields in the old declaration are present in the new declaration. - throw new IncompatibleClassChangeError( newDeclaration.getTypeName() + " introduces" - + " fields that are not present in its previous version." ); + throw new IncompatibleClassChangeError(newDeclaration.getTypeName() + " introduces" + + " fields that are not present in its previous version."); } @@ -3886,37 +3926,38 @@ private int compareTypeDeclarations(TypeDeclaration oldDeclaration, * @param newDeclaration */ private void mergeTypeDeclarations(TypeDeclaration oldDeclaration, - TypeDeclaration newDeclaration) { - if ( oldDeclaration == null ) { + TypeDeclaration newDeclaration) { + if (oldDeclaration == null) { return; } //add the missing fields (if any) to newDeclaration - for ( FieldDefinition oldFactField : oldDeclaration.getTypeClassDef().getFieldsDefinitions() ) { - FieldDefinition newFactField = newDeclaration.getTypeClassDef().getField( oldFactField.getName() ); - if ( newFactField == null ) { - newDeclaration.getTypeClassDef().addField( oldFactField ); + for (FieldDefinition oldFactField : oldDeclaration.getTypeClassDef().getFieldsDefinitions()) { + FieldDefinition newFactField = newDeclaration.getTypeClassDef().getField(oldFactField.getName()); + if (newFactField == null) { + newDeclaration.getTypeClassDef().addField(oldFactField); } } //copy the defined class - newDeclaration.setTypeClass( oldDeclaration.getTypeClass() ); + newDeclaration.setTypeClass(oldDeclaration.getTypeClass()); } private boolean nullSafeEqualityComparison(Comparable c1, - Comparable c2) { - if ( c1 == null ) { + Comparable c2) { + if (c1 == null) { return c2 == null; } - return c2 != null && c1.compareTo( c2 ) == 0; + return c2 != null && c1.compareTo(c2) == 0; } static class TypeDefinition { + private final AbstractClassTypeDeclarationDescr typeDescr; private final TypeDeclaration type; private TypeDefinition(TypeDeclaration type, - AbstractClassTypeDeclarationDescr typeDescr) { + AbstractClassTypeDeclarationDescr typeDescr) { this.type = type; this.typeDescr = typeDescr; } @@ -3930,20 +3971,20 @@ public String getNamespace() { } } - private ChangeSet parseChangeSet( Resource resource ) throws IOException, SAXException { - XmlChangeSetReader reader = new XmlChangeSetReader( this.configuration.getSemanticModules() ); + private ChangeSet parseChangeSet(Resource resource) throws IOException, SAXException { + XmlChangeSetReader reader = new XmlChangeSetReader(this.configuration.getSemanticModules()); if (resource instanceof ClassPathResource) { - reader.setClassLoader( ( (ClassPathResource) resource ).getClassLoader(), - ( (ClassPathResource) resource ).getClazz() ); + reader.setClassLoader(((ClassPathResource) resource).getClassLoader(), + ((ClassPathResource) resource).getClazz()); } else { - reader.setClassLoader( this.configuration.getClassLoader(), - null ); + reader.setClassLoader(this.configuration.getClassLoader(), + null); } Reader resourceReader = null; try { resourceReader = resource.getReader(); - ChangeSet changeSet = reader.read( resourceReader ); + ChangeSet changeSet = reader.read(resourceReader); return changeSet; } finally { if (resourceReader != null) { @@ -3952,103 +3993,106 @@ private ChangeSet parseChangeSet( Resource resource ) throws IOException, SAXExc } } - public void registerBuildResource( final Resource resource, ResourceType type ) { + public void registerBuildResource(final Resource resource, ResourceType type) { InternalResource ires = (InternalResource) resource; - if ( ires.getResourceType() == null ) { - ires.setResourceType( type ); - } else if ( ires.getResourceType() != type ) { - this.results.add( new ResourceTypeDeclarationWarning( resource, ires.getResourceType(), type ) ); + if (ires.getResourceType() == null) { + ires.setResourceType(type); + } else if (ires.getResourceType() != type) { + this.results.add(new ResourceTypeDeclarationWarning(resource, ires.getResourceType(), type)); } - if ( ResourceType.CHANGE_SET == type ) { + if (ResourceType.CHANGE_SET == type) { try { - ChangeSet changeSet = parseChangeSet( resource ); - List<Resource> resources = new ArrayList<Resource>( ); - resources.add( resource ); - for ( Resource addedRes : changeSet.getResourcesAdded() ) { - resources.add( addedRes ); + ChangeSet changeSet = parseChangeSet(resource); + List<Resource> resources = new ArrayList<Resource>(); + resources.add(resource); + for (Resource addedRes : changeSet.getResourcesAdded()) { + resources.add(addedRes); } - for ( Resource modifiedRes : changeSet.getResourcesModified() ) { - resources.add( modifiedRes ); + for (Resource modifiedRes : changeSet.getResourcesModified()) { + resources.add(modifiedRes); } - for ( Resource removedRes : changeSet.getResourcesRemoved() ) { - resources.add( removedRes ); + for (Resource removedRes : changeSet.getResourcesRemoved()) { + resources.add(removedRes); } - buildResources.push( resources ); - } catch ( Exception e ) { - results.add( new DroolsError() { + buildResources.push(resources); + } catch (Exception e) { + results.add(new DroolsError() { + public String getMessage() { return "Unable to register changeset resource " + resource; } - public int[] getLines() { return new int[ 0 ]; } - } ); + + public int[] getLines() { + return new int[0]; + } + }); } } else { - buildResources.push( Arrays.asList( resource ) ); + buildResources.push(Arrays.asList(resource)); } } - public void registerBuildResources(List<Resource> resources) { - buildResources.push( resources ); + buildResources.push(resources); } public void undo() { - if ( buildResources.isEmpty() ) { + if (buildResources.isEmpty()) { return; } - for ( Resource resource : buildResources.pop() ) { - removeObjectsGeneratedFromResource( resource ); + for (Resource resource : buildResources.pop()) { + removeObjectsGeneratedFromResource(resource); } } public boolean removeObjectsGeneratedFromResource(Resource resource) { boolean modified = false; - if ( pkgRegistryMap != null ) { - for ( PackageRegistry packageRegistry : pkgRegistryMap.values() ) { - modified = packageRegistry.removeObjectsGeneratedFromResource( resource ) || modified; + if (pkgRegistryMap != null) { + for (PackageRegistry packageRegistry : pkgRegistryMap.values()) { + modified = packageRegistry.removeObjectsGeneratedFromResource(resource) || modified; } } - if ( results != null ) { + if (results != null) { Iterator<KnowledgeBuilderResult> i = results.iterator(); - while ( i.hasNext() ) { - if ( resource.equals( i.next().getResource() ) ) { + while (i.hasNext()) { + if (resource.equals(i.next().getResource())) { i.remove(); } } } - if ( processBuilder != null && processBuilder.getErrors() != null ) { + if (processBuilder != null && processBuilder.getErrors() != null) { Iterator<? extends KnowledgeBuilderResult> i = processBuilder.getErrors().iterator(); - while ( i.hasNext() ) { - if ( resource.equals( i.next().getResource() ) ) { + while (i.hasNext()) { + if (resource.equals(i.next().getResource())) { i.remove(); } } } - if ( results.size() == 0 ) { + if (results.size() == 0) { // TODO Error attribution might be bugged - for ( PackageRegistry packageRegistry : pkgRegistryMap.values() ) { + for (PackageRegistry packageRegistry : pkgRegistryMap.values()) { packageRegistry.getPackage().resetErrors(); } } - if ( cacheTypes != null ) { + if (cacheTypes != null) { List<String> typesToBeRemoved = new ArrayList<String>(); - for ( Map.Entry<String, TypeDeclaration> type : cacheTypes.entrySet() ) { - if ( resource.equals( type.getValue().getResource() ) ) { - typesToBeRemoved.add( type.getKey() ); + for (Map.Entry<String, TypeDeclaration> type : cacheTypes.entrySet()) { + if (resource.equals(type.getValue().getResource())) { + typesToBeRemoved.add(type.getKey()); } } - for ( String type : typesToBeRemoved ) { - cacheTypes.remove( type ); + for (String type : typesToBeRemoved) { + cacheTypes.remove(type); } } - for ( List<PackageDescr> pkgDescrs : packages.values() ) { - for ( PackageDescr pkgDescr : pkgDescrs ) { - pkgDescr.removeObjectsGeneratedFromResource( resource ); + for (List<PackageDescr> pkgDescrs : packages.values()) { + for (PackageDescr pkgDescr : pkgDescrs) { + pkgDescr.removeObjectsGeneratedFromResource(resource); } } @@ -4058,4 +4102,20 @@ public boolean removeObjectsGeneratedFromResource(Resource resource) { return modified; } + + public static interface AssetFilter { + public static enum Action { + DO_NOTHING, ADD, REMOVE, UPDATE; + } + + public Action accept(String pkgName, String assetName); + } + + public AssetFilter getAssetFilter() { + return assetFilter; + } + + public void setAssetFilter(AssetFilter assetFilter) { + this.assetFilter = assetFilter; + } } 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 984d6f7f532..fa8c4a94850 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 @@ -9,6 +9,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; @@ -39,6 +40,8 @@ import org.kie.internal.builder.KnowledgeBuilder; import org.kie.internal.builder.KnowledgeBuilderError; import org.kie.internal.builder.KnowledgeBuilderFactory; +import org.kie.internal.builder.ResourceChange; +import org.kie.internal.builder.ResourceChangeSet; import org.kie.internal.definition.KnowledgePackage; import org.kie.internal.io.ResourceFactory; import org.kie.internal.io.ResourceTypeImpl; @@ -351,4 +354,27 @@ private void validatePomModel(PomModel pomModel) { private byte[] getPomXml() { return getBytes(((ReleaseIdImpl)releaseId).getPomXmlPath()); } + + public static boolean updateResource(CompositeKnowledgeBuilder ckbuilder, + InternalKieModule kieModule, + String resourceName, + ResourceChangeSet changes) { + ResourceConfiguration conf = getResourceConfiguration(kieModule, resourceName); + Resource resource = kieModule.getResource(resourceName); + if (resource != null) { + if (conf == null) { + ckbuilder.add(resource, + ResourceType.determineResourceType(resourceName), + changes ); + } else { + ckbuilder.add(resource, + ResourceType.determineResourceType(resourceName), + conf, + changes ); + } + return true; + } + return false; + } + } 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 48243217ef1..0d1d267b562 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 @@ -14,9 +14,7 @@ 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.definitions.impl.KnowledgePackageImp; @@ -34,6 +32,8 @@ import org.kie.api.builder.model.KieSessionModel; import org.kie.api.conf.EventProcessingOption; import org.kie.api.event.KieRuntimeEventManager; +import org.kie.api.io.Resource; +import org.kie.api.io.ResourceType; import org.kie.api.logger.KieLoggers; import org.kie.api.runtime.Environment; import org.kie.api.runtime.KieSession; @@ -41,9 +41,12 @@ import org.kie.api.runtime.StatelessKieSession; import org.kie.internal.KnowledgeBase; import org.kie.internal.KnowledgeBaseFactory; +import org.kie.internal.builder.ChangeType; import org.kie.internal.builder.CompositeKnowledgeBuilder; import org.kie.internal.builder.KnowledgeBuilder; import org.kie.internal.builder.KnowledgeBuilderFactory; +import org.kie.internal.builder.ResourceChange; +import org.kie.internal.builder.ResourceChangeSet; import org.kie.internal.definition.KnowledgePackage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -121,9 +124,23 @@ public void updateToVersion(ReleaseId newReleaseId) { 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; + Resource resource = currentKM.getResource( rcs.getResourceName() ); + List<ResourceChange> changes = rcs.getChanges(); + if( ! changes.isEmpty() ) { + // we need to deal with individual parts of the resource + fileCount += AbstractKieModule.updateResource( ckbuilder, + newKM, + resourceName, + rcs ) ? 1 : 0; + } else { + // the whole resource has to handled + if( rcs.getChangeType().equals( ChangeType.UPDATED ) ) { + pkgbuilder.removeObjectsGeneratedFromResource( resource ); + } + fileCount += AbstractKieModule.addFile( ckbuilder, + newKM, + resourceName ) ? 1 : 0; + } } } } diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/util/ChangeSetBuilder.java b/drools-compiler/src/main/java/org/drools/compiler/kie/util/ChangeSetBuilder.java index ca3b49bdbc8..b154afb38cb 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/util/ChangeSetBuilder.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/util/ChangeSetBuilder.java @@ -24,11 +24,14 @@ import java.util.List; import org.drools.compiler.compiler.DrlParser; -import org.drools.core.io.impl.ByteArrayResource; +import org.drools.compiler.kie.builder.impl.InternalKieModule; import org.drools.compiler.lang.descr.PackageDescr; import org.drools.compiler.lang.descr.RuleDescr; -import org.drools.compiler.kie.builder.impl.InternalKieModule; +import org.drools.core.io.impl.ByteArrayResource; import org.kie.api.io.ResourceType; +import org.kie.internal.builder.ChangeType; +import org.kie.internal.builder.ResourceChange; +import org.kie.internal.builder.ResourceChangeSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -88,10 +91,14 @@ public ResourceChangeSet diffResource(String file, boolean found = false; for( Iterator<RuleDescr> it = orules.iterator(); it.hasNext(); ) { RuleDescr ord = it.next(); - if( ord.getName().equals( crd ) ) { + if( ord.getName().equals( crd.getName() ) ) { found = true; it.remove(); - if( !ord.equals( crd ) ) { + + // using byte[] comparison because using the descriptor equals() method + // is brittle and heavier than iterating an array + if( !segmentEquals(ob, ord.getStartCharacter(), ord.getEndCharacter(), + cb, crd.getStartCharacter(), crd.getEndCharacter() ) ) { pkgcs.getChanges().add( new ResourceChange( ChangeType.UPDATED, ResourceChange.Type.RULE, crd.getName() ) ); @@ -124,6 +131,21 @@ public int compare(ResourceChange o1, return pkgcs; } + private boolean segmentEquals( byte[] a1, int s1, int e1, + byte[] a2, int s2, int e2) { + int length = e1 - s1; + if( length <= 0 || length != e2-s2 || s1+length > a1.length || s2+length > a2.length ) { + return false; + } + for( int i = 0; i < length; i++ ) { + if( a1[s1+i] != a2[s2+i] ) { + return false; + } + } + return true; + } + + public String toProperties( KieJarChangeSet kcs ) { StringBuilder builder = new StringBuilder(); builder.append( "kiejar.changeset.version=1.0\n" ); diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/util/ChangeType.java b/drools-compiler/src/main/java/org/drools/compiler/kie/util/ChangeType.java deleted file mode 100644 index 0a2c4a9dcc3..00000000000 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/util/ChangeType.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.drools.compiler.kie.util; - -public enum ChangeType { - REMOVED, UPDATED, ADDED; - - public String toString() { - return super.toString().toLowerCase(); - } -} diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/util/KieJarChangeSet.java b/drools-compiler/src/main/java/org/drools/compiler/kie/util/KieJarChangeSet.java index bd812a91214..9420297b7a8 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/util/KieJarChangeSet.java +++ b/drools-compiler/src/main/java/org/drools/compiler/kie/util/KieJarChangeSet.java @@ -3,6 +3,8 @@ import java.util.HashMap; import java.util.Map; +import org.kie.internal.builder.ResourceChangeSet; + public class KieJarChangeSet { private final Map<String, ResourceChangeSet> changes = new HashMap<String, ResourceChangeSet>(); diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/util/ResourceChange.java b/drools-compiler/src/main/java/org/drools/compiler/kie/util/ResourceChange.java deleted file mode 100644 index 8e5e2318f24..00000000000 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/util/ResourceChange.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.drools.compiler.kie.util; - - -public class ResourceChange { - public static enum Type { - RULE, DECLARATION, FUNCTION; - public String toString() { - return super.toString().toLowerCase(); - } - } - private final ChangeType action; - private final ResourceChange.Type type; - private final String name; - public ResourceChange(ChangeType action, - ResourceChange.Type type, - String name) { - super(); - this.action = action; - this.type = type; - this.name = name; - } - public ChangeType getChangeType() { - return action; - } - public ResourceChange.Type getType() { - return type; - } - public String getName() { - return name; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((action == null) ? 0 : action.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((type == null) ? 0 : type.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if ( this == obj ) return true; - if ( obj == null ) return false; - if ( getClass() != obj.getClass() ) return false; - ResourceChange other = (ResourceChange) obj; - if ( action != other.action ) return false; - if ( name == null ) { - if ( other.name != null ) return false; - } else if ( !name.equals( other.name ) ) return false; - if ( type != other.type ) return false; - return true; - } - - @Override - public String toString() { - return "ResourceChange [action=" + action + ", type=" + type + ", name=" + name + "]"; - } - -} diff --git a/drools-compiler/src/main/java/org/drools/compiler/kie/util/ResourceChangeSet.java b/drools-compiler/src/main/java/org/drools/compiler/kie/util/ResourceChangeSet.java deleted file mode 100644 index de7dca84cd5..00000000000 --- a/drools-compiler/src/main/java/org/drools/compiler/kie/util/ResourceChangeSet.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.drools.compiler.kie.util; - -import java.util.ArrayList; -import java.util.List; - -public class ResourceChangeSet { - private final String resourceName; // src/main/resources/org/drools/rules.drl - private final ChangeType status; - private final List<ResourceChange> changes = new ArrayList<ResourceChange>(); - - public ResourceChangeSet(String resourceName, ChangeType status) { - this.resourceName = resourceName; - this.status = status; - } - - public String getResourceName() { - return resourceName; - } - - public ChangeType getChangeType() { - return status; - } - - public List<ResourceChange> getChanges() { - return changes; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((changes == null) ? 0 : changes.hashCode()); - result = prime * result + ((resourceName == null) ? 0 : resourceName.hashCode()); - result = prime * result + ((status == null) ? 0 : status.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if ( this == obj ) return true; - if ( obj == null ) return false; - if ( getClass() != obj.getClass() ) return false; - ResourceChangeSet other = (ResourceChangeSet) obj; - if ( changes == null ) { - if ( other.changes != null ) return false; - } else if ( !changes.equals( other.changes ) ) return false; - if ( resourceName == null ) { - if ( other.resourceName != null ) return false; - } else if ( !resourceName.equals( other.resourceName ) ) return false; - if ( status != other.status ) return false; - return true; - } -} diff --git a/drools-compiler/src/main/java/org/drools/compiler/lang/descr/AndDescr.java b/drools-compiler/src/main/java/org/drools/compiler/lang/descr/AndDescr.java index 6933b325d1f..a753cea6119 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/lang/descr/AndDescr.java +++ b/drools-compiler/src/main/java/org/drools/compiler/lang/descr/AndDescr.java @@ -77,8 +77,6 @@ public boolean removeDescr(BaseDescr baseDescr) { return baseDescr == null ? false : descrs.remove(baseDescr); } - - public String toString() { return "[AND "+descrs+" ]"; } diff --git a/drools-compiler/src/main/java/org/drools/compiler/lang/descr/CompositePackageDescr.java b/drools-compiler/src/main/java/org/drools/compiler/lang/descr/CompositePackageDescr.java index b2dea3996a0..e83f9dfb0ba 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/lang/descr/CompositePackageDescr.java +++ b/drools-compiler/src/main/java/org/drools/compiler/lang/descr/CompositePackageDescr.java @@ -1,11 +1,15 @@ package org.drools.compiler.lang.descr; +import org.drools.compiler.compiler.PackageBuilder; import org.kie.api.io.Resource; +import java.util.ArrayList; import java.util.List; import java.util.Set; public class CompositePackageDescr extends PackageDescr { + + private CompositeAssetFilter filter; public CompositePackageDescr() { } @@ -94,4 +98,32 @@ private void internalAdd(Resource resource, PackageDescr packageDescr) { } } } + + public CompositeAssetFilter getFilter() { + return filter; + } + + public void addFilter( PackageBuilder.AssetFilter f ) { + if( f != null ) { + if( filter == null ) { + this.filter = new CompositeAssetFilter(); + } + this.filter.filters.add( f ); + } + } + + public static class CompositeAssetFilter implements PackageBuilder.AssetFilter { + public List<PackageBuilder.AssetFilter> filters = new ArrayList<PackageBuilder.AssetFilter>(); + + @Override + public Action accept(String pkgName, String assetName) { + for( PackageBuilder.AssetFilter filter : filters ) { + Action result = filter.accept(pkgName, assetName); + if( !Action.DO_NOTHING.equals( result ) ) { + return result; + } + } + return Action.DO_NOTHING; + } + } } 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 37fd9fde563..3c3c26d7344 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,14 +1,24 @@ package org.drools.compiler.integrationtests; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + import org.drools.compiler.CommonTestMethodBase; import org.drools.compiler.Message; -import org.junit.Ignore; +import org.drools.compiler.kie.builder.impl.KieContainerImpl; +import org.drools.core.RuleBase; +import org.drools.core.common.InternalRuleBase; +import org.drools.core.impl.KnowledgeBaseImpl; +import org.drools.core.reteoo.RuleTerminalNode; +import org.kie.api.definition.rule.Rule; import org.junit.Test; import org.kie.api.KieServices; 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.definition.KiePackage; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.internal.builder.IncrementalResults; @@ -468,4 +478,80 @@ public void testIncrementalCompilationAddErrorThenEmptyWithoutError() throws Exc assertEquals( 0, addResults2.getAddedMessages().size() ); assertEquals( 0, addResults2.getRemovedMessages().size() ); } + + @Test + public void testRuleRemoval() throws Exception { + String drl1 = "package org.drools.compiler\n" + + "rule R1 when\n" + + " $m : Message()\n" + + "then\n" + + "end\n"; + + String drl2 = "rule R2 when\n" + + " $m : Message( message == \"Hi Universe\" )\n" + + "then\n" + + "end\n"; + + String drl3 = "rule R3 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 +drl3 ); + + // Create a session and fire rules + KieContainer kc = ks.newKieContainer(km.getReleaseId()); + KiePackage kpkg = ((KieContainerImpl) kc).getKieBase().getKiePackage( "org.drools.compiler"); + assertEquals( 3, kpkg.getRules().size() ); + Map<String, Rule> rules = rulestoMap( kpkg.getRules() ); + + + assertNotNull(((org.drools.core.definitions.rule.impl.RuleImpl) rules.get("R1"))); + assertNotNull(((org.drools.core.definitions.rule.impl.RuleImpl) rules.get("R2"))); + assertNotNull(((org.drools.core.definitions.rule.impl.RuleImpl) rules.get("R3"))); + + RuleBase rb_1 = ((InternalRuleBase) ((KnowledgeBaseImpl) kc.getKieBase()).getRuleBase()); + + RuleTerminalNode rtn1_1 = (RuleTerminalNode) ((InternalRuleBase) ((KnowledgeBaseImpl)kc.getKieBase()).getRuleBase()).getReteooBuilder().getTerminalNodes( "R1" )[0]; + RuleTerminalNode rtn2_1 = (RuleTerminalNode) ((InternalRuleBase) ((KnowledgeBaseImpl)kc.getKieBase()).getRuleBase()).getReteooBuilder().getTerminalNodes( "R2" )[0]; + RuleTerminalNode rtn3_1 = (RuleTerminalNode) ((InternalRuleBase) ((KnowledgeBaseImpl)kc.getKieBase()).getRuleBase()).getReteooBuilder().getTerminalNodes( "R3" )[0]; + + // 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 + drl3 ); + + // try to update the container to version 1.1.0 + kc.updateToVersion(releaseId2); + + InternalRuleBase rb_2 = ((InternalRuleBase) ((KnowledgeBaseImpl) kc.getKieBase()).getRuleBase()); + assertSame ( rb_1, rb_2 ); + + RuleTerminalNode rtn1_2 = (RuleTerminalNode) rb_2.getReteooBuilder().getTerminalNodes( "R1" )[0]; + RuleTerminalNode rtn3_2 = (RuleTerminalNode) rb_2.getReteooBuilder().getTerminalNodes( "R3" )[0]; + assertNull( rb_2.getReteooBuilder().getTerminalNodes( "R2" ) ); + + assertSame( rtn3_1, rtn3_2 ); + assertSame( rtn1_1, rtn1_2 ); + + kpkg = ((KieContainerImpl) kc).getKieBase().getKiePackage( "org.drools.compiler"); + assertEquals( 2, kpkg.getRules().size() ); + rules = rulestoMap( kpkg.getRules() ); + + assertNotNull( ((org.drools.core.definitions.rule.impl.RuleImpl ) rules.get( "R1" )) ); + assertNull(((org.drools.core.definitions.rule.impl.RuleImpl) rules.get("R2"))); + assertNotNull(((org.drools.core.definitions.rule.impl.RuleImpl) rules.get("R3"))); + } + + private Map<String, Rule> rulestoMap(Collection<Rule> rules) { + Map<String, Rule> ret = new HashMap<String, Rule>(); + for( Rule rule : rules ) { + ret.put( rule.getName(), rule ); + } + return ret; + } + } 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 30e239ea8f1..b03aa0d0a30 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 @@ -1,5 +1,17 @@ package org.drools.compiler.kie.util; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.drools.compiler.kie.builder.impl.InternalKieModule; import org.drools.compiler.kproject.models.KieModuleModelImpl; import org.junit.Test; import org.kie.api.KieServices; @@ -8,21 +20,13 @@ import org.kie.api.builder.model.KieModuleModel; import org.kie.api.builder.model.KieSessionModel; import org.kie.api.builder.model.KieSessionModel.KieSessionType; -import org.drools.compiler.kie.builder.impl.InternalKieModule; import org.kie.api.conf.EqualityBehaviorOption; import org.kie.api.conf.EventProcessingOption; import org.kie.api.runtime.conf.ClockTypeOption; -import org.drools.compiler.kie.util.ResourceChange.Type; - -import java.util.ArrayList; -import java.util.List; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import org.kie.internal.builder.ChangeType; +import org.kie.internal.builder.ResourceChange; +import org.kie.internal.builder.ResourceChangeSet; +import org.kie.internal.builder.ResourceChange.Type; public class ChangeSetBuilderTest { @@ -190,7 +194,37 @@ public void testModified2() { // assertThat( cs.getChanges().get( 1 ), is( new ResourceChange(ChangeType.REMOVED, Type.RULE, "A removed rule") ) ); // assertThat( cs.getChanges().get( 2 ), is( new ResourceChange(ChangeType.UPDATED, Type.RULE, "An updated rule") ) ); } + + @Test + public void testRuleRemoval() throws Exception { + String drl1 = "package org.drools.compiler\n" + + "rule R1 when\n" + + " $m : Message()\n" + + "then\n" + + "end\n"; + + String drl2 = "rule R2 when\n" + + " $m : Message( message == \"Hi Universe\" )\n" + + "then\n" + + "end\n"; + + String drl3 = "rule R3 when\n" + + " $m : Message( message == \"Hello World\" )\n" + + "then\n" + + "end\n"; + + InternalKieModule kieJar1 = createKieJar( drl1 + drl2 + drl3 ); + InternalKieModule kieJar2 = createKieJar( drl1 + drl3 ); + ChangeSetBuilder builder = new ChangeSetBuilder(); + KieJarChangeSet changes = builder.build( kieJar1, kieJar2 ); + assertEquals( 1, changes.getChanges().size() ); + + ResourceChangeSet rcs = changes.getChanges().values().iterator().next(); + assertEquals( 1, rcs.getChanges().size() ); + assertEquals( ChangeType.REMOVED, rcs.getChanges().get(0).getChangeType() ); + } + private InternalKieModule createKieJar( String... drls) { InternalKieModule kieJar = mock( InternalKieModule.class ); KieServices ks = KieServices.Factory.get(); diff --git a/knowledge-api-legacy5-adapter/src/main/java/org/drools/impl/adapters/CompositeKnowledgeBuilderAdapter.java b/knowledge-api-legacy5-adapter/src/main/java/org/drools/impl/adapters/CompositeKnowledgeBuilderAdapter.java index 3c6f60d841f..245504d41d5 100644 --- a/knowledge-api-legacy5-adapter/src/main/java/org/drools/impl/adapters/CompositeKnowledgeBuilderAdapter.java +++ b/knowledge-api-legacy5-adapter/src/main/java/org/drools/impl/adapters/CompositeKnowledgeBuilderAdapter.java @@ -29,7 +29,7 @@ public org.drools.builder.CompositeKnowledgeBuilder add(Resource resource, Resou } public org.drools.builder.CompositeKnowledgeBuilder add(Resource resource, ResourceType type, ResourceConfiguration configuration) { - delegate.add(((ResourceAdapter)resource).getDelegate(), type.toKieResourceType(), null); + delegate.add(((ResourceAdapter)resource).getDelegate(), type.toKieResourceType(), (org.kie.api.io.ResourceConfiguration) null); return this; }
59673312da6263719881b427abca92e010b693d5
eclipsesource$tabris
Improves Test Stability Makes the tabris tests independent of the RAP test fixture to be more stable for future changes. It adds junit rule called TabrisEnvironment which encapsulates the whole tabris setup. It also allows the dispatching of operations on remote objects. Besides this a MessageUtil was added to make the verification if a message was send to the cleint or not easier. Change-Id: Ife0d372971a8d00160fc07ad40587fb2401b7914
p
https://github.com/eclipsesource/tabris
diff --git a/com.eclipsesource.tabris.build/pom.xml b/com.eclipsesource.tabris.build/pom.xml index 8c2ed6e..7c93b5f 100644 --- a/com.eclipsesource.tabris.build/pom.xml +++ b/com.eclipsesource.tabris.build/pom.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<!-- Copyright (C) 2011, EclipseSource and others All rights reserved. This +<!-- Copyright (C) 2011,2014 EclipseSource and others All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html --> @@ -58,6 +58,7 @@ <module>../com.eclipsesource.tabris.tracking</module> <module>../com.eclipsesource.tabris.passepartout</module> <!-- Tests --> + <module>../com.eclipsesource.tabris.test.util</module> <module>../com.eclipsesource.tabris.test</module> <module>../com.eclipsesource.tabris.tracking.test</module> <module>../com.eclipsesource.tabris.passepartout.test</module> diff --git a/com.eclipsesource.tabris.test.util/.classpath b/com.eclipsesource.tabris.test.util/.classpath new file mode 100644 index 0000000..ad32c83 --- /dev/null +++ b/com.eclipsesource.tabris.test.util/.classpath @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/> + <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> + <classpathentry kind="src" path="src"/> + <classpathentry kind="output" path="bin"/> +</classpath> diff --git a/com.eclipsesource.tabris.test.util/.project b/com.eclipsesource.tabris.test.util/.project new file mode 100644 index 0000000..6e2854e --- /dev/null +++ b/com.eclipsesource.tabris.test.util/.project @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>com.eclipsesource.tabris.test.util</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.jdt.core.javabuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.ManifestBuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.SchemaBuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.pde.PluginNature</nature> + <nature>org.eclipse.jdt.core.javanature</nature> + </natures> +</projectDescription> diff --git a/com.eclipsesource.tabris.test.util/.settings/org.eclipse.core.resources.prefs b/com.eclipsesource.tabris.test.util/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..99f26c0 --- /dev/null +++ b/com.eclipsesource.tabris.test.util/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +encoding/<project>=UTF-8 diff --git a/com.eclipsesource.tabris.test.util/.settings/org.eclipse.jdt.core.prefs b/com.eclipsesource.tabris.test.util/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..8891217 --- /dev/null +++ b/com.eclipsesource.tabris.test.util/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,366 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.doc.comment.support=enabled +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.autoboxing=error +org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning +org.eclipse.jdt.core.compiler.problem.deadCode=warning +org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=warning +org.eclipse.jdt.core.compiler.problem.emptyStatement=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning +org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled +org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore +org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=error +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore +org.eclipse.jdt.core.compiler.problem.invalidJavadoc=warning +org.eclipse.jdt.core.compiler.problem.invalidJavadocTags=enabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=disabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=disabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=public +org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public +org.eclipse.jdt.core.compiler.problem.missingJavadocTagDescription=return_tag +org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsMethodTypeParameters=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=public +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore +org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore +org.eclipse.jdt.core.compiler.problem.nullReference=warning +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.parameterAssignment=warning +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning +org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore +org.eclipse.jdt.core.compiler.problem.rawTypeReference=ignore +org.eclipse.jdt.core.compiler.problem.redundantNullCheck=warning +org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore +org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore +org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.compiler.problem.unusedImport=warning +org.eclipse.jdt.core.compiler.problem.unusedLabel=warning +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.source=1.6 +org.eclipse.jdt.core.formatter.align_type_members_on_columns=false +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=82 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=82 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=82 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=82 +org.eclipse.jdt.core.formatter.alignment_for_assignment=0 +org.eclipse.jdt.core.formatter.alignment_for_binary_expression=50 +org.eclipse.jdt.core.formatter.alignment_for_compact_if=52 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=51 +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=52 +org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=82 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=82 +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=84 +org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=36 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=36 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=36 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=36 +org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_after_package=1 +org.eclipse.jdt.core.formatter.blank_lines_before_field=0 +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=1 +org.eclipse.jdt.core.formatter.blank_lines_before_imports=0 +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=0 +org.eclipse.jdt.core.formatter.blank_lines_before_method=1 +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=0 +org.eclipse.jdt.core.formatter.blank_lines_before_package=0 +org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 +org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=next_line_on_wrap +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block=next_line_on_wrap +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=next_line_on_wrap +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=next_line_on_wrap +org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=next_line_on_wrap +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=true +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=true +org.eclipse.jdt.core.formatter.comment.format_block_comments=true +org.eclipse.jdt.core.formatter.comment.format_header=true +org.eclipse.jdt.core.formatter.comment.format_html=true +org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true +org.eclipse.jdt.core.formatter.comment.format_line_comments=true +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true +org.eclipse.jdt.core.formatter.comment.indent_root_tags=true +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=do not insert +org.eclipse.jdt.core.formatter.comment.line_length=80 +org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true +org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true +org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=2 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off +org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=false +org.eclipse.jdt.core.formatter.indent_empty_lines=false +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true +org.eclipse.jdt.core.formatter.indentation.size=2 +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.join_lines_in_comments=true +org.eclipse.jdt.core.formatter.join_wrapped_lines=true +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.formatter.lineSplit=100 +org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=0 +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=false +org.eclipse.jdt.core.formatter.tabulation.char=space +org.eclipse.jdt.core.formatter.tabulation.size=2 +org.eclipse.jdt.core.formatter.use_on_off_tags=false +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true diff --git a/com.eclipsesource.tabris.test.util/.settings/org.eclipse.jdt.ui.prefs b/com.eclipsesource.tabris.test.util/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 0000000..c7bfd71 --- /dev/null +++ b/com.eclipsesource.tabris.test.util/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,10 @@ +#Mon Sep 19 22:12:05 CEST 2011 +eclipse.preferences.version=1 +formatter_profile=_RAP +formatter_settings_version=12 +org.eclipse.jdt.ui.ignorelowercasenames=true +org.eclipse.jdt.ui.importorder=java;javax;org;com; +org.eclipse.jdt.ui.javadoc=false +org.eclipse.jdt.ui.ondemandthreshold=99 +org.eclipse.jdt.ui.staticondemandthreshold=99 +org.eclipse.jdt.ui.text.custom_code_templates=<?xml version\="1.0" encoding\="UTF-8" standalone\="no"?><templates><template autoinsert\="true" context\="gettercomment_context" deleted\="false" description\="Comment for getter method" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.gettercomment" name\="gettercomment"/><template autoinsert\="true" context\="settercomment_context" deleted\="false" description\="Comment for setter method" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.settercomment" name\="settercomment"/><template autoinsert\="true" context\="constructorcomment_context" deleted\="false" description\="Comment for created constructors" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.constructorcomment" name\="constructorcomment"/><template autoinsert\="true" context\="filecomment_context" deleted\="false" description\="Comment for created Java files" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.filecomment" name\="filecomment">/**\n * \n */</template><template autoinsert\="true" context\="typecomment_context" deleted\="false" description\="Comment for created types" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.typecomment" name\="typecomment">/**\n * @author ${user} */</template><template autoinsert\="true" context\="fieldcomment_context" deleted\="false" description\="Comment for fields" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.fieldcomment" name\="fieldcomment"/><template autoinsert\="true" context\="methodcomment_context" deleted\="false" description\="Comment for non-overriding methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.methodcomment" name\="methodcomment"/><template autoinsert\="true" context\="overridecomment_context" deleted\="false" description\="Comment for overriding methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.overridecomment" name\="overridecomment"/><template autoinsert\="true" context\="delegatecomment_context" deleted\="false" description\="Comment for delegate methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.delegatecomment" name\="delegatecomment">/**\n * ${tags}\n * ${see_to_target}\n */</template><template autoinsert\="false" context\="newtype_context" deleted\="false" description\="Newly created files" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.newtype" name\="newtype">/*******************************************************************************\n * Copyright (c) ${year} EclipseSource and others.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http\://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors\:\n * EclipseSource - initial API and implementation\n ******************************************************************************/\n${package_declaration}\n\n${typecomment}\n${type_declaration}</template><template autoinsert\="true" context\="classbody_context" deleted\="false" description\="Code in new class type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.classbody" name\="classbody">\n</template><template autoinsert\="true" context\="interfacebody_context" deleted\="false" description\="Code in new interface type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.interfacebody" name\="interfacebody">\n</template><template autoinsert\="true" context\="enumbody_context" deleted\="false" description\="Code in new enum type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.enumbody" name\="enumbody">\n</template><template autoinsert\="true" context\="annotationbody_context" deleted\="false" description\="Code in new annotation type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.annotationbody" name\="annotationbody">\n</template><template autoinsert\="true" context\="catchblock_context" deleted\="false" description\="Code in new catch blocks" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.catchblock" name\="catchblock">// ${todo} Auto-generated catch block\n${exception_var}.printStackTrace();</template><template autoinsert\="true" context\="methodbody_context" deleted\="false" description\="Code in created method stubs" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.methodbody" name\="methodbody">${body_statement}</template><template autoinsert\="true" context\="constructorbody_context" deleted\="false" description\="Code in created constructor stubs" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.constructorbody" name\="constructorbody">${body_statement}</template><template autoinsert\="true" context\="getterbody_context" deleted\="false" description\="Code in created getters" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.getterbody" name\="getterbody">return ${field};</template><template autoinsert\="true" context\="setterbody_context" deleted\="false" description\="Code in created setters" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.setterbody" name\="setterbody">${field} \= ${param};</template></templates> diff --git a/com.eclipsesource.tabris.test.util/.settings/org.eclipse.pde.core.prefs b/com.eclipsesource.tabris.test.util/.settings/org.eclipse.pde.core.prefs new file mode 100644 index 0000000..e8ff8be --- /dev/null +++ b/com.eclipsesource.tabris.test.util/.settings/org.eclipse.pde.core.prefs @@ -0,0 +1,4 @@ +eclipse.preferences.version=1 +pluginProject.equinox=false +pluginProject.extensions=false +resolve.requirebundle=false diff --git a/com.eclipsesource.tabris.test.util/.settings/org.eclipse.pde.prefs b/com.eclipsesource.tabris.test.util/.settings/org.eclipse.pde.prefs new file mode 100644 index 0000000..0bc2d73 --- /dev/null +++ b/com.eclipsesource.tabris.test.util/.settings/org.eclipse.pde.prefs @@ -0,0 +1,32 @@ +compilers.f.unresolved-features=1 +compilers.f.unresolved-plugins=1 +compilers.incompatible-environment=1 +compilers.p.build=1 +compilers.p.build.bin.includes=1 +compilers.p.build.encodings=2 +compilers.p.build.java.compiler=2 +compilers.p.build.java.compliance=1 +compilers.p.build.missing.output=2 +compilers.p.build.output.library=1 +compilers.p.build.source.library=1 +compilers.p.build.src.includes=1 +compilers.p.deprecated=1 +compilers.p.discouraged-class=1 +compilers.p.internal=1 +compilers.p.missing-packages=2 +compilers.p.missing-version-export-package=2 +compilers.p.missing-version-import-package=2 +compilers.p.missing-version-require-bundle=1 +compilers.p.no-required-att=0 +compilers.p.not-externalized-att=2 +compilers.p.unknown-attribute=1 +compilers.p.unknown-class=1 +compilers.p.unknown-element=1 +compilers.p.unknown-identifier=1 +compilers.p.unknown-resource=1 +compilers.p.unresolved-ex-points=0 +compilers.p.unresolved-import=0 +compilers.s.create-docs=false +compilers.s.doc-folder=doc +compilers.s.open-tags=1 +eclipse.preferences.version=1 diff --git a/com.eclipsesource.tabris.test.util/META-INF/MANIFEST.MF b/com.eclipsesource.tabris.test.util/META-INF/MANIFEST.MF new file mode 100644 index 0000000..e848efe --- /dev/null +++ b/com.eclipsesource.tabris.test.util/META-INF/MANIFEST.MF @@ -0,0 +1,15 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Tabris Test Util +Bundle-SymbolicName: com.eclipsesource.tabris.test.util +Bundle-Version: 1.4.0.qualifier +Bundle-Vendor: EclipseSource +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Require-Bundle: org.junit;bundle-version="[4.10.0,5.0.0)", + org.mockito.mockito-all;bundle-version="1.9.5", + org.eclipse.rap.rwt.testfixture;bundle-version="2.3.0", + org.eclipse.rap.rwt;bundle-version="2.3.0", + com.eclipsesource.tabris;bundle-version="1.4.0" +Export-Package: com.eclipsesource.tabris.test.util;version="1.4.0" +Import-Package: javax.servlet;version="[2.3.0,4.0.0)", + javax.servlet.http;version="[2.3.0,4.0.0)" diff --git a/com.eclipsesource.tabris.test.util/build.properties b/com.eclipsesource.tabris.test.util/build.properties new file mode 100644 index 0000000..018bdbd --- /dev/null +++ b/com.eclipsesource.tabris.test.util/build.properties @@ -0,0 +1,5 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + epl-v10.html diff --git a/com.eclipsesource.tabris.test.util/epl-v10.html b/com.eclipsesource.tabris.test.util/epl-v10.html new file mode 100644 index 0000000..3998fce --- /dev/null +++ b/com.eclipsesource.tabris.test.util/epl-v10.html @@ -0,0 +1,261 @@ +<?xml version="1.0" encoding="ISO-8859-1" ?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> + +<head> +<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> +<title>Eclipse Public License - Version 1.0</title> +<style type="text/css"> + body { + size: 8.5in 11.0in; + margin: 0.25in 0.5in 0.25in 0.5in; + tab-interval: 0.5in; + } + p { + margin-left: auto; + margin-top: 0.5em; + margin-bottom: 0.5em; + } + p.list { + margin-left: 0.5in; + margin-top: 0.05em; + margin-bottom: 0.05em; + } + </style> + +</head> + +<body lang="EN-US"> + +<h2>Eclipse Public License - v 1.0</h2> + +<p>THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE +PUBLIC LICENSE (&quot;AGREEMENT&quot;). ANY USE, REPRODUCTION OR +DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS +AGREEMENT.</p> + +<p><b>1. DEFINITIONS</b></p> + +<p>&quot;Contribution&quot; means:</p> + +<p class="list">a) in the case of the initial Contributor, the initial +code and documentation distributed under this Agreement, and</p> +<p class="list">b) in the case of each subsequent Contributor:</p> +<p class="list">i) changes to the Program, and</p> +<p class="list">ii) additions to the Program;</p> +<p class="list">where such changes and/or additions to the Program +originate from and are distributed by that particular Contributor. A +Contribution 'originates' from a Contributor if it was added to the +Program by such Contributor itself or anyone acting on such +Contributor's behalf. Contributions do not include additions to the +Program which: (i) are separate modules of software distributed in +conjunction with the Program under their own license agreement, and (ii) +are not derivative works of the Program.</p> + +<p>&quot;Contributor&quot; means any person or entity that distributes +the Program.</p> + +<p>&quot;Licensed Patents&quot; mean patent claims licensable by a +Contributor which are necessarily infringed by the use or sale of its +Contribution alone or when combined with the Program.</p> + +<p>&quot;Program&quot; means the Contributions distributed in accordance +with this Agreement.</p> + +<p>&quot;Recipient&quot; means anyone who receives the Program under +this Agreement, including all Contributors.</p> + +<p><b>2. GRANT OF RIGHTS</b></p> + +<p class="list">a) Subject to the terms of this Agreement, each +Contributor hereby grants Recipient a non-exclusive, worldwide, +royalty-free copyright license to reproduce, prepare derivative works +of, publicly display, publicly perform, distribute and sublicense the +Contribution of such Contributor, if any, and such derivative works, in +source code and object code form.</p> + +<p class="list">b) Subject to the terms of this Agreement, each +Contributor hereby grants Recipient a non-exclusive, worldwide, +royalty-free patent license under Licensed Patents to make, use, sell, +offer to sell, import and otherwise transfer the Contribution of such +Contributor, if any, in source code and object code form. This patent +license shall apply to the combination of the Contribution and the +Program if, at the time the Contribution is added by the Contributor, +such addition of the Contribution causes such combination to be covered +by the Licensed Patents. The patent license shall not apply to any other +combinations which include the Contribution. No hardware per se is +licensed hereunder.</p> + +<p class="list">c) Recipient understands that although each Contributor +grants the licenses to its Contributions set forth herein, no assurances +are provided by any Contributor that the Program does not infringe the +patent or other intellectual property rights of any other entity. Each +Contributor disclaims any liability to Recipient for claims brought by +any other entity based on infringement of intellectual property rights +or otherwise. As a condition to exercising the rights and licenses +granted hereunder, each Recipient hereby assumes sole responsibility to +secure any other intellectual property rights needed, if any. For +example, if a third party patent license is required to allow Recipient +to distribute the Program, it is Recipient's responsibility to acquire +that license before distributing the Program.</p> + +<p class="list">d) Each Contributor represents that to its knowledge it +has sufficient copyright rights in its Contribution, if any, to grant +the copyright license set forth in this Agreement.</p> + +<p><b>3. REQUIREMENTS</b></p> + +<p>A Contributor may choose to distribute the Program in object code +form under its own license agreement, provided that:</p> + +<p class="list">a) it complies with the terms and conditions of this +Agreement; and</p> + +<p class="list">b) its license agreement:</p> + +<p class="list">i) effectively disclaims on behalf of all Contributors +all warranties and conditions, express and implied, including warranties +or conditions of title and non-infringement, and implied warranties or +conditions of merchantability and fitness for a particular purpose;</p> + +<p class="list">ii) effectively excludes on behalf of all Contributors +all liability for damages, including direct, indirect, special, +incidental and consequential damages, such as lost profits;</p> + +<p class="list">iii) states that any provisions which differ from this +Agreement are offered by that Contributor alone and not by any other +party; and</p> + +<p class="list">iv) states that source code for the Program is available +from such Contributor, and informs licensees how to obtain it in a +reasonable manner on or through a medium customarily used for software +exchange.</p> + +<p>When the Program is made available in source code form:</p> + +<p class="list">a) it must be made available under this Agreement; and</p> + +<p class="list">b) a copy of this Agreement must be included with each +copy of the Program.</p> + +<p>Contributors may not remove or alter any copyright notices contained +within the Program.</p> + +<p>Each Contributor must identify itself as the originator of its +Contribution, if any, in a manner that reasonably allows subsequent +Recipients to identify the originator of the Contribution.</p> + +<p><b>4. COMMERCIAL DISTRIBUTION</b></p> + +<p>Commercial distributors of software may accept certain +responsibilities with respect to end users, business partners and the +like. While this license is intended to facilitate the commercial use of +the Program, the Contributor who includes the Program in a commercial +product offering should do so in a manner which does not create +potential liability for other Contributors. Therefore, if a Contributor +includes the Program in a commercial product offering, such Contributor +(&quot;Commercial Contributor&quot;) hereby agrees to defend and +indemnify every other Contributor (&quot;Indemnified Contributor&quot;) +against any losses, damages and costs (collectively &quot;Losses&quot;) +arising from claims, lawsuits and other legal actions brought by a third +party against the Indemnified Contributor to the extent caused by the +acts or omissions of such Commercial Contributor in connection with its +distribution of the Program in a commercial product offering. The +obligations in this section do not apply to any claims or Losses +relating to any actual or alleged intellectual property infringement. In +order to qualify, an Indemnified Contributor must: a) promptly notify +the Commercial Contributor in writing of such claim, and b) allow the +Commercial Contributor to control, and cooperate with the Commercial +Contributor in, the defense and any related settlement negotiations. The +Indemnified Contributor may participate in any such claim at its own +expense.</p> + +<p>For example, a Contributor might include the Program in a commercial +product offering, Product X. That Contributor is then a Commercial +Contributor. If that Commercial Contributor then makes performance +claims, or offers warranties related to Product X, those performance +claims and warranties are such Commercial Contributor's responsibility +alone. Under this section, the Commercial Contributor would have to +defend claims against the other Contributors related to those +performance claims and warranties, and if a court requires any other +Contributor to pay any damages as a result, the Commercial Contributor +must pay those damages.</p> + +<p><b>5. NO WARRANTY</b></p> + +<p>EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS +PROVIDED ON AN &quot;AS IS&quot; BASIS, WITHOUT WARRANTIES OR CONDITIONS +OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, +ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY +OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely +responsible for determining the appropriateness of using and +distributing the Program and assumes all risks associated with its +exercise of rights under this Agreement , including but not limited to +the risks and costs of program errors, compliance with applicable laws, +damage to or loss of data, programs or equipment, and unavailability or +interruption of operations.</p> + +<p><b>6. DISCLAIMER OF LIABILITY</b></p> + +<p>EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT +NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING +WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR +DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED +HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.</p> + +<p><b>7. GENERAL</b></p> + +<p>If any provision of this Agreement is invalid or unenforceable under +applicable law, it shall not affect the validity or enforceability of +the remainder of the terms of this Agreement, and without further action +by the parties hereto, such provision shall be reformed to the minimum +extent necessary to make such provision valid and enforceable.</p> + +<p>If Recipient institutes patent litigation against any entity +(including a cross-claim or counterclaim in a lawsuit) alleging that the +Program itself (excluding combinations of the Program with other +software or hardware) infringes such Recipient's patent(s), then such +Recipient's rights granted under Section 2(b) shall terminate as of the +date such litigation is filed.</p> + +<p>All Recipient's rights under this Agreement shall terminate if it +fails to comply with any of the material terms or conditions of this +Agreement and does not cure such failure in a reasonable period of time +after becoming aware of such noncompliance. If all Recipient's rights +under this Agreement terminate, Recipient agrees to cease use and +distribution of the Program as soon as reasonably practicable. However, +Recipient's obligations under this Agreement and any licenses granted by +Recipient relating to the Program shall continue and survive.</p> + +<p>Everyone is permitted to copy and distribute copies of this +Agreement, but in order to avoid inconsistency the Agreement is +copyrighted and may only be modified in the following manner. The +Agreement Steward reserves the right to publish new versions (including +revisions) of this Agreement from time to time. No one other than the +Agreement Steward has the right to modify this Agreement. The Eclipse +Foundation is the initial Agreement Steward. The Eclipse Foundation may +assign the responsibility to serve as the Agreement Steward to a +suitable separate entity. Each new version of the Agreement will be +given a distinguishing version number. The Program (including +Contributions) may always be distributed subject to the version of the +Agreement under which it was received. In addition, after a new version +of the Agreement is published, Contributor may elect to distribute the +Program (including its Contributions) under the new version. Except as +expressly stated in Sections 2(a) and 2(b) above, Recipient receives no +rights or licenses to the intellectual property of any Contributor under +this Agreement, whether expressly, by implication, estoppel or +otherwise. All rights in the Program not expressly granted under this +Agreement are reserved.</p> + +<p>This Agreement is governed by the laws of the State of New York and +the intellectual property laws of the United States of America. No party +to this Agreement will bring a legal action under this Agreement more +than one year after the cause of action arose. Each party waives its +rights to a jury trial in any resulting litigation.</p> + +</body> + +</html> \ No newline at end of file diff --git a/com.eclipsesource.tabris.test.util/pom.xml b/com.eclipsesource.tabris.test.util/pom.xml new file mode 100644 index 0000000..06afd43 --- /dev/null +++ b/com.eclipsesource.tabris.test.util/pom.xml @@ -0,0 +1,81 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- Copyright (C) 2014, EclipseSource and others All rights reserved. This + program and the accompanying materials are made available under the terms + of the Eclipse Public License v1.0 which accompanies this distribution, and + is available at http://www.eclipse.org/legal/epl-v10.html --> + +<project + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <artifactId>tabris-parent</artifactId> + <groupId>com.eclipsesource</groupId> + <version>1.0.0-SNAPSHOT</version> + <relativePath>../com.eclipsesource.tabris.build</relativePath> + </parent> + + <groupId>com.eclipsesource</groupId> + <artifactId>com.eclipsesource.tabris.test.util</artifactId> + <version>1.4.0-SNAPSHOT</version> + <packaging>eclipse-plugin</packaging> + + <build> + <plugins> + <plugin> + <groupId>${tycho-groupid}</groupId> + <artifactId>target-platform-configuration</artifactId> + <version>${tycho-version}</version> + <configuration> + <filters> + <filter> + <type>java-package</type> + <id>javax.servlet</id> + <restrictTo> + <type>osgi-bundle</type> + <id>javax.servlet</id> + <versionRange>[2.3.0,4.0.0)</versionRange> + </restrictTo> + </filter> + </filters> + </configuration> + </plugin> + </plugins> + </build> + + <profiles> + <profile> + <id>findbugs</id> + <activation> + <activeByDefault>false</activeByDefault> + <property> + <name>fullBuild</name> + <value>true</value> + </property> + </activation> + <build> + <plugins> + <!-- Configure FindBugs --> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>findbugs-maven-plugin</artifactId> + <version>${findbugs-version}</version> + <configuration> + <findbugsXmlOutput>true</findbugsXmlOutput> + <failOnError>false</failOnError> + </configuration> + <executions> + <execution> + <goals> + <goal>check</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + </build> + </profile> + </profiles> + +</project> diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/test/ControlLCATestUtil.java b/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/ControlLCATestUtil.java similarity index 99% rename from com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/test/ControlLCATestUtil.java rename to com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/ControlLCATestUtil.java index 310f729..982c453 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/test/ControlLCATestUtil.java +++ b/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/ControlLCATestUtil.java @@ -8,7 +8,7 @@ * Contributors: * EclipseSource - initial API and implementation ******************************************************************************/ -package com.eclipsesource.tabris.test; +package com.eclipsesource.tabris.test.util; import static org.eclipse.rap.rwt.internal.lifecycle.WidgetUtil.getLCA; import static org.junit.Assert.assertFalse; diff --git a/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/MessageUtil.java b/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/MessageUtil.java new file mode 100644 index 0000000..14746f6 --- /dev/null +++ b/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/MessageUtil.java @@ -0,0 +1,162 @@ +/******************************************************************************* + * Copyright (c) 2014 EclipseSource and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * EclipseSource - initial API and implementation + ******************************************************************************/ +package com.eclipsesource.tabris.test.util; + +import java.util.List; + +import org.eclipse.rap.json.JsonObject; +import org.eclipse.rap.rwt.testfixture.Fixture; +import org.eclipse.rap.rwt.testfixture.Message; +import org.eclipse.rap.rwt.testfixture.Message.CallOperation; +import org.eclipse.rap.rwt.testfixture.Message.CreateOperation; +import org.eclipse.rap.rwt.testfixture.Message.ListenOperation; +import org.eclipse.rap.rwt.testfixture.Message.Operation; +import org.eclipse.rap.rwt.testfixture.Message.SetOperation; + + +public class MessageUtil { + + public static enum OperationType { + CREATE, SET, CALL, LISTEN + } + + public static boolean hasCreateOperation( String type ) { + boolean found = false; + Message protocolMessage = Fixture.getProtocolMessage(); + int operationCount = protocolMessage.getOperationCount(); + for( int i = 0; i < operationCount; i++ ) { + Operation operation = protocolMessage.getOperation( i ); + if( operation instanceof CreateOperation ) { + CreateOperation create = ( CreateOperation )operation; + if( create.getType().equals( type ) ) { + found = true; + } + } + } + return found; + } + + public static boolean isParentOfCreate( String type, String parentId ) { + boolean found = false; + Message protocolMessage = Fixture.getProtocolMessage(); + int operationCount = protocolMessage.getOperationCount(); + for( int i = 0; i < operationCount; i++ ) { + Operation operation = protocolMessage.getOperation( i ); + if( operation instanceof CreateOperation ) { + CreateOperation create = ( CreateOperation )operation; + if( create.getType().equals( type ) && create.getParent().equals( parentId ) ) { + found = true; + } + } + } + return found; + } + + public static JsonObject getHead() { + return Fixture.getProtocolMessage().getHead(); + } + + public static boolean hasOperation( String target, OperationType type, String operationName ) { + Message message = Fixture.getProtocolMessage(); + if( type == OperationType.CREATE ) { + CreateOperation operation = message.findCreateOperation( target ); + if( operation != null ) { + return true; + } + } else if( type == OperationType.CALL ) { + CallOperation operation = message.findCallOperation( target, operationName ); + if( operation != null ) { + return true; + } + } else if( type == OperationType.SET ) { + SetOperation operation = findSetOperation( message, target ); + if( operation != null ) { + return true; + } + } else if( type == OperationType.LISTEN ) { + ListenOperation operation = findListenOperation( message, target ); + if( operation != null ) { + return true; + } + } + return false; + } + + public static JsonObject getOperationProperties( String target, OperationType type, String operationName ) { + Message message = Fixture.getProtocolMessage(); + if( type == OperationType.CREATE ) { + CreateOperation operation = message.findCreateOperation( target ); + if( operation != null ) { + return createProperties( operation ); + } + } else if( type == OperationType.CALL ) { + CallOperation operation = message.findCallOperation( target, operationName ); + if( operation != null ) { + return createProperties( operation ); + } + } else if( type == OperationType.SET ) { + SetOperation operation = findSetOperation( message, target ); + if( operation != null ) { + return createProperties( operation ); + } + } else if( type == OperationType.LISTEN ) { + ListenOperation operation = findListenOperation( message, target ); + if( operation != null ) { + return createProperties( operation ); + } + } + return new JsonObject(); + } + + private static SetOperation findSetOperation( Message message, String target ) { + Message protocolMessage = Fixture.getProtocolMessage(); + int operationCount = protocolMessage.getOperationCount(); + for( int i = 0; i < operationCount; i++ ) { + Operation operation = protocolMessage.getOperation( i ); + if( operation instanceof SetOperation ) { + SetOperation set = ( SetOperation )operation; + if( set.getTarget().equals( target ) ) { + return set; + } + } + } + return null; + } + + private static ListenOperation findListenOperation( Message message, String target ) { + Message protocolMessage = Fixture.getProtocolMessage(); + int operationCount = protocolMessage.getOperationCount(); + for( int i = 0; i < operationCount; i++ ) { + Operation operation = protocolMessage.getOperation( i ); + if( operation instanceof ListenOperation ) { + ListenOperation listen = ( ListenOperation )operation; + if( listen.getTarget().equals( target ) ) { + return listen; + } + } + } + return null; + } + + private static JsonObject createProperties( Operation operation ) { + JsonObject result = new JsonObject(); + List<String> propertyNames = operation.getPropertyNames(); + for( String name : propertyNames ) { + result.add( name, operation.getProperty( name ) ); + } + return result; + } + + private MessageUtil() { + // prevent instantiation + } + +} diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/test/RWTEnvironment.java b/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/TabrisEnvironment.java similarity index 69% rename from com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/test/RWTEnvironment.java rename to com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/TabrisEnvironment.java index 96fb2e1..8d06499 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/test/RWTEnvironment.java +++ b/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/TabrisEnvironment.java @@ -1,3 +1,4 @@ +package com.eclipsesource.tabris.test.util; /******************************************************************************* * Copyright (c) 2014 EclipseSource and others. * All rights reserved. This program and the accompanying materials @@ -8,24 +9,31 @@ * Contributors: * EclipseSource - initial API and implementation ******************************************************************************/ -package com.eclipsesource.tabris.test; + + +import static org.mockito.Mockito.mock; import org.eclipse.rap.json.JsonObject; import org.eclipse.rap.rwt.RWT; +import org.eclipse.rap.rwt.client.Client; import org.eclipse.rap.rwt.internal.remote.ConnectionImpl; +import org.eclipse.rap.rwt.internal.service.ContextProvider; import org.eclipse.rap.rwt.lifecycle.PhaseId; import org.eclipse.rap.rwt.remote.Connection; import org.eclipse.rap.rwt.remote.RemoteObject; import org.eclipse.rap.rwt.testfixture.Fixture; +import org.eclipse.rap.rwt.testfixture.TestRequest; +import org.eclipse.rap.rwt.testfixture.internal.engine.ThemeManagerHelper; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; -import com.eclipsesource.tabris.test.TabrisTestUtil.TestRemoteObject; +import com.eclipsesource.tabris.TabrisClient; +import com.eclipsesource.tabris.test.util.internal.RemoteObjectHelper; @SuppressWarnings( { "restriction", "deprecation" } ) -public class RWTEnvironment implements TestRule { +public class TabrisEnvironment implements TestRule { @Override public Statement apply( final Statement base, Description description ) { @@ -37,12 +45,15 @@ public void evaluate() throws Throwable { Fixture.setSkipResourceRegistration( true ); Fixture.setUp(); Fixture.fakePhase( PhaseId.PROCESS_ACTION ); - TabrisTestUtil.mockRemoteObject(); + Fixture.fakeClient( mock( TabrisClient.class ) ); + RemoteObjectHelper.mockRemoteObject(); base.evaluate(); } catch( Throwable shouldNotHappen ) { throw shouldNotHappen; } finally { - Fixture.tearDown(); + if( ContextProvider.hasContext() ) { + Fixture.tearDown(); + } } } }; @@ -57,6 +68,18 @@ public RemoteObject getServiceObject() { return ( ( ConnectionImpl )connection ).createServiceObject( "foo" ); } + public TabrisRequest getRequest() { + return new TabrisRequest( ( TestRequest )RWT.getRequest() ); + } + + public void resetThemes() { + ThemeManagerHelper.resetThemeManager(); + } + + public void setClient( Client client ) { + Fixture.fakeClient( client ); + } + public void dispatchSet( JsonObject properties ) { ( ( TestRemoteObject )getRemoteObject() ).getHandler().handleSet( properties ); } @@ -81,7 +104,16 @@ public void dispatchCallOnServiceObject( String methodName, JsonObject parameter ( ( TestRemoteObject )getServiceObject() ).getHandler().handleCall( methodName, parameters ); } - public void runProcessAction() { + public TabrisRequest newRequest() { + TabrisRequest request = new TabrisRequest( Fixture.fakeNewRequest() ); + Fixture.fakePhase( PhaseId.PROCESS_ACTION ); + return request; + } + + public TabrisRequest newGetRequest() { + TabrisRequest request = new TabrisRequest( Fixture.fakeNewGetRequest() ); Fixture.fakePhase( PhaseId.PROCESS_ACTION ); + return request; } + } diff --git a/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/TabrisRequest.java b/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/TabrisRequest.java new file mode 100644 index 0000000..4f8350c --- /dev/null +++ b/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/TabrisRequest.java @@ -0,0 +1,440 @@ +/******************************************************************************* + * Copyright (c) 2014 EclipseSource and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * EclipseSource - initial API and implementation + ******************************************************************************/ +package com.eclipsesource.tabris.test.util; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.security.Principal; +import java.util.Collection; +import java.util.Enumeration; +import java.util.Locale; +import java.util.Map; + +import javax.servlet.AsyncContext; +import javax.servlet.DispatcherType; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import javax.servlet.http.Part; + +import org.eclipse.rap.rwt.testfixture.TestRequest; + + +public class TabrisRequest implements HttpServletRequest { + + private final TestRequest delegate; + + public TabrisRequest( TestRequest delegate ) { + this.delegate = delegate; + } + + @Override + public String getAuthType() { + return delegate.getAuthType(); + } + + public void addCookie( Cookie cookie ) { + delegate.addCookie( cookie ); + } + + @Override + public Cookie[] getCookies() { + return delegate.getCookies(); + } + + @Override + public long getDateHeader( String arg0 ) { + return delegate.getDateHeader( arg0 ); + } + + @Override + public String getHeader( String arg0 ) { + return delegate.getHeader( arg0 ); + } + + public void setHeader( String arg0, String arg1) { + delegate.setHeader( arg0, arg1 ); + } + + @Override + public Enumeration<String> getHeaders( String arg0 ) { + return delegate.getHeaders( arg0 ); + } + + @Override + public Enumeration<String> getHeaderNames() { + return delegate.getHeaderNames(); + } + + @Override + public int getIntHeader( String arg0 ) { + return delegate.getIntHeader( arg0 ); + } + + @Override + public String getMethod() { + return delegate.getMethod(); + } + + public void setMethod( String method ) { + delegate.setMethod( method ); + } + + @Override + public String getPathInfo() { + return delegate.getPathInfo(); + } + + public void setPathInfo( String pathInfo ) { + delegate.setPathInfo( pathInfo ); + } + + @Override + public String getPathTranslated() { + return delegate.getPathTranslated(); + } + + @Override + public String getContextPath() { + return delegate.getContextPath(); + } + + public void setContextPath( String contextPath ) { + delegate.setContextPath( contextPath ); + } + + @Override + public String getQueryString() { + return delegate.getQueryString(); + } + + @Override + public String getRemoteUser() { + return delegate.getRemoteUser(); + } + + @Override + public boolean isUserInRole( String arg0 ) { + return false; + } + + @Override + public Principal getUserPrincipal() { + return null; + } + + @Override + public String getRequestedSessionId() { + return delegate.getRequestedSessionId(); + } + + @Override + public String getRequestURI() { + return delegate.getRequestURI(); + } + + public void setRequestURI( String requestURI ) { + delegate.setRequestURI( requestURI ); + } + + @Override + public StringBuffer getRequestURL() { + return delegate.getRequestURL(); + } + + @Override + public String getServletPath() { + return delegate.getServletPath(); + } + + public void setServletPath( String servletPath ) { + delegate.setServletPath( servletPath ); + } + + @Override + public HttpSession getSession( boolean arg0 ) { + return delegate.getSession( arg0 ); + } + + @Override + public HttpSession getSession() { + return delegate.getSession(); + } + + @Override + public boolean isRequestedSessionIdValid() { + return delegate.isRequestedSessionIdValid(); + } + + @Override + public boolean isRequestedSessionIdFromCookie() { + return delegate.isRequestedSessionIdFromCookie(); + } + + @Override + public boolean isRequestedSessionIdFromURL() { + return delegate.isRequestedSessionIdFromURL(); + } + + @Override + public boolean isRequestedSessionIdFromUrl() { + return delegate.isRequestedSessionIdFromUrl(); + } + + @Override + public Object getAttribute( String arg0 ) { + return delegate.getAttribute( arg0 ); + } + + @Override + public Enumeration<String> getAttributeNames() { + return delegate.getAttributeNames(); + } + + @Override + public String getCharacterEncoding() { + return delegate.getCharacterEncoding(); + } + + @Override + public void setCharacterEncoding( String arg0 ) throws UnsupportedEncodingException { + delegate.setCharacterEncoding( arg0 ); + } + + @Override + public int getContentLength() { + return delegate.getContentLength(); + } + + @Override + public String getContentType() { + return delegate.getContentType(); + } + + public void setContentType( String contentType ) { + delegate.setContentType( contentType ); + } + + @Override + public ServletInputStream getInputStream() throws IOException { + return delegate.getInputStream(); + } + + @Override + public String getParameter( String arg0 ) { + return delegate.getParameter( arg0 ); + } + + @Override + public Enumeration<String> getParameterNames() { + return delegate.getParameterNames(); + } + + @Override + public String[] getParameterValues( String arg0 ) { + return delegate.getParameterValues( arg0 ); + } + + public void setParameter( String key, String value ) { + delegate.setParameter( key, value ); + } + + public void addParameter( String key, String value ) { + delegate.addParameter( key, value ); + } + + @Override + public Map<String,String[]> getParameterMap() { + return delegate.getParameterMap(); + } + + @Override + public String getProtocol() { + return delegate.getProtocol(); + } + + @Override + public String getScheme() { + return delegate.getScheme(); + } + + public void setScheme( String scheme ) { + delegate.setScheme( scheme ); + } + + @Override + public String getServerName() { + return delegate.getServerName(); + } + + public void setServerName( String serverName ) { + delegate.setServerName( serverName ); + } + + @Override + public int getServerPort() { + return delegate.getServerPort(); + } + + @Override + public BufferedReader getReader() throws IOException { + return delegate.getReader(); + } + + public void setBody( String body ) { + delegate.setBody( body ); + } + + public String getBody() { + return delegate.getBody(); + } + + @Override + public String getRemoteAddr() { + return delegate.getRemoteAddr(); + } + + @Override + public String getRemoteHost() { + return delegate.getRemoteHost(); + } + + @Override + public void setAttribute( String arg0, Object arg1 ) { + delegate.setAttribute( arg0, arg1 ); + } + + @Override + public void removeAttribute( String arg0 ) { + delegate.removeAttribute( arg0 ); + } + + @Override + public Locale getLocale() { + return delegate.getLocale(); + } + + @Override + public Enumeration<Locale> getLocales() { + return delegate.getLocales(); + } + + public void setLocales( Locale... locales ) { + delegate.setLocales( locales ); + } + + @Override + public boolean isSecure() { + return delegate.isSecure(); + } + + @Override + public RequestDispatcher getRequestDispatcher( String arg0 ) { + return delegate.getRequestDispatcher( arg0 ); + } + + @Override + public String getRealPath( String arg0 ) { + return delegate.getRealPath( arg0 ); + } + + public void setSession( HttpSession session ) { + delegate.setSession( session ); + } + + @Override + public String getLocalAddr() { + return delegate.getLocalAddr(); + } + + @Override + public String getLocalName() { + return delegate.getLocalName(); + } + + @Override + public int getLocalPort() { + return delegate.getLocalPort(); + } + + @Override + public int getRemotePort() { + return delegate.getRemotePort(); + } + + @Override + public ServletContext getServletContext() { + return delegate.getServletContext(); + } + + @Override + public AsyncContext startAsync() throws IllegalStateException { + return delegate.startAsync(); + } + + @Override + public AsyncContext startAsync( ServletRequest servletRequest, ServletResponse servletResponse ) throws IllegalStateException { + return delegate.startAsync( servletRequest, servletResponse ); + } + + @Override + public boolean isAsyncStarted() { + return delegate.isAsyncStarted(); + } + + @Override + public boolean isAsyncSupported() { + return delegate.isAsyncSupported(); + } + + @Override + public AsyncContext getAsyncContext() { + return delegate.getAsyncContext(); + } + + @Override + public DispatcherType getDispatcherType() { + return delegate.getDispatcherType(); + } + + @Override + public boolean authenticate( HttpServletResponse response ) throws IOException, ServletException { + return delegate.authenticate( response ); + } + + @Override + public void login( String username, String password ) throws ServletException { + delegate.login( username, password ); + } + + @Override + public void logout() throws ServletException { + delegate.logout(); + } + + @Override + public Collection<Part> getParts() throws IOException, ServletException { + return delegate.getParts(); + } + + @Override + public Part getPart( String name ) throws IOException, ServletException { + return delegate.getPart( name ); + } +} diff --git a/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/TestRemoteObject.java b/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/TestRemoteObject.java new file mode 100644 index 0000000..95690dd --- /dev/null +++ b/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/TestRemoteObject.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright (c) 2014 EclipseSource and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * EclipseSource - initial API and implementation + ******************************************************************************/ +package com.eclipsesource.tabris.test.util; + +import org.eclipse.rap.json.JsonObject; +import org.eclipse.rap.json.JsonValue; +import org.eclipse.rap.rwt.remote.OperationHandler; +import org.eclipse.rap.rwt.remote.RemoteObject; + +public class TestRemoteObject implements RemoteObject { + + private final String id; + private OperationHandler handler; + + public TestRemoteObject( String id ) { + this.id = id; + } + + @Override + public String getId() { + return id; + } + + @Override + public void set( String name, int value ) { + } + + @Override + public void set( String name, double value ) { + } + + @Override + public void set( String name, boolean value ) { + } + + @Override + public void set( String name, String value ) { + } + + @Override + public void set( String name, JsonValue value ) { + } + + @Override + public void listen( String eventType, boolean listen ) { + } + + @Override + public void call( String method, JsonObject parameters ) { + } + + @Override + public void destroy() { + } + + @Override + public void setHandler( OperationHandler handler ) { + this.handler = handler; + } + + public OperationHandler getHandler() { + return handler; + } + +} \ No newline at end of file diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/test/TabrisTestUtil.java b/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/internal/RemoteObjectHelper.java similarity index 59% rename from com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/test/TabrisTestUtil.java rename to com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/internal/RemoteObjectHelper.java index 63cb3cf..0ec1932 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/test/TabrisTestUtil.java +++ b/com.eclipsesource.tabris.test.util/src/com/eclipsesource/tabris/test/util/internal/RemoteObjectHelper.java @@ -1,3 +1,4 @@ +package com.eclipsesource.tabris.test.util.internal; /******************************************************************************* * Copyright (c) 2012 EclipseSource and others. * All rights reserved. This program and the accompanying materials @@ -8,7 +9,7 @@ * Contributors: * EclipseSource - initial API and implementation ******************************************************************************/ -package com.eclipsesource.tabris.test; + import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; @@ -17,16 +18,16 @@ import java.util.Random; -import org.eclipse.rap.json.JsonObject; -import org.eclipse.rap.json.JsonValue; import org.eclipse.rap.rwt.internal.remote.ConnectionImpl; import org.eclipse.rap.rwt.remote.OperationHandler; import org.eclipse.rap.rwt.remote.RemoteObject; import org.eclipse.rap.rwt.testfixture.Fixture; +import com.eclipsesource.tabris.test.util.TestRemoteObject; + @SuppressWarnings("restriction") -public class TabrisTestUtil { +public class RemoteObjectHelper { private static final Random random = new Random(); @@ -47,65 +48,7 @@ private static RemoteObject createRemoteObject() { return remoteObject; } - - private TabrisTestUtil() { + private RemoteObjectHelper() { // prevent instantiation } - - public static class TestRemoteObject implements RemoteObject { - - private final String id; - private OperationHandler handler; - - public TestRemoteObject( String id ) { - this.id = id; - } - - @Override - public String getId() { - return id; - } - - @Override - public void set( String name, int value ) { - } - - @Override - public void set( String name, double value ) { - } - - @Override - public void set( String name, boolean value ) { - } - - @Override - public void set( String name, String value ) { - } - - @Override - public void set( String name, JsonValue value ) { - } - - @Override - public void listen( String eventType, boolean listen ) { - } - - @Override - public void call( String method, JsonObject parameters ) { - } - - @Override - public void destroy() { - } - - @Override - public void setHandler( OperationHandler handler ) { - this.handler = handler; - } - - public OperationHandler getHandler() { - return handler; - } - - } } diff --git a/com.eclipsesource.tabris.test/META-INF/MANIFEST.MF b/com.eclipsesource.tabris.test/META-INF/MANIFEST.MF index 8fc8885..ffa7e96 100644 --- a/com.eclipsesource.tabris.test/META-INF/MANIFEST.MF +++ b/com.eclipsesource.tabris.test/META-INF/MANIFEST.MF @@ -8,4 +8,4 @@ Fragment-Host: com.eclipsesource.tabris;bundle-version="1.4.0" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Require-Bundle: org.junit;bundle-version="[4.10.0,5.0.0)", org.mockito.mockito-all;bundle-version="1.9.5", - org.eclipse.rap.rwt.testfixture;bundle-version="2.2.0" + com.eclipsesource.tabris.test.util;bundle-version="1.4.0" diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/TabrisClientInstallerTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/TabrisClientInstallerTest.java index 6744cfe..2487e8c 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/TabrisClientInstallerTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/TabrisClientInstallerTest.java @@ -25,26 +25,19 @@ import org.eclipse.rap.rwt.internal.resources.ResourceRegistry; import org.eclipse.rap.rwt.internal.theme.ThemeManager; import org.eclipse.rap.rwt.service.ResourceLoader; -import org.junit.Before; import org.junit.Rule; import org.junit.Test; import com.eclipsesource.tabris.internal.Constants; import com.eclipsesource.tabris.internal.TabrisResourceLoader; -import com.eclipsesource.tabris.test.RWTEnvironment; -import com.eclipsesource.tabris.test.TabrisTestUtil; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; @SuppressWarnings("restriction") public class TabrisClientInstallerTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); - - @Before - public void setUp() { - TabrisTestUtil.mockRemoteObject(); - } + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testRegistersTheme() { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/AppImplTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/AppImplTest.java index 8fc8ff4..ba682a6 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/AppImplTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/AppImplTest.java @@ -36,13 +36,13 @@ import com.eclipsesource.tabris.app.AppEvent; import com.eclipsesource.tabris.app.AppListener; import com.eclipsesource.tabris.app.BackNavigationListener; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class AppImplTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testIsSerializable() { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/AppLauncherTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/AppLauncherTest.java index 0e998b8..b948b31 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/AppLauncherTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/AppLauncherTest.java @@ -28,14 +28,13 @@ import com.eclipsesource.tabris.interaction.LaunchOptions; import com.eclipsesource.tabris.interaction.LaunchOptions.App; import com.eclipsesource.tabris.interaction.MailOptions; -import com.eclipsesource.tabris.test.RWTEnvironment; -import com.eclipsesource.tabris.test.TabrisTestUtil; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class AppLauncherTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testIsSerializable() { @@ -51,7 +50,7 @@ public void testFailsWithNullOptions() { @Test public void testOpenCreatsCallOperation() { - RemoteObject remoteObject = TabrisTestUtil.mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); AppLauncher launcher = new AppLauncherImpl(); launcher.open( new MailOptions( "foo" ) ); @@ -63,7 +62,7 @@ public void testOpenCreatsCallOperation() { @Test public void testOpenCreatsCallOperationWithProperties() { - RemoteObject remoteObject = TabrisTestUtil.mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); AppLauncher launcher = new AppLauncherImpl(); LaunchOptions options = new MailOptions( "foo" ); options.add( "foo", "bar" ); @@ -79,7 +78,7 @@ public void testOpenCreatsCallOperationWithProperties() { @Test public void testOpenUrlCreatesCallOperation() { - RemoteObject remoteObject = TabrisTestUtil.mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); AppLauncher launcher = new AppLauncherImpl(); launcher.openUrl( "http://foo.bar" ); diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/Base64Test.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/Base64Test.java index 94dc1cc..0442004 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/Base64Test.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/Base64Test.java @@ -6,11 +6,9 @@ import java.util.Arrays; import java.util.Random; -import org.junit.Test; - import junit.framework.TestCase; -import com.eclipsesource.tabris.internal.Base64; +import org.junit.Test; public class Base64Test extends TestCase { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/CameraImplTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/CameraImplTest.java index 8ad295b..a82d2e4 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/CameraImplTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/CameraImplTest.java @@ -37,13 +37,13 @@ import com.eclipsesource.tabris.camera.Camera; import com.eclipsesource.tabris.camera.CameraListener; import com.eclipsesource.tabris.camera.CameraOptions; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class CameraImplTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Before public void setUp() { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ClientCanvasLCATest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ClientCanvasLCATest.java index 1b6f4fd..0db6d8e 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ClientCanvasLCATest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ClientCanvasLCATest.java @@ -28,7 +28,7 @@ import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.widgets.ClientCanvas; @@ -36,7 +36,7 @@ public class ClientCanvasLCATest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private ClientCanvas clientCanvas; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ClientCanvasOperatorTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ClientCanvasOperatorTest.java index cf1389f..1381feb 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ClientCanvasOperatorTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ClientCanvasOperatorTest.java @@ -16,8 +16,6 @@ import org.eclipse.rap.json.JsonObject; import org.eclipse.rap.json.JsonValue; -import org.eclipse.rap.rwt.lifecycle.WidgetUtil; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; @@ -25,7 +23,7 @@ import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.widgets.ClientCanvas; import com.eclipsesource.tabris.widgets.ClientDrawListener; @@ -33,7 +31,7 @@ public class ClientCanvasOperatorTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Shell shell; @@ -54,11 +52,10 @@ public void testFiresDrawEvent() { ClientDrawListener drawListener = mock( ClientDrawListener.class ); clientCanvas.addClientDrawListener( drawListener ); ClientCanvasOperator operator = new ClientCanvasOperator( clientCanvas ); - Fixture.fakeNewRequest(); + environment.newRequest(); JsonObject drawings = new JsonObject(); drawings.add( ClientCanvasOperator.DRAWINGS_PROPERTY, JsonValue.valueOf( ClientCanvasTestUtil.createDrawings( 1 ) ) ); - Fixture.fakeNotifyOperation( WidgetUtil.getId( clientCanvas ), ClientCanvasOperator.DRAWING_EVENT, drawings ); - environment.runProcessAction(); + environment.dispatchNotify( ClientCanvasOperator.DRAWING_EVENT, drawings ); operator.handleNotify( clientCanvas, ClientCanvasOperator.DRAWING_EVENT, drawings ); @@ -71,11 +68,10 @@ public void testAddsDrawingToCache() { ClientDrawListener drawListener = mock( ClientDrawListener.class ); clientCanvas.addClientDrawListener( drawListener ); ClientCanvasOperator operator = new ClientCanvasOperator( clientCanvas ); - Fixture.fakeNewRequest(); + environment.newRequest(); JsonObject drawings = new JsonObject(); drawings.add( ClientCanvasOperator.DRAWINGS_PROPERTY, JsonValue.valueOf( ClientCanvasTestUtil.createDrawings( 1 ) ) ); - Fixture.fakeNotifyOperation( WidgetUtil.getId( clientCanvas ), ClientCanvasOperator.DRAWING_EVENT, drawings ); - environment.runProcessAction(); + environment.dispatchNotify( ClientCanvasOperator.DRAWING_EVENT, drawings ); operator.handleNotify( clientCanvas, ClientCanvasOperator.DRAWING_EVENT, drawings ); diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ClientDeviceImplTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ClientDeviceImplTest.java index 200b915..14bfc0c 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ClientDeviceImplTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ClientDeviceImplTest.java @@ -23,9 +23,6 @@ import org.eclipse.rap.json.JsonArray; import org.eclipse.rap.json.JsonObject; -import org.eclipse.rap.rwt.RWT; -import org.eclipse.rap.rwt.testfixture.Fixture; -import org.eclipse.rap.rwt.testfixture.TestRequest; import org.junit.Rule; import org.junit.Test; @@ -35,13 +32,14 @@ import com.eclipsesource.tabris.device.ClientDevice.Orientation; import com.eclipsesource.tabris.device.ClientDevice.Platform; import com.eclipsesource.tabris.device.ClientDeviceListener; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; +import com.eclipsesource.tabris.test.util.TabrisRequest; public class ClientDeviceImplTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testIsSerializable() { @@ -55,7 +53,7 @@ public void testClientDeviceListenerIsSerializable() { @Test public void testGetPlatformIsAndroid() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, "com.eclipsesource.tabris.android" ); ClientDevice device = new ClientDeviceImpl(); @@ -66,7 +64,7 @@ public void testGetPlatformIsAndroid() { @Test public void testGetPlatformIsIOS() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, "com.eclipsesource.tabris.ios" ); ClientDevice device = new ClientDeviceImpl(); @@ -77,7 +75,7 @@ public void testGetPlatformIsIOS() { @Test public void testGetPlatformIsSWT() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, "com.eclipsesource.tabris.swt" ); ClientDevice device = new ClientDeviceImpl(); @@ -88,7 +86,7 @@ public void testGetPlatformIsSWT() { @Test public void testGetPlatformIsWebByDefault() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, "Mozilla/bla" ); ClientDevice device = new ClientDeviceImpl(); @@ -99,7 +97,7 @@ public void testGetPlatformIsWebByDefault() { @Test public void testGetLocaleReturnsNullWhenLocaleNotSet() { - Fixture.fakeNewGetRequest(); + environment.newGetRequest(); ClientDeviceImpl deviceImpl = new ClientDeviceImpl(); Locale locale = deviceImpl.getLocale(); @@ -109,7 +107,7 @@ public void testGetLocaleReturnsNullWhenLocaleNotSet() { @Test public void testGetLocalesReturnsEmptyArrayWhenLocaleNotSet() { - Fixture.fakeNewGetRequest(); + environment.newGetRequest(); ClientDeviceImpl deviceImpl = new ClientDeviceImpl(); Locale[] locales = deviceImpl.getLocales(); @@ -119,7 +117,7 @@ public void testGetLocalesReturnsEmptyArrayWhenLocaleNotSet() { @Test public void testGetLocaleReadsLocaleFromRequest() { - TestRequest request = Fixture.fakeNewGetRequest(); + TabrisRequest request = environment.newGetRequest(); request.setHeader( "Accept-Language", "anything" ); request.setLocales( new Locale( "en-US" ) ); ClientDeviceImpl deviceImpl = new ClientDeviceImpl(); @@ -131,7 +129,7 @@ public void testGetLocaleReadsLocaleFromRequest() { @Test public void testGetLocalesReadsLocalesFromRequest() { - TestRequest request = Fixture.fakeNewGetRequest(); + TabrisRequest request = environment.newGetRequest(); request.setHeader( "Accept-Language", "anything" ); request.setLocales( new Locale( "en-US" ), new Locale( "de-DE" ) ); ClientDeviceImpl deviceImpl = new ClientDeviceImpl(); @@ -145,7 +143,7 @@ public void testGetLocalesReadsLocalesFromRequest() { @Test public void testReturnsSaveLocalesCopy() { - TestRequest request = Fixture.fakeNewGetRequest(); + TabrisRequest request = environment.newGetRequest(); request.setHeader( "Accept-Language", "anything" ); request.setLocales( new Locale( "en-US" ) ); ClientDeviceImpl deviceImpl = new ClientDeviceImpl(); diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ClientStoreImplTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ClientStoreImplTest.java index 9c6cae8..17cd41f 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ClientStoreImplTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ClientStoreImplTest.java @@ -24,13 +24,13 @@ import org.junit.Test; import org.mockito.ArgumentCaptor; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class ClientStoreImplTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Test( expected = IllegalArgumentException.class ) public void testAddFailsWithNullKey() { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/DataWhitelistTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/DataWhitelistTest.java index 3d22a3e..2f06557 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/DataWhitelistTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/DataWhitelistTest.java @@ -20,14 +20,14 @@ import org.junit.Test; import com.eclipsesource.tabris.internal.DataWhitelist.WhiteListEntry; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; @SuppressWarnings("restriction") public class DataWhitelistTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testIsSerializable() { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/GCOperationDispatcherTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/GCOperationDispatcherTest.java index 4ef86eb..37ec186 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/GCOperationDispatcherTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/GCOperationDispatcherTest.java @@ -30,13 +30,13 @@ import org.mockito.ArgumentCaptor; import org.mockito.InOrder; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class GCOperationDispatcherTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private GC gc; private GCOperationDispatcher dispatcher; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/GeolocationImplTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/GeolocationImplTest.java index 0ce1b66..ebf139a 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/GeolocationImplTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/GeolocationImplTest.java @@ -33,13 +33,13 @@ import com.eclipsesource.tabris.geolocation.Position; import com.eclipsesource.tabris.geolocation.PositionError; import com.eclipsesource.tabris.geolocation.PositionError.PositionErrorCode; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class GeolocationImplTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testIsSerializable() { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/PrintImplTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/PrintImplTest.java index bde3a31..0924e15 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/PrintImplTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/PrintImplTest.java @@ -33,13 +33,13 @@ import com.eclipsesource.tabris.print.PrintError; import com.eclipsesource.tabris.print.PrintListener; import com.eclipsesource.tabris.print.PrintOptions; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class PrintImplTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testIsSerializable() { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/RefreshCompositeLCATest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/RefreshCompositeLCATest.java index 758442c..10aaa6a 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/RefreshCompositeLCATest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/RefreshCompositeLCATest.java @@ -10,31 +10,39 @@ ******************************************************************************/ package com.eclipsesource.tabris.internal; +import static com.eclipsesource.tabris.test.util.MessageUtil.getOperationProperties; +import static com.eclipsesource.tabris.test.util.MessageUtil.hasCreateOperation; +import static com.eclipsesource.tabris.test.util.MessageUtil.hasOperation; +import static com.eclipsesource.tabris.test.util.MessageUtil.isParentOfCreate; +import static com.eclipsesource.tabris.test.util.MessageUtil.OperationType.CALL; +import static com.eclipsesource.tabris.test.util.MessageUtil.OperationType.CREATE; +import static com.eclipsesource.tabris.test.util.MessageUtil.OperationType.LISTEN; +import static com.eclipsesource.tabris.test.util.MessageUtil.OperationType.SET; import static org.eclipse.rap.rwt.lifecycle.WidgetUtil.getId; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import java.io.IOException; import org.eclipse.rap.json.JsonArray; +import org.eclipse.rap.json.JsonObject; import org.eclipse.rap.rwt.internal.remote.RemoteObjectRegistry; +import org.eclipse.rap.rwt.lifecycle.WidgetUtil; import org.eclipse.rap.rwt.remote.OperationHandler; import org.eclipse.rap.rwt.scripting.ClientListener; -import org.eclipse.rap.rwt.testfixture.Fixture; -import org.eclipse.rap.rwt.testfixture.Message; -import org.eclipse.rap.rwt.testfixture.Message.CreateOperation; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; -import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.test.ControlLCATestUtil; +import com.eclipsesource.tabris.test.util.ControlLCATestUtil; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.widgets.RefreshComposite; import com.eclipsesource.tabris.widgets.RefreshListener; @@ -42,6 +50,9 @@ @SuppressWarnings("restriction") public class RefreshCompositeLCATest { + @Rule + public TabrisEnvironment environment = new TabrisEnvironment(); + private Display display; private Shell shell; private RefreshCompositeLCA lca; @@ -49,19 +60,12 @@ public class RefreshCompositeLCATest { @Before public void setUp() { - Fixture.setUp(); display = new Display(); shell = new Shell( display ); lca = new RefreshCompositeLCA(); - Fixture.fakeNewRequest(); composite = new RefreshComposite( shell, SWT.BORDER ); } - @After - public void tearDown() { - Fixture.tearDown(); - } - @Test public void testControlListeners() throws IOException { ControlLCATestUtil.testActivateListener( composite ); @@ -77,9 +81,7 @@ public void testControlListeners() throws IOException { public void testRenderCreate() throws IOException { lca.renderInitialization( composite ); - Message message = Fixture.getProtocolMessage(); - CreateOperation operation = message.findCreateOperation( composite ); - assertEquals( "tabris.widgets.RefreshComposite", operation.getType() ); + assertTrue( hasCreateOperation( "tabris.widgets.RefreshComposite" ) ); } @Test @@ -97,8 +99,8 @@ public void testRenderInitializationRendersMessage() throws IOException { lca.renderInitialization( composite ); - Message message = Fixture.getProtocolMessage(); - assertEquals( "foo", message.findCreateProperty( composite, "message" ).asString() ); + JsonObject properties = getOperationProperties( WidgetUtil.getId( composite ), CREATE, null ); + assertEquals( "foo", properties.get( "message" ).asString() ); } @Test @@ -107,17 +109,15 @@ public void testRenderInitializationRendersRefreshListen() throws IOException { lca.renderInitialization( composite ); - Message message = Fixture.getProtocolMessage(); - assertTrue( message.findListenProperty( composite, "Refresh" ).asBoolean() ); + JsonObject properties = getOperationProperties( WidgetUtil.getId( composite ), LISTEN, null ); + assertTrue( properties.get( "Refresh" ).asBoolean() ); } @Test public void testRenderParent() throws IOException { lca.renderInitialization( composite ); - Message message = Fixture.getProtocolMessage(); - CreateOperation operation = message.findCreateOperation( composite ); - assertEquals( getId( composite.getParent() ), operation.getParent() ); + assertTrue( isParentOfCreate( "tabris.widgets.RefreshComposite", getId( composite.getParent() ) ) ); } @Test @@ -126,20 +126,18 @@ public void testRenderListenToRefreshToRefresh() { lca.renderListenToRefresh( composite ); - Message message = Fixture.getProtocolMessage(); - assertTrue( message.findListenProperty( composite, "Refresh" ).asBoolean() ); + JsonObject properties = getOperationProperties( WidgetUtil.getId( composite ), LISTEN, null ); + assertTrue( properties.get( "Refresh" ).asBoolean() ); } @Test public void testRenderListenToRefreshToRefreshUnchanged() { - Fixture.markInitialized( composite ); composite.addRefreshListener( mock( RefreshListener.class ) ); lca.preserveValues( composite ); lca.renderClientArea( composite ); - Message message = Fixture.getProtocolMessage(); - assertNull( message.findListenOperation( composite, "Refresh" ) ); + assertFalse( hasOperation( WidgetUtil.getId( composite ), LISTEN, null ) ); } @Test @@ -148,20 +146,19 @@ public void testRenderMessage() { lca.renderMessage( composite ); - Message message = Fixture.getProtocolMessage(); - assertEquals( "foo", message.findSetProperty( composite, "message" ).asString() ); + JsonObject properties = getOperationProperties( WidgetUtil.getId( composite ), SET, null ); + assertEquals( "foo", properties.get( "message" ).asString() ); } @Test - public void testRenderMessageUnchanged() { - Fixture.markInitialized( composite ); + public void testRenderMessageUnchanged() throws IOException { composite.setMessage( "foo" ); + lca.renderInitialization( composite ); lca.preserveValues( composite ); lca.renderClientArea( composite ); - Message message = Fixture.getProtocolMessage(); - assertNull( message.findSetOperation( composite, "message" ) ); + assertFalse( hasOperation( WidgetUtil.getId( composite ), SET, null ) ); } @Test @@ -170,20 +167,18 @@ public void testRenderDone() { lca.renderDone( composite ); - Message message = Fixture.getProtocolMessage(); - assertNotNull( message.findCallOperation( composite, "done" ) ); + JsonObject properties = getOperationProperties( WidgetUtil.getId( composite ), CALL, "done" ); + assertTrue( properties.isEmpty() ); } @Test public void testRenderDoneUnchanged() { - Fixture.markInitialized( composite ); composite.done(); lca.preserveValues( composite ); lca.renderDone( composite ); - Message message = Fixture.getProtocolMessage(); - assertNull( message.findCallOperation( composite, "done" ) ); + assertFalse( hasOperation( WidgetUtil.getId( composite ), CALL, "done" ) ); } @Test @@ -192,9 +187,9 @@ public void testRenderClientArea() { lca.renderClientArea( composite ); - Message message = Fixture.getProtocolMessage(); Rectangle clientArea = composite.getClientArea(); - assertEquals( clientArea, toRectangle( message.findSetProperty( composite, "clientArea" ) ) ); + JsonObject properties = getOperationProperties( WidgetUtil.getId( composite ), SET, null ); + assertEquals( clientArea, toRectangle( properties.get( "clientArea" ) ) ); } @Test @@ -203,21 +198,20 @@ public void testRenderClientAreaSizeZero() { lca.renderClientArea( composite ); - Message message = Fixture.getProtocolMessage(); Rectangle clientArea = new Rectangle( 0, 0, 0, 0 ); - assertEquals( clientArea, toRectangle( message.findSetProperty( composite, "clientArea" ) ) ); + JsonObject properties = getOperationProperties( WidgetUtil.getId( composite ), SET, null ); + assertEquals( clientArea, toRectangle( properties.get( "clientArea" ) ) ); } @Test - public void testRenderClientAreaSizeUnchanged() { - Fixture.markInitialized( composite ); + public void testRenderClientAreaSizeUnchanged() throws IOException { composite.setSize( 110, 120 ); + lca.renderInitialization( composite ); lca.preserveValues( composite ); lca.renderClientArea( composite ); - Message message = Fixture.getProtocolMessage(); - assertNull( message.findSetOperation( composite, "clientArea" ) ); + assertFalse( hasOperation( WidgetUtil.getId( composite ), SET, null ) ); } @Test @@ -226,8 +220,8 @@ public void testRenderChangesRendersClientListener() throws IOException { lca.renderChanges( composite ); - Message message = Fixture.getProtocolMessage(); - assertNotNull( message.findCallOperation( composite, "addListener" ) ); + JsonObject properties = getOperationProperties( WidgetUtil.getId( composite ), CALL, "addListener" ); + assertNotNull( properties ); } private Rectangle toRectangle( Object property ) { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/RefreshCompositeOperationHandlerTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/RefreshCompositeOperationHandlerTest.java index f32cf14..5ff906d 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/RefreshCompositeOperationHandlerTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/RefreshCompositeOperationHandlerTest.java @@ -23,7 +23,7 @@ import org.junit.Test; import org.mockito.InOrder; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.widgets.RefreshComposite; import com.eclipsesource.tabris.widgets.RefreshListener; @@ -32,7 +32,7 @@ public class RefreshCompositeOperationHandlerTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Shell shell; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TableItemHeightServiceTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TableItemHeightServiceTest.java index aec6888..0f7981a 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TableItemHeightServiceTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TableItemHeightServiceTest.java @@ -8,31 +8,36 @@ package com.eclipsesource.tabris.internal; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.verify; import java.io.Serializable; import org.eclipse.rap.json.JsonObject; -import org.eclipse.rap.rwt.internal.remote.RemoteObjectRegistry; +import org.eclipse.rap.rwt.RWT; +import org.eclipse.rap.rwt.internal.remote.ConnectionImpl; import org.eclipse.rap.rwt.lifecycle.WidgetUtil; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.Widget; -import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; + @SuppressWarnings("restriction") public class TableItemHeightServiceTest { + @Rule + public TabrisEnvironment environment = new TabrisEnvironment(); + private Table table; private Tree tree; private JsonObject parameters; @@ -40,7 +45,6 @@ public class TableItemHeightServiceTest { @Before public void setUp() { - Fixture.setUp(); Display display = new Display(); Shell shell = new Shell( display ); table = new Table( shell, SWT.NONE ); @@ -49,11 +53,6 @@ public void setUp() { itemHeightService = new TableItemHeightService(); } - @After - public void tearDown() { - Fixture.tearDown(); - } - @Test public void testIsSerializable() { assertTrue( Serializable.class.isAssignableFrom( TableItemHeightService.class ) ); @@ -61,7 +60,9 @@ public void testIsSerializable() { @Test public void testServiceCreated() { - assertNotNull( RemoteObjectRegistry.getInstance().get( Constants.GRID_ITEM_HEIGHT_SETTER ) ); + ConnectionImpl connection = ( ConnectionImpl )RWT.getUISession().getConnection(); + + verify( connection ).createServiceObject( Constants.GRID_ITEM_HEIGHT_SETTER ); } @Test diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TabrisClientImplTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TabrisClientImplTest.java index 45a8c00..38fac61 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TabrisClientImplTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TabrisClientImplTest.java @@ -25,13 +25,13 @@ import com.eclipsesource.tabris.geolocation.Geolocation; import com.eclipsesource.tabris.interaction.AppLauncher; import com.eclipsesource.tabris.print.Print; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class TabrisClientImplTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testHasAppLauncherService() { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TabrisClientProviderTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TabrisClientProviderTest.java index bb2fc61..e3ac9ce 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TabrisClientProviderTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TabrisClientProviderTest.java @@ -12,6 +12,7 @@ import static com.eclipsesource.tabris.internal.Constants.PROPERTY_VERSION_CHECK; import static com.eclipsesource.tabris.internal.VersionCheck.TABRIS_SERVER_VERSION; +import static com.eclipsesource.tabris.test.util.MessageUtil.getHead; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; @@ -32,23 +33,21 @@ import org.eclipse.rap.rwt.internal.theme.css.CssFileReader; import org.eclipse.rap.rwt.internal.theme.css.StyleSheet; import org.eclipse.rap.rwt.service.ResourceLoader; -import org.eclipse.rap.rwt.testfixture.Fixture; -import org.eclipse.rap.rwt.testfixture.TestRequest; -import org.eclipse.rap.rwt.testfixture.internal.engine.ThemeManagerHelper; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import com.eclipsesource.tabris.TabrisClient; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; +import com.eclipsesource.tabris.test.util.TabrisRequest; @SuppressWarnings("restriction") public class TabrisClientProviderTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private static final String CURRENT_THEME_ID = "org.eclipse.rap.theme.current"; @@ -76,7 +75,7 @@ public void testFailsWithEmptyServerId() { @Test public void testAcceptForAndroid() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, Constants.ID_ANDROID ); assertTrue( provider.accept( request ) ); @@ -84,7 +83,7 @@ public void testAcceptForAndroid() { @Test public void testAcceptForIOS() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, Constants.ID_IOS ); assertTrue( provider.accept( request ) ); @@ -103,7 +102,7 @@ public void testReturnsTabrisClient() { @Test public void testUsesIOSTheme() throws IOException { registerTheme( Constants.THEME_ID_IOS ); - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, Constants.ID_IOS ); provider.accept( request ); @@ -115,7 +114,7 @@ public void testUsesIOSTheme() throws IOException { @Test public void testUsesIOS6Theme() throws IOException { registerTheme( Constants.THEME_ID_IOS6 ); - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, Constants.ID_IOS + " OS 6.1.2" ); provider.accept( request ); @@ -127,7 +126,7 @@ public void testUsesIOS6Theme() throws IOException { @Test public void testUsesAndroidTheme() throws IOException { registerTheme( Constants.THEME_ID_ANDROID ); - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, Constants.ID_ANDROID ); provider.accept( request ); @@ -147,7 +146,7 @@ public InputStream getResourceAsStream( String resourceName ) throws IOException StyleSheet styleSheet = CssFileReader.readStyleSheet( "", resourceLoader ); Theme theme = new Theme( themeId, "unknown", styleSheet ); ApplicationContextImpl applicationContext = ContextProvider.getContext().getApplicationContext(); - ThemeManagerHelper.resetThemeManager(); + environment.resetThemes(); ThemeManager themeManager = applicationContext.getThemeManager(); themeManager.registerTheme( theme ); } @@ -155,7 +154,7 @@ public InputStream getResourceAsStream( String resourceName ) throws IOException @Test public void testSetsServerIdAsHeaderForAndroid() { provider = new TabrisClientProvider( "foo" ); - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, Constants.ID_ANDROID ); provider.accept( request ); @@ -167,7 +166,7 @@ public void testSetsServerIdAsHeaderForAndroid() { @Test public void testSetsServerIdAsHeaderForIOS() { provider = new TabrisClientProvider( "foo" ); - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, Constants.ID_IOS ); provider.accept( request ); @@ -178,7 +177,7 @@ public void testSetsServerIdAsHeaderForIOS() { @Test public void testSetsServerIdAsHeaderForAndroidOnlyIfSet() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, Constants.ID_ANDROID ); provider.accept( request ); @@ -189,7 +188,7 @@ public void testSetsServerIdAsHeaderForAndroidOnlyIfSet() { @Test public void testSetsServerIdAsHeaderForIOSOnlyIfSet() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, Constants.ID_IOS ); provider.accept( request ); @@ -201,7 +200,7 @@ public void testSetsServerIdAsHeaderForIOSOnlyIfSet() { @Test public void testSetsNoServerIdAsHeaderForWeb() { provider = new TabrisClientProvider( "foo" ); - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); provider.accept( request ); @@ -211,7 +210,7 @@ public void testSetsNoServerIdAsHeaderForWeb() { @Test public void testSets412ForIncompatibleVersion() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, Constants.ID_IOS + "/42.1.0 (foo)" ); provider.accept( request ); @@ -222,12 +221,12 @@ public void testSets412ForIncompatibleVersion() { @Test public void testSetsErrorHeadAttribute() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, Constants.ID_IOS + "/42.1.0 (foo)" ); provider.accept( request ); - JsonObject head = Fixture.getProtocolMessage().getHead(); + JsonObject head = getHead(); String error = head.get( "error" ).asString(); assertEquals( "Incompatible Tabris Versions:\nClient 42.1 vs. Server " + TABRIS_SERVER_VERSION, error ); } @@ -235,7 +234,7 @@ public void testSetsErrorHeadAttribute() { @Test public void testRespectsSystemPropertyForVersionCheck() { System.setProperty( PROPERTY_VERSION_CHECK, "false" ); - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, Constants.ID_IOS + "/42.1.0 (foo)" ); provider.accept( request ); diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TabrisSWTClientProviderTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TabrisSWTClientProviderTest.java index 96bc460..fc05ba3 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TabrisSWTClientProviderTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TabrisSWTClientProviderTest.java @@ -27,20 +27,19 @@ import org.eclipse.rap.rwt.internal.theme.css.CssFileReader; import org.eclipse.rap.rwt.internal.theme.css.StyleSheet; import org.eclipse.rap.rwt.service.ResourceLoader; -import org.eclipse.rap.rwt.testfixture.TestRequest; -import org.eclipse.rap.rwt.testfixture.internal.engine.ThemeManagerHelper; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; +import com.eclipsesource.tabris.test.util.TabrisRequest; @SuppressWarnings("restriction") public class TabrisSWTClientProviderTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private static final String CURRENT_THEME_ID = "org.eclipse.rap.theme.current"; @@ -58,7 +57,7 @@ public void testIsSerializable() { @Test public void testAcceptForSWT() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, Constants.ID_SWT ); assertTrue( provider.accept( request ) ); @@ -77,7 +76,7 @@ public void testReturnsTabrisClient() { @Test public void testUsesSWTTheme() throws IOException { registerTheme( Constants.THEME_ID_SWT ); - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, Constants.ID_SWT ); provider.accept( request ); @@ -97,7 +96,7 @@ public InputStream getResourceAsStream( String resourceName ) throws IOException StyleSheet styleSheet = CssFileReader.readStyleSheet( "", resourceLoader ); Theme theme = new Theme( themeId, "unknown", styleSheet ); ApplicationContextImpl applicationContext = ContextProvider.getContext().getApplicationContext(); - ThemeManagerHelper.resetThemeManager(); + environment.resetThemes(); ThemeManager themeManager = applicationContext.getThemeManager(); themeManager.registerTheme( theme ); } diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TabrisSWTClientTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TabrisSWTClientTest.java index aabaa6a..4b53872 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TabrisSWTClientTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/TabrisSWTClientTest.java @@ -14,13 +14,13 @@ import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class TabrisSWTClientTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testHasBrowserNavigationService() { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/VersionCheckTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/VersionCheckTest.java index a1bdd56..1569a51 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/VersionCheckTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/VersionCheckTest.java @@ -14,29 +14,21 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import org.eclipse.rap.rwt.RWT; -import org.eclipse.rap.rwt.testfixture.Fixture; -import org.eclipse.rap.rwt.testfixture.TestRequest; -import org.junit.After; -import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; +import com.eclipsesource.tabris.test.util.TabrisRequest; -public class VersionCheckTest { - @Before - public void setUp() { - Fixture.setUp(); - } +public class VersionCheckTest { - @After - public void tearDown() { - Fixture.tearDown(); - } + @Rule + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testFindsHasServerServsion() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, "com.eclipsesource.tabris.android/1.3.0 (foo)" ); VersionCheck versionCheck = new VersionCheck( "1.3" ); @@ -47,7 +39,7 @@ public void testFindsHasServerServsion() { @Test public void testFindsClientVersionOnAndroid() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, "com.eclipsesource.tabris.android/1.3.0 (foo)" ); VersionCheck versionCheck = new VersionCheck( "1.3" ); @@ -58,7 +50,7 @@ public void testFindsClientVersionOnAndroid() { @Test public void testFindsClientVersionOnIOS() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, "com.eclipsesource.tabris.ios/1.3.0 (foo)" ); VersionCheck versionCheck = new VersionCheck( "1.3" ); @@ -69,7 +61,7 @@ public void testFindsClientVersionOnIOS() { @Test public void testMatchesIdenticalVersionOnAdnroid() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, "com.eclipsesource.tabris.android/1.3.0 (foo)" ); VersionCheck versionCheck = new VersionCheck( "1.3" ); @@ -80,7 +72,7 @@ public void testMatchesIdenticalVersionOnAdnroid() { @Test public void testMatchesIdenticalVersionOnIOS() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, "com.eclipsesource.tabris.ios/1.3.0 (foo)" ); VersionCheck versionCheck = new VersionCheck( "1.3" ); @@ -91,7 +83,7 @@ public void testMatchesIdenticalVersionOnIOS() { @Test public void testMatchesMajorMinorVersionOnAdnroid() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, "com.eclipsesource.tabris.android/1.3.1 (foo)" ); VersionCheck versionCheck = new VersionCheck( "1.3" ); @@ -102,7 +94,7 @@ public void testMatchesMajorMinorVersionOnAdnroid() { @Test public void testMatchesMajorMinorVersionOnIOS() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, "com.eclipsesource.tabris.ios/1.3.1 (foo)" ); VersionCheck versionCheck = new VersionCheck( "1.3" ); @@ -113,7 +105,7 @@ public void testMatchesMajorMinorVersionOnIOS() { @Test public void testMatchesNotDifferentMinorOnAndroid() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, "com.eclipsesource.tabris.android/1.4 (foo)" ); VersionCheck versionCheck = new VersionCheck( "1.3" ); @@ -124,7 +116,7 @@ public void testMatchesNotDifferentMinorOnAndroid() { @Test public void testMatchesNotDifferentMinorOnIOS() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, "com.eclipsesource.tabris.ios/1.4 (foo)" ); VersionCheck versionCheck = new VersionCheck( "1.3" ); @@ -135,7 +127,7 @@ public void testMatchesNotDifferentMinorOnIOS() { @Test public void testMatchesNotDifferentMajorOnAndroid() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, "com.eclipsesource.tabris.android/2.3 (foo)" ); VersionCheck versionCheck = new VersionCheck( "1.3" ); @@ -146,7 +138,7 @@ public void testMatchesNotDifferentMajorOnAndroid() { @Test public void testMatchesNotDifferentMajorOnIOS() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, "com.eclipsesource.tabris.ios/2.3 (foo)" ); VersionCheck versionCheck = new VersionCheck( "1.3" ); @@ -157,7 +149,7 @@ public void testMatchesNotDifferentMajorOnIOS() { @Test public void testMatchesNotDifferentHighMajorOnAndroid() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, "com.eclipsesource.tabris.android/41.1.0 (foo)" ); VersionCheck versionCheck = new VersionCheck( "1.3" ); @@ -168,7 +160,7 @@ public void testMatchesNotDifferentHighMajorOnAndroid() { @Test public void testMatchesNotDifferentHighMajorOnIOS() { - TestRequest request = ( TestRequest )RWT.getRequest(); + TabrisRequest request = environment.getRequest(); request.setHeader( Constants.USER_AGENT, "com.eclipsesource.tabris.ios/42.1.0 (foo)" ); VersionCheck versionCheck = new VersionCheck( "1.3" ); diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/VideoLifeCycleAdapterTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/VideoLifeCycleAdapterTest.java index c0add58..aeeff6c 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/VideoLifeCycleAdapterTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/VideoLifeCycleAdapterTest.java @@ -13,11 +13,14 @@ import static com.eclipsesource.tabris.internal.Constants.PROPERTY_PLAYBACK; import static com.eclipsesource.tabris.internal.Constants.PROPERTY_PRESENTATION; import static com.eclipsesource.tabris.internal.VideoLifeCycleAdapter.keyForEnum; -import static org.eclipse.rap.rwt.testfixture.Fixture.fakeNotifyOperation; +import static com.eclipsesource.tabris.test.util.MessageUtil.hasOperation; +import static com.eclipsesource.tabris.test.util.MessageUtil.isParentOfCreate; +import static com.eclipsesource.tabris.test.util.MessageUtil.OperationType.CREATE; +import static com.eclipsesource.tabris.test.util.MessageUtil.OperationType.LISTEN; +import static com.eclipsesource.tabris.test.util.MessageUtil.OperationType.SET; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -29,11 +32,6 @@ import org.eclipse.rap.rwt.internal.lifecycle.AbstractWidgetLCA; import org.eclipse.rap.rwt.internal.lifecycle.WidgetLifeCycleAdapter; import org.eclipse.rap.rwt.lifecycle.WidgetUtil; -import org.eclipse.rap.rwt.testfixture.Fixture; -import org.eclipse.rap.rwt.testfixture.Message; -import org.eclipse.rap.rwt.testfixture.Message.CreateOperation; -import org.eclipse.rap.rwt.testfixture.Message.ListenOperation; -import org.eclipse.rap.rwt.testfixture.Message.SetOperation; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; @@ -43,8 +41,10 @@ import org.junit.Test; import com.eclipsesource.tabris.internal.VideoLifeCycleAdapter.PlaybackOptions; -import com.eclipsesource.tabris.test.ControlLCATestUtil; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.internal.VideoLifeCycleAdapter.VideoOperationHandler; +import com.eclipsesource.tabris.test.util.ControlLCATestUtil; +import com.eclipsesource.tabris.test.util.MessageUtil; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.widgets.PlaybackListener; import com.eclipsesource.tabris.widgets.PresentationListener; import com.eclipsesource.tabris.widgets.Video; @@ -56,7 +56,7 @@ public class VideoLifeCycleAdapterTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Video video; private Shell parent; @@ -73,7 +73,7 @@ public void setUp() { presentationListener = mock( PresentationListener.class ); new Button( parent, SWT.PUSH ); lifeCycleAdapter = ( AbstractWidgetLCA )video.getAdapter( WidgetLifeCycleAdapter.class ); - Fixture.fakeNewRequest(); + environment.newRequest(); } @Test @@ -96,240 +96,194 @@ public void testControlListeners() throws IOException { public void testCreatesWidget() throws IOException { lifeCycleAdapter.renderInitialization( video ); - CreateOperation createOperation = Fixture.getProtocolMessage().findCreateOperation( video ); - assertEquals( video.getURL().toString(), createOperation.getProperty( Constants.PROPERTY_URL ).asString() ); + assertTrue( MessageUtil.hasCreateOperation( "tabris.widgets.Video" ) ); + JsonObject properties = MessageUtil.getOperationProperties( WidgetUtil.getId( video ), CREATE, null ); + assertEquals( video.getURL().toString(), properties.get( Constants.PROPERTY_URL ).asString() ); } @Test public void testCreatesParent() throws IOException { lifeCycleAdapter.renderInitialization( video ); - Message message = Fixture.getProtocolMessage(); - CreateOperation operation = message.findCreateOperation( video ); - assertEquals( WidgetUtil.getId( video.getParent() ), operation.getParent() ); - } - - @Test - public void testType() throws IOException { - lifeCycleAdapter.renderInitialization( video ); - - Message message = Fixture.getProtocolMessage(); - CreateOperation operation = message.findCreateOperation( video ); - assertEquals( Constants.TYPE_VIDEO, operation.getType() ); + assertTrue( isParentOfCreate( "tabris.widgets.Video", WidgetUtil.getId( video.getParent() ) ) ); } @Test public void testFiresPlaybackChange() { + environment.getRemoteObject().setHandler( new VideoOperationHandler( video ) ); video.addPlaybackListener( playbackListener ); JsonObject parameters = new JsonObject(); parameters.add( PROPERTY_PLAYBACK, Playback.ERROR.name() ); - fakeNotifyOperation( getId(), Constants.EVENT_PLAYBACK, parameters ); - Fixture.executeLifeCycleFromServerThread(); + environment.dispatchNotify( Constants.EVENT_PLAYBACK, parameters ); verify( playbackListener ).playbackChanged( Playback.ERROR ); } @Test public void testRendersPlaybackReadyOnce() { + environment.getRemoteObject().setHandler( new VideoOperationHandler( video ) ); video.addPlaybackListener( playbackListener ); - Fixture.executeLifeCycleFromServerThread(); - Fixture.fakeNewRequest(); + environment.newRequest(); JsonObject parameters = new JsonObject(); parameters.add( PROPERTY_PLAYBACK, Playback.READY.name() ); - fakeNotifyOperation( getId(), Constants.EVENT_PLAYBACK, parameters ); - Fixture.executeLifeCycleFromServerThread(); + environment.dispatchNotify( Constants.EVENT_PLAYBACK, parameters ); verify( playbackListener ).playbackChanged( Playback.READY ); - Message message = Fixture.getProtocolMessage(); - assertNull( message.findSetOperation( video, keyForEnum( PlaybackOptions.PLAYBACK ) ) ); + assertFalse( hasOperation( WidgetUtil.getId( video ), SET, null ) ); } @Test public void testRendersPlaybackPlayOnce() { + environment.getRemoteObject().setHandler( new VideoOperationHandler( video ) ); video.addPlaybackListener( playbackListener ); - Fixture.executeLifeCycleFromServerThread(); - Fixture.fakeNewRequest(); + environment.newRequest(); JsonObject parameters = new JsonObject(); parameters.add( PROPERTY_PLAYBACK, Playback.PLAY.name() ); - fakeNotifyOperation( getId(), Constants.EVENT_PLAYBACK, parameters ); - Fixture.executeLifeCycleFromServerThread(); + + environment.dispatchNotify( Constants.EVENT_PLAYBACK, parameters ); verify( playbackListener ).playbackChanged( Playback.PLAY ); - Message message = Fixture.getProtocolMessage(); - assertNull( message.findSetOperation( video, keyForEnum( PlaybackOptions.PLAYBACK ) ) ); + assertFalse( hasOperation( WidgetUtil.getId( video ), SET, null ) ); } @Test public void testFiresPresentationChange() { + environment.getRemoteObject().setHandler( new VideoOperationHandler( video ) ); video.addPresentationListener( presentationListener ); JsonObject parameters = new JsonObject(); parameters.add( PROPERTY_PRESENTATION, Presentation.FULL_SCREEN.name() ); - fakeNotifyOperation( getId(), Constants.EVENT_PRESENTATION, parameters ); - Fixture.executeLifeCycleFromServerThread(); + environment.dispatchNotify( Constants.EVENT_PRESENTATION, parameters ); verify( presentationListener ).presentationChanged( Presentation.FULL_SCREEN ); } @Test public void testFiresPresentationChangeToFullScreen() { + environment.getRemoteObject().setHandler( new VideoOperationHandler( video ) ); video.addPresentationListener( presentationListener ); JsonObject parameters = new JsonObject(); parameters.add( PROPERTY_PRESENTATION, Presentation.FULL_SCREEN.name() ); - fakeNotifyOperation( getId(), Constants.EVENT_PRESENTATION, parameters ); - Fixture.executeLifeCycleFromServerThread(); + environment.dispatchNotify( Constants.EVENT_PRESENTATION, parameters ); verify( presentationListener ).presentationChanged( Presentation.FULL_SCREEN ); } @Test public void testFiresPresentationChangeToFullScreenOnce() { + environment.getRemoteObject().setHandler( new VideoOperationHandler( video ) ); video.addPresentationListener( presentationListener ); - Fixture.executeLifeCycleFromServerThread(); - Fixture.fakeNewRequest(); + environment.newRequest(); JsonObject parameters = new JsonObject(); parameters.add( PROPERTY_PRESENTATION, Presentation.FULL_SCREEN.name() ); - fakeNotifyOperation( getId(), Constants.EVENT_PRESENTATION, parameters ); - Fixture.executeLifeCycleFromServerThread(); + environment.dispatchNotify( Constants.EVENT_PRESENTATION, parameters ); verify( presentationListener ).presentationChanged( Presentation.FULL_SCREEN ); - Message message = Fixture.getProtocolMessage(); - assertNull( message.findSetOperation( video, keyForEnum( PlaybackOptions.PRESENTATION ) ) ); + assertFalse( hasOperation( WidgetUtil.getId( video ), SET, null ) ); } @Test public void testRendersPlaybackMode() throws IOException { - Fixture.markInitialized( video.getDisplay() ); - Fixture.markInitialized( video ); - Fixture.preserveWidgets(); + lifeCycleAdapter.preserveValues( video ); video.play(); lifeCycleAdapter.renderChanges( video ); - Message message = Fixture.getProtocolMessage(); - SetOperation operation = message.findSetOperation( video, keyForEnum( PlaybackOptions.PLAYBACK ) ); - assertEquals( keyForEnum( Playback.PLAY ), operation.getProperty( keyForEnum( PlaybackOptions.PLAYBACK ) ).asString() ); + JsonObject properties = MessageUtil.getOperationProperties( WidgetUtil.getId( video ), SET, null ); + assertEquals( keyForEnum( Playback.PLAY ), properties.get( keyForEnum( PlaybackOptions.PLAYBACK ) ).asString() ); } @Test public void testRendersPresentationMode() throws IOException { - Fixture.markInitialized( video.getDisplay() ); - Fixture.markInitialized( video ); - Fixture.preserveWidgets(); + lifeCycleAdapter.preserveValues( video ); video.setFullscreen( true ); lifeCycleAdapter.renderChanges( video ); - Message message = Fixture.getProtocolMessage(); - SetOperation operation = message.findSetOperation( video, keyForEnum( PlaybackOptions.PRESENTATION ) ); + JsonObject properties = MessageUtil.getOperationProperties( WidgetUtil.getId( video ), SET, null ); assertEquals( keyForEnum( Presentation.FULL_SCREEN ), - operation.getProperty( keyForEnum( PlaybackOptions.PRESENTATION ) ).asString() ); + properties.get( keyForEnum( PlaybackOptions.PRESENTATION ) ).asString() ); } @Test public void testRendersSpeedForward() throws IOException { - Fixture.markInitialized( video.getDisplay() ); - Fixture.markInitialized( video ); - Fixture.preserveWidgets(); + lifeCycleAdapter.preserveValues( video ); video.fastForward( 2 ); lifeCycleAdapter.renderChanges( video ); - Message message = Fixture.getProtocolMessage(); - SetOperation operation = message.findSetOperation( video, keyForEnum( PlaybackOptions.SPEED ) ); - assertEquals( 2, operation.getProperty( keyForEnum( PlaybackOptions.SPEED ) ).asDouble(), 0 ); + JsonObject properties = MessageUtil.getOperationProperties( WidgetUtil.getId( video ), SET, null ); + assertEquals( 2, properties.get( keyForEnum( PlaybackOptions.SPEED ) ).asDouble(), 0 ); } @Test public void testRendersSpeedBackward() throws IOException { - Fixture.markInitialized( video.getDisplay() ); - Fixture.markInitialized( video ); - Fixture.preserveWidgets(); + lifeCycleAdapter.preserveValues( video ); video.fastBackward( -2 ); lifeCycleAdapter.renderChanges( video ); - Message message = Fixture.getProtocolMessage(); - SetOperation operation = message.findSetOperation( video, keyForEnum( PlaybackOptions.SPEED ) ); - assertEquals( -2, operation.getProperty( keyForEnum( PlaybackOptions.SPEED ) ).asDouble(), 0 ); + JsonObject properties = MessageUtil.getOperationProperties( WidgetUtil.getId( video ), SET, null ); + assertEquals( -2, properties.get( keyForEnum( PlaybackOptions.SPEED ) ).asDouble(), 0 ); } @Test public void testRendersRepeat() throws IOException { - Fixture.markInitialized( video.getDisplay() ); - Fixture.markInitialized( video ); - Fixture.preserveWidgets(); + lifeCycleAdapter.preserveValues( video ); video.setRepeat( true ); lifeCycleAdapter.renderChanges( video ); - Message message = Fixture.getProtocolMessage(); - SetOperation operation = message.findSetOperation( video, keyForEnum( PlaybackOptions.REPEAT ) ); - assertTrue( operation.getProperty( keyForEnum( PlaybackOptions.REPEAT ) ).asBoolean() ); + JsonObject properties = MessageUtil.getOperationProperties( WidgetUtil.getId( video ), SET, null ); + assertTrue( properties.get( keyForEnum( PlaybackOptions.REPEAT ) ).asBoolean() ); } @Test public void testRendersControlsVisible() throws IOException { - Fixture.markInitialized( video.getDisplay() ); - Fixture.markInitialized( video ); - Fixture.preserveWidgets(); + lifeCycleAdapter.preserveValues( video ); video.setPlayerControlsVisible( false ); lifeCycleAdapter.renderChanges( video ); - Message message = Fixture.getProtocolMessage(); - SetOperation operation = message.findSetOperation( video, keyForEnum( PlaybackOptions.CONTROLS_VISIBLE ) ); - assertFalse( operation.getProperty( keyForEnum( PlaybackOptions.CONTROLS_VISIBLE ) ).asBoolean() ); + JsonObject properties = MessageUtil.getOperationProperties( WidgetUtil.getId( video ), SET, null ); + assertFalse( properties.get( keyForEnum( PlaybackOptions.CONTROLS_VISIBLE ) ).asBoolean() ); } @Test public void testRendersHeadPointer() throws IOException { - Fixture.markInitialized( video.getDisplay() ); - Fixture.markInitialized( video ); - Fixture.preserveWidgets(); + lifeCycleAdapter.preserveValues( video ); video.stepToTime( 23 ); lifeCycleAdapter.renderChanges( video ); - Message message = Fixture.getProtocolMessage(); - SetOperation operation = message.findSetOperation( video, keyForEnum( PlaybackOptions.HEAD_POSITION ) ); - assertEquals( 23, operation.getProperty( keyForEnum( PlaybackOptions.HEAD_POSITION ) ).asInt() ); + JsonObject properties = MessageUtil.getOperationProperties( WidgetUtil.getId( video ), SET, null ); + assertEquals( 23, properties.get( keyForEnum( PlaybackOptions.HEAD_POSITION ) ).asInt() ); } @Test public void testRendersPlaybackListener() throws IOException { - Fixture.markInitialized( video.getDisplay() ); - Fixture.markInitialized( video ); - Fixture.preserveWidgets(); + lifeCycleAdapter.preserveValues( video ); video.addPlaybackListener( playbackListener ); lifeCycleAdapter.renderChanges( video ); - Message message = Fixture.getProtocolMessage(); - ListenOperation listenOperation = message.findListenOperation( video, Constants.EVENT_PLAYBACK ); - assertNotNull( listenOperation ); + JsonObject properties = MessageUtil.getOperationProperties( WidgetUtil.getId( video ), LISTEN, null ); + assertNotNull( properties.get( Constants.EVENT_PLAYBACK ) ); } @Test public void testRendersPresentationListener() throws IOException { - Fixture.markInitialized( video.getDisplay() ); - Fixture.markInitialized( video ); - Fixture.preserveWidgets(); + lifeCycleAdapter.preserveValues( video ); video.addPresentationListener( presentationListener ); lifeCycleAdapter.renderChanges( video ); - Message message = Fixture.getProtocolMessage(); - ListenOperation listenOperation = message.findListenOperation( video, Constants.EVENT_PRESENTATION ); - assertNotNull( listenOperation ); - } - - private String getId() { - return WidgetUtil.getId( video ); + JsonObject properties = MessageUtil.getOperationProperties( WidgetUtil.getId( video ), LISTEN, null ); + assertNotNull( properties.get( Constants.EVENT_PRESENTATION ) ); } } diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ZIndexStackLayoutTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ZIndexStackLayoutTest.java index 8c0f20a..d8247ac 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ZIndexStackLayoutTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ZIndexStackLayoutTest.java @@ -25,13 +25,13 @@ import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class ZIndexStackLayoutTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Shell shell; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/ActionDescriptorTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/ActionDescriptorTest.java index 4e02279..124580d 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/ActionDescriptorTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/ActionDescriptorTest.java @@ -22,7 +22,7 @@ import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.Action; import com.eclipsesource.tabris.ui.PlacementPriority; @@ -30,7 +30,7 @@ public class ActionDescriptorTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testIsSerializable() { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/ControllerTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/ControllerTest.java index bb9bf51..569cce2 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/ControllerTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/ControllerTest.java @@ -33,7 +33,6 @@ import org.eclipse.rap.rwt.RWT; import org.eclipse.rap.rwt.remote.RemoteObject; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; @@ -46,13 +45,12 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import com.eclipsesource.tabris.TabrisClient; import com.eclipsesource.tabris.internal.ZIndexStackLayout; import com.eclipsesource.tabris.internal.ui.rendering.ActionRenderer; import com.eclipsesource.tabris.internal.ui.rendering.PageRenderer; import com.eclipsesource.tabris.internal.ui.rendering.RendererFactory; import com.eclipsesource.tabris.internal.ui.rendering.UIRenderer; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.Action; import com.eclipsesource.tabris.ui.ActionConfiguration; import com.eclipsesource.tabris.ui.Page; @@ -66,7 +64,7 @@ public class ControllerTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Shell shell; private UIDescriptor uiDescriptor; @@ -77,7 +75,6 @@ public class ControllerTest { @Before public void setUp() { - Fixture.fakeClient( mock( TabrisClient.class ) ); Display display = new Display(); shell = new Shell( display ); layout = mock( ZIndexStackLayout.class ); diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/PageDescriptorTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/PageDescriptorTest.java index cefc7ef..56f20d4 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/PageDescriptorTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/PageDescriptorTest.java @@ -23,7 +23,7 @@ import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.ActionConfiguration; import com.eclipsesource.tabris.ui.PageStyle; @@ -31,7 +31,7 @@ public class PageDescriptorTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testIsSerializable() { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/PageFlowTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/PageFlowTest.java index 421ef1c..02ca865 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/PageFlowTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/PageFlowTest.java @@ -33,7 +33,7 @@ import org.mockito.InOrder; import com.eclipsesource.tabris.internal.ui.rendering.PageRenderer; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.PageData; import com.eclipsesource.tabris.ui.UI; @@ -41,7 +41,7 @@ public class PageFlowTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Shell shell; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/PageOperatorImplTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/PageOperatorImplTest.java index cf8883a..ecf4ae4 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/PageOperatorImplTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/PageOperatorImplTest.java @@ -29,7 +29,7 @@ import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.Page; import com.eclipsesource.tabris.ui.PageData; import com.eclipsesource.tabris.ui.UIConfiguration; @@ -38,7 +38,7 @@ public class PageOperatorImplTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Display display; private Controller controller; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemoteActionTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemoteActionTest.java index 9d2079c..859553f 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemoteActionTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemoteActionTest.java @@ -32,7 +32,7 @@ import org.junit.Test; import org.mockito.ArgumentCaptor; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.Action; import com.eclipsesource.tabris.ui.ActionListener; import com.eclipsesource.tabris.ui.PlacementPriority; @@ -43,7 +43,7 @@ public class RemoteActionTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private RemoteObject remoteObject; private ActionDescriptor actionDescriptor; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemotePageTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemotePageTest.java index 0e95ef0..cc11297 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemotePageTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemotePageTest.java @@ -38,7 +38,7 @@ import com.eclipsesource.tabris.internal.ui.rendering.ActionRenderer; import com.eclipsesource.tabris.internal.ui.rendering.UIRenderer; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.Page; import com.eclipsesource.tabris.ui.PageData; import com.eclipsesource.tabris.ui.PageStyle; @@ -48,7 +48,7 @@ public class RemotePageTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private RemoteObject remoteObject; private PageDescriptor descriptor; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemoteRendererFactoryTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemoteRendererFactoryTest.java index 3610120..38cc511 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemoteRendererFactoryTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemoteRendererFactoryTest.java @@ -25,7 +25,7 @@ import com.eclipsesource.tabris.internal.ui.rendering.ActionRenderer; import com.eclipsesource.tabris.internal.ui.rendering.PageRenderer; import com.eclipsesource.tabris.internal.ui.rendering.UIRenderer; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.Action; import com.eclipsesource.tabris.ui.PageData; import com.eclipsesource.tabris.ui.UI; @@ -34,7 +34,7 @@ public class RemoteRendererFactoryTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private RemoteRendererFactory rendererFactory; private UI ui; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemoteSearchActionTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemoteSearchActionTest.java index e39b30e..db80067 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemoteSearchActionTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemoteSearchActionTest.java @@ -37,7 +37,7 @@ import org.junit.Test; import org.mockito.ArgumentCaptor; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.UI; import com.eclipsesource.tabris.ui.UIConfiguration; import com.eclipsesource.tabris.ui.action.Proposal; @@ -50,7 +50,7 @@ public class RemoteSearchActionTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private RemoteObject remoteObject; private ActionDescriptor actionDescriptor; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemoteUITest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemoteUITest.java index 7b7d045..f8ed2b7 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemoteUITest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/RemoteUITest.java @@ -35,7 +35,7 @@ import org.junit.Test; import com.eclipsesource.tabris.internal.ui.rendering.PageRenderer; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.PageOperator; import com.eclipsesource.tabris.ui.UI; @@ -43,7 +43,7 @@ public class RemoteUITest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Shell shell; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/TabrisUIIntegrationTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/TabrisUIIntegrationTest.java index 8d1b818..fb8edc9 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/TabrisUIIntegrationTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/TabrisUIIntegrationTest.java @@ -10,19 +10,14 @@ ******************************************************************************/ package com.eclipsesource.tabris.internal.ui; -import static org.mockito.Mockito.mock; - -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; -import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.TabrisClient; import com.eclipsesource.tabris.internal.ZIndexStackLayout; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.AbstractPage; import com.eclipsesource.tabris.ui.ActionConfiguration; import com.eclipsesource.tabris.ui.PageConfiguration; @@ -33,12 +28,7 @@ public class TabrisUIIntegrationTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); - - @Before - public void setUp() { - Fixture.fakeClient( mock( TabrisClient.class ) ); - } + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testCanEnableActionInPageCreate() { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/UIDescriptorTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/UIDescriptorTest.java index 8abf551..298cbb3 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/UIDescriptorTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/UIDescriptorTest.java @@ -21,13 +21,12 @@ import java.util.List; import org.eclipse.rap.rwt.client.WebClient; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.junit.Rule; import org.junit.Test; import com.eclipsesource.tabris.TabrisClient; import com.eclipsesource.tabris.internal.ui.web.WebRendererFactory; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.ActionListener; import com.eclipsesource.tabris.ui.TransitionListener; @@ -35,7 +34,7 @@ public class UIDescriptorTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testIsSerializable() { @@ -183,7 +182,7 @@ public void testGetRootPagesReturnsOnlyRootPages() { @Test public void testGetRendererFactory_tabris() { - Fixture.fakeClient( mock( TabrisClient.class ) ); + environment.setClient( mock( TabrisClient.class ) ); UIDescriptor uiDescriptor = new UIDescriptor(); assertTrue( uiDescriptor.getRendererFactory() instanceof RemoteRendererFactory ); @@ -191,7 +190,7 @@ public void testGetRendererFactory_tabris() { @Test public void testGetRendererFactory_web() { - Fixture.fakeClient( mock( WebClient.class ) ); + environment.setClient( mock( WebClient.class ) ); UIDescriptor uiDescriptor = new UIDescriptor(); assertTrue( uiDescriptor.getRendererFactory() instanceof WebRendererFactory ); diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/UIImplTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/UIImplTest.java index 23c53ba..af0b2a6 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/UIImplTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/UIImplTest.java @@ -27,7 +27,7 @@ import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.Action; import com.eclipsesource.tabris.ui.ActionOperator; import com.eclipsesource.tabris.ui.Page; @@ -38,7 +38,7 @@ public class UIImplTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Display display; private Controller controller; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/UpdateUtilTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/UpdateUtilTest.java index 4b60037..48cc8d0 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/UpdateUtilTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/UpdateUtilTest.java @@ -17,11 +17,10 @@ import org.eclipse.rap.rwt.RWT; import org.eclipse.rap.rwt.internal.service.ContextProvider; -import org.eclipse.rap.rwt.testfixture.Fixture; -import org.junit.After; -import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.PageConfiguration; import com.eclipsesource.tabris.ui.UIConfiguration; @@ -29,17 +28,8 @@ @SuppressWarnings("restriction") public class UpdateUtilTest { - @Before - public void setUp() { - Fixture.setUp(); - } - - @After - public void tearDown() { - if( ContextProvider.hasContext() ) { - Fixture.tearDown(); - } - } + @Rule + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testRegistersUpdaterInUISession() { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebActionTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebActionTest.java index 29ff011..0b4c850 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebActionTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebActionTest.java @@ -36,7 +36,7 @@ import com.eclipsesource.tabris.internal.ui.ImageUtil; import com.eclipsesource.tabris.internal.ui.RemoteActionTest; import com.eclipsesource.tabris.internal.ui.TestAction; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.ActionListener; import com.eclipsesource.tabris.ui.UI; import com.eclipsesource.tabris.ui.UIConfiguration; @@ -45,7 +45,7 @@ public class WebActionTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private UI ui; private WebUI webUI; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebPageTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebPageTest.java index 618f38d..6619a3d 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebPageTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebPageTest.java @@ -27,7 +27,6 @@ import org.eclipse.rap.rwt.client.WebClient; import org.eclipse.rap.rwt.client.service.JavaScriptExecutor; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.junit.Before; @@ -41,7 +40,7 @@ import com.eclipsesource.tabris.internal.ui.TestPage; import com.eclipsesource.tabris.internal.ui.UITestUtil; import com.eclipsesource.tabris.internal.ui.rendering.ActionRenderer; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.Page; import com.eclipsesource.tabris.ui.PageData; import com.eclipsesource.tabris.ui.PageStyle; @@ -51,7 +50,7 @@ public class WebPageTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Shell shell; private UI ui; @@ -127,7 +126,7 @@ public void testSetTitle_rendersTitle() { WebClient webClient = mock( WebClient.class ); JavaScriptExecutor javaScriptExecutor = mock( JavaScriptExecutor.class ); when( webClient.getService( JavaScriptExecutor.class ) ).thenReturn( javaScriptExecutor ); - Fixture.fakeClient( webClient ); + environment.setClient( webClient ); webPage.setTitle( "foo" ); @@ -139,7 +138,7 @@ public void testSetTitleUpdatesUi() { WebClient webClient = mock( WebClient.class ); JavaScriptExecutor javaScriptExecutor = mock( JavaScriptExecutor.class ); when( webClient.getService( JavaScriptExecutor.class ) ).thenReturn( javaScriptExecutor ); - Fixture.fakeClient( webClient ); + environment.setClient( webClient ); webPage.setTitle( "foo" ); @@ -151,7 +150,7 @@ public void testPageActivated_rendersTitle() { WebClient webClient = mock( WebClient.class ); JavaScriptExecutor javaScriptExecutor = mock( JavaScriptExecutor.class ); when( webClient.getService( JavaScriptExecutor.class ) ).thenReturn( javaScriptExecutor ); - Fixture.fakeClient( webClient ); + environment.setClient( webClient ); webPage.pageActivated(); diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebRendererFactoryTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebRendererFactoryTest.java index e04212e..bcd45de 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebRendererFactoryTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebRendererFactoryTest.java @@ -29,7 +29,7 @@ import com.eclipsesource.tabris.internal.ui.rendering.ActionRenderer; import com.eclipsesource.tabris.internal.ui.rendering.PageRenderer; import com.eclipsesource.tabris.internal.ui.rendering.UIRenderer; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.Action; import com.eclipsesource.tabris.ui.PageData; import com.eclipsesource.tabris.ui.UI; @@ -38,7 +38,7 @@ public class WebRendererFactoryTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private WebRendererFactory rendererFactory; private Shell shell; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebSearchActionTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebSearchActionTest.java index 2235ff1..63513cf 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebSearchActionTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebSearchActionTest.java @@ -47,7 +47,7 @@ import com.eclipsesource.tabris.internal.ui.PropertyChangeNotifier; import com.eclipsesource.tabris.internal.ui.RemoteActionTest; import com.eclipsesource.tabris.internal.ui.TestSearchAction; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.Action; import com.eclipsesource.tabris.ui.UI; import com.eclipsesource.tabris.ui.UIConfiguration; @@ -60,7 +60,7 @@ public class WebSearchActionTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private UI ui; private WebUI uiRenderer; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebUITest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebUITest.java index e8d67f7..c4e36b5 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebUITest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/internal/ui/web/WebUITest.java @@ -41,7 +41,7 @@ import org.junit.Test; import com.eclipsesource.tabris.internal.ui.PageDescriptor; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.ui.PageOperator; import com.eclipsesource.tabris.ui.UI; @@ -49,7 +49,7 @@ public class WebUITest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Display display; private Shell shell; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/AbstractPageTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/AbstractPageTest.java index 1b67e16..f89d037 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/AbstractPageTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/AbstractPageTest.java @@ -26,13 +26,13 @@ import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class AbstractPageTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Shell shell; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/ActionConfigurationTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/ActionConfigurationTest.java index f459206..cdc1824 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/ActionConfigurationTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/ActionConfigurationTest.java @@ -27,13 +27,13 @@ import com.eclipsesource.tabris.internal.ui.ActionDescriptor; import com.eclipsesource.tabris.internal.ui.TestAction; import com.eclipsesource.tabris.internal.ui.UITestUtil; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class ActionConfigurationTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testIsSerializable() { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/PageConfigurationTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/PageConfigurationTest.java index ab9186a..c2fca70 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/PageConfigurationTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/PageConfigurationTest.java @@ -35,13 +35,13 @@ import com.eclipsesource.tabris.internal.ui.UITestUtil; import com.eclipsesource.tabris.internal.ui.UIUpdater; import com.eclipsesource.tabris.internal.ui.UpdateUtil; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class PageConfigurationTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testIsSerializable() { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/TabrisUIEntryPointTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/TabrisUIEntryPointTest.java index 7100602..64b2f80 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/TabrisUIEntryPointTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/TabrisUIEntryPointTest.java @@ -22,28 +22,25 @@ import org.eclipse.rap.rwt.internal.application.ApplicationContextImpl; import org.eclipse.rap.rwt.internal.lifecycle.LifeCycle; import org.eclipse.rap.rwt.internal.lifecycle.LifeCycleFactory; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.widgets.Shell; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.internal.TabrisClientImpl; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; @SuppressWarnings("restriction") public class TabrisUIEntryPointTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Before public void setUp() { LifeCycleFactory lifeCycleFactory = getApplicationContext().getLifeCycleFactory(); lifeCycleFactory.configure( TestLifeCycle.class ); lifeCycleFactory.activate(); - Fixture.fakeClient( new TabrisClientImpl() ); } @Test diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/TabrisUIEntrypointFactoryTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/TabrisUIEntrypointFactoryTest.java index f6ab1c2..1984601 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/TabrisUIEntrypointFactoryTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/TabrisUIEntrypointFactoryTest.java @@ -20,13 +20,13 @@ import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class TabrisUIEntrypointFactoryTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testIsSerializable() { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/TabrisUITest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/TabrisUITest.java index ed9af89..843b90f 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/TabrisUITest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/TabrisUITest.java @@ -21,7 +21,6 @@ import org.eclipse.rap.json.JsonArray; import org.eclipse.rap.rwt.remote.JsonMapping; import org.eclipse.rap.rwt.remote.RemoteObject; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Display; @@ -30,28 +29,25 @@ import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.TabrisClient; import com.eclipsesource.tabris.internal.ZIndexStackLayout; import com.eclipsesource.tabris.internal.ui.TestPage; import com.eclipsesource.tabris.internal.ui.UITestUtil; -import com.eclipsesource.tabris.test.RWTEnvironment; -import com.eclipsesource.tabris.test.TabrisTestUtil; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class TabrisUITest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Shell shell; private RemoteObject remoteObject; @Before public void setUp() { - Fixture.fakeClient( mock( TabrisClient.class ) ); Display display = new Display(); shell = new Shell( display ); - remoteObject = TabrisTestUtil.mockRemoteObject(); + remoteObject = environment.getRemoteObject(); } @Test diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/UIConfigurationTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/UIConfigurationTest.java index 719b64d..81cc257 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/UIConfigurationTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/ui/UIConfigurationTest.java @@ -35,13 +35,13 @@ import com.eclipsesource.tabris.internal.ui.UITestUtil; import com.eclipsesource.tabris.internal.ui.UIUpdater; import com.eclipsesource.tabris.internal.ui.UpdateUtil; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class UIConfigurationTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Test public void testIsSerializable() { diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/ClientCanvasTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/ClientCanvasTest.java index 992b56b..9b21112 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/ClientCanvasTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/ClientCanvasTest.java @@ -11,7 +11,6 @@ package com.eclipsesource.tabris.widgets; import static com.eclipsesource.tabris.internal.DataWhitelist.WhiteListEntry.CLIENT_CANVAS; -import static org.eclipse.rap.rwt.lifecycle.WidgetUtil.getId; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -26,7 +25,6 @@ import org.eclipse.rap.json.JsonObject; import org.eclipse.rap.rwt.internal.lifecycle.WidgetLifeCycleAdapter; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.SWT; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; @@ -42,14 +40,14 @@ import com.eclipsesource.tabris.internal.ClientCanvasOperator; import com.eclipsesource.tabris.internal.ClientCanvasTestUtil; import com.eclipsesource.tabris.internal.DrawingsCache; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; @SuppressWarnings("restriction") public class ClientCanvasTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private ClientCanvas clientCanvas; @@ -145,9 +143,7 @@ public void testCachesDrawings() { clientCanvas.addPaintListener( paintListener ); fakeDrawEvent(); - JsonObject parameters = new JsonObject(); - parameters.add( ClientCanvasOperator.DRAWINGS_PROPERTY, ClientCanvasTestUtil.createDrawingsWithoutLineWidth() ); - Fixture.fakeNewRequest(); + environment.newRequest(); fakeDrawEvent(); assertEquals( 1, clientCanvas.getAdapter( DrawingsCache.class ).getCachedDrawings().size() ); @@ -159,7 +155,7 @@ public void testClearTriggersRedraw() { clientCanvas.addPaintListener( listener ); clientCanvas.clear(); - Fixture.fakeNewRequest(); + environment.newRequest(); fakeDrawEvent(); assertTrue( listener.wasCalled() ); @@ -189,7 +185,6 @@ public void testUndoRedraws() { clientCanvas.addPaintListener( listener ); fakeDrawEvent(); - environment.runProcessAction(); clientCanvas.undo(); assertTrue( listener.wasCalled() ); @@ -220,7 +215,6 @@ public void testRedoRedraws() { CheckPaintListener listener = new CheckPaintListener(); clientCanvas.addPaintListener( listener ); fakeDrawEvent(); - environment.runProcessAction(); clientCanvas.undo(); clientCanvas.redo(); @@ -304,11 +298,9 @@ public void testFiresDrawingReceivedOnRemoved() { } private void fakeDrawEvent() { + environment.getRemoteObject().setHandler( new ClientCanvasOperator( clientCanvas ) ); JsonObject parameters = new JsonObject(); parameters.add( ClientCanvasOperator.DRAWINGS_PROPERTY, ClientCanvasTestUtil.createDrawings( 2 ) ); - Fixture.executeLifeCycleFromServerThread(); - Fixture.fakeNewRequest(); - Fixture.fakeNotifyOperation( getId( clientCanvas ), ClientCanvasOperator.DRAWING_EVENT, parameters ); - Fixture.executeLifeCycleFromServerThread(); + environment.dispatchNotify( ClientCanvasOperator.DRAWING_EVENT, parameters ); } } diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/ClientDialogTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/ClientDialogTest.java index d1cc421..d51c16b 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/ClientDialogTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/ClientDialogTest.java @@ -11,7 +11,6 @@ package com.eclipsesource.tabris.widgets; import static com.eclipsesource.tabris.internal.Constants.EVENT_SELECTION; -import static com.eclipsesource.tabris.test.TabrisTestUtil.mockRemoteObject; import static com.eclipsesource.tabris.widgets.ClientDialog.Severity.INFO; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; @@ -34,7 +33,7 @@ import org.mockito.ArgumentCaptor; import com.eclipsesource.tabris.internal.Constants; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.widgets.ClientDialog.ButtonType; import com.eclipsesource.tabris.widgets.ClientDialog.Severity; @@ -42,7 +41,7 @@ public class ClientDialogTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Rule public ExpectedException thrown = ExpectedException.none(); @@ -72,7 +71,7 @@ public void testSetsTitle() { @Test public void testSetsTitleOnRemoteObject() { - RemoteObject remoteObject = mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); ClientDialog dialog = new ClientDialog(); dialog.setTitle( "foo" ); @@ -101,7 +100,7 @@ public void testSetsMessage() { @Test public void testSetsMessageOnRemoteObject() { - RemoteObject remoteObject = mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); ClientDialog dialog = new ClientDialog(); dialog.setMessage( "bar" ); @@ -139,7 +138,7 @@ public void testSetsSeverity() { @Test public void testSetsSeverityOnRemoteObject() { - RemoteObject remoteObject = mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); ClientDialog dialog = new ClientDialog(); dialog.setSeverity( INFO ); @@ -158,7 +157,7 @@ public void testSetSeverityReturnsDialog() { @Test public void testOpenCreatesCallOperation() { - RemoteObject remoteObject = mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); ClientDialog dialog = new ClientDialog(); dialog.open(); @@ -168,7 +167,7 @@ public void testOpenCreatesCallOperation() { @Test public void testCloseCreatesCallOperation() { - RemoteObject remoteObject = mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); ClientDialog dialog = new ClientDialog(); dialog.close(); @@ -207,7 +206,7 @@ public void testNotifiesListenerOnSelectionEventWithCorrectDisplay() { @Test public void testSetsButtonSetsButtonPropertyOnRemoteObject() { - RemoteObject remoteObject = mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); ClientDialog dialog = new ClientDialog(); Listener listener = mock( Listener.class ); @@ -218,7 +217,7 @@ public void testSetsButtonSetsButtonPropertyOnRemoteObject() { @Test public void testSetsButtonCreateListenOnRemoteObject() { - RemoteObject remoteObject = mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); ClientDialog dialog = new ClientDialog(); Listener listener = mock( Listener.class ); @@ -229,7 +228,7 @@ public void testSetsButtonCreateListenOnRemoteObject() { @Test public void testSetsButtonCreateListenOnRemoteObjectOnce() { - RemoteObject remoteObject = mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); ClientDialog dialog = new ClientDialog(); Listener listener = mock( Listener.class ); @@ -241,7 +240,7 @@ public void testSetsButtonCreateListenOnRemoteObjectOnce() { @Test public void testSetsButtonWithoutListenerSetsButtonPropertyOnRemoteObject() { - RemoteObject remoteObject = mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); ClientDialog dialog = new ClientDialog(); dialog.setButton( ButtonType.OK, "bar" ); @@ -323,7 +322,7 @@ public void testFailsToRemoveNullClientListener() { @Test public void testAddClientDialogListenerSendsListen() { - RemoteObject remoteObject = mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); ClientDialog dialog = new ClientDialog(); dialog.addClientDialogListener( mock( ClientDialogListener.class ) ); @@ -333,7 +332,7 @@ public void testAddClientDialogListenerSendsListen() { @Test public void testAddClientDialogListenersSendsListenOnce() { - RemoteObject remoteObject = mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); ClientDialog dialog = new ClientDialog(); dialog.addClientDialogListener( mock( ClientDialogListener.class ) ); @@ -344,7 +343,7 @@ public void testAddClientDialogListenersSendsListenOnce() { @Test public void testRemoveClientDialogListenerSendsListen() { - RemoteObject remoteObject = mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); ClientDialog dialog = new ClientDialog(); ClientDialogListener listener = mock( ClientDialogListener.class ); dialog.addClientDialogListener( listener ); diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/PagingIndicatorTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/PagingIndicatorTest.java index c89f8dd..5731af9 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/PagingIndicatorTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/PagingIndicatorTest.java @@ -10,35 +10,43 @@ ******************************************************************************/ package com.eclipsesource.tabris.widgets; +import static com.eclipsesource.tabris.test.util.MessageUtil.OperationType.CALL; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; +import java.io.IOException; + +import org.eclipse.rap.json.JsonObject; import org.eclipse.rap.rwt.lifecycle.WidgetUtil; -import org.eclipse.rap.rwt.testfixture.Fixture; -import org.eclipse.rap.rwt.testfixture.Message; -import org.eclipse.rap.rwt.testfixture.Message.CallOperation; -import org.eclipse.rap.rwt.testfixture.Message.Operation; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.internal.widgets.canvaskit.CanvasLCA; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.junit.Before; import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.MessageUtil; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; +@SuppressWarnings("restriction") public class PagingIndicatorTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Shell parent; + private PagingIndicator indicator; + @Before public void setUp() { parent = new Shell( new Display() ); + indicator = new PagingIndicator( parent ); + renderInitialization( indicator ); } @Test( expected = IllegalArgumentException.class ) @@ -48,8 +56,6 @@ public void testFailsWithNullParent() { @Test public void testHasDefaultForCount() { - PagingIndicator indicator = new PagingIndicator( parent ); - int count = indicator.getCount(); assertEquals( 1, count ); @@ -57,8 +63,6 @@ public void testHasDefaultForCount() { @Test public void testSavesSettedCount() { - PagingIndicator indicator = new PagingIndicator( parent ); - indicator.setCount( 10 ); int count = indicator.getCount(); @@ -67,15 +71,11 @@ public void testSavesSettedCount() { @Test( expected = IllegalArgumentException.class ) public void testFailsToSetNegativeCount() { - PagingIndicator indicator = new PagingIndicator( parent ); - indicator.setCount( -1 ); } @Test public void testHasDefaultForActive() { - PagingIndicator indicator = new PagingIndicator( parent ); - int active = indicator.getActive(); assertEquals( 0, active ); @@ -83,7 +83,6 @@ public void testHasDefaultForActive() { @Test public void testSavesSettedActive() { - PagingIndicator indicator = new PagingIndicator( parent ); indicator.setCount( 2 ); indicator.setActive( 1 ); @@ -94,22 +93,16 @@ public void testSavesSettedActive() { @Test( expected = IllegalArgumentException.class ) public void testFailsToSetActiveWithNegativeIndex() { - PagingIndicator indicator = new PagingIndicator( parent ); - indicator.setActive( -1 ); } @Test( expected = IllegalStateException.class ) public void testFailsToSetActiveWithNonExistingIndex() { - PagingIndicator indicator = new PagingIndicator( parent ); - indicator.setActive( 2 ); } @Test public void testHasDefaultForSpacing() { - PagingIndicator indicator = new PagingIndicator( parent ); - int spacing = indicator.getSpacing(); assertEquals( 9, spacing ); @@ -117,8 +110,6 @@ public void testHasDefaultForSpacing() { @Test public void testSavesSettedSpacing() { - PagingIndicator indicator = new PagingIndicator( parent ); - indicator.setSpacing( 5 ); int spacing = indicator.getSpacing(); @@ -127,15 +118,11 @@ public void testSavesSettedSpacing() { @Test( expected = IllegalArgumentException.class ) public void testFailsToSetNegativeSpacing() { - PagingIndicator indicator = new PagingIndicator( parent ); - indicator.setSpacing( -1 ); } @Test public void testHasDefaultForDiameter() { - PagingIndicator indicator = new PagingIndicator( parent ); - int diameter = indicator.getDiameter(); assertEquals( 7, diameter ); @@ -143,8 +130,6 @@ public void testHasDefaultForDiameter() { @Test public void testSavesSettedDiameter() { - PagingIndicator indicator = new PagingIndicator( parent ); - indicator.setDiameter( 5 ); int diameter = indicator.getDiameter(); @@ -153,15 +138,11 @@ public void testSavesSettedDiameter() { @Test( expected = IllegalArgumentException.class ) public void testFailsToSetNegativeDiameter() { - PagingIndicator indicator = new PagingIndicator( parent ); - indicator.setDiameter( -1 ); } @Test public void testHasDefaultForActiveColor() { - PagingIndicator indicator = new PagingIndicator( parent ); - Color activeColor = indicator.getActiveColor(); assertEquals( activeColor.getRGB(), new RGB( 0, 122, 255 ) ); @@ -169,8 +150,6 @@ public void testHasDefaultForActiveColor() { @Test public void testSavesSettedActiveColor() { - PagingIndicator indicator = new PagingIndicator( parent ); - indicator.setActiveColor( new Color( parent.getDisplay(), 0, 0, 0 ) ); Color activeColor = indicator.getActiveColor(); @@ -179,15 +158,11 @@ public void testSavesSettedActiveColor() { @Test( expected = IllegalArgumentException.class ) public void testFailsToSetNullActiveColor() { - PagingIndicator indicator = new PagingIndicator( parent ); - indicator.setActiveColor( null ); } @Test public void testHasDefaultForInactiveColor() { - PagingIndicator indicator = new PagingIndicator( parent ); - Color inactiveColor = indicator.getInactiveColor(); assertEquals( inactiveColor.getRGB(), new RGB( 192, 192, 192 ) ); @@ -195,8 +170,6 @@ public void testHasDefaultForInactiveColor() { @Test public void testSavesSettedInactiveColor() { - PagingIndicator indicator = new PagingIndicator( parent ); - indicator.setInactiveColor( new Color( parent.getDisplay(), 255, 0, 0 ) ); Color inactiveColor = indicator.getInactiveColor(); @@ -205,14 +178,11 @@ public void testSavesSettedInactiveColor() { @Test( expected = IllegalArgumentException.class ) public void testFailsToSetNullInactiveColor() { - PagingIndicator indicator = new PagingIndicator( parent ); - indicator.setInactiveColor( null ); } @Test public void testSetActiveDrawsIndicator() { - PagingIndicator indicator = new PagingIndicator( parent ); indicator.setCount( 2 ); indicator.setActive( 1 ); @@ -222,8 +192,6 @@ public void testSetActiveDrawsIndicator() { @Test public void testSetCountDrawsIndicator() { - PagingIndicator indicator = new PagingIndicator( parent ); - indicator.setCount( 2 ); verifyDraw( indicator ); @@ -231,8 +199,6 @@ public void testSetCountDrawsIndicator() { @Test public void testSetSpacingDrawsIndicator() { - PagingIndicator indicator = new PagingIndicator( parent ); - indicator.setSpacing( 2 ); verifyDraw( indicator ); @@ -240,8 +206,6 @@ public void testSetSpacingDrawsIndicator() { @Test public void testSetDiameterDrawsIndicator() { - PagingIndicator indicator = new PagingIndicator( parent ); - indicator.setDiameter( 10 ); verifyDraw( indicator ); @@ -249,8 +213,6 @@ public void testSetDiameterDrawsIndicator() { @Test public void testSetActiveColorDrawsIndicator() { - PagingIndicator indicator = new PagingIndicator( parent ); - indicator.setActiveColor( new Color( parent.getDisplay(), 0, 0, 0 ) ); verifyDraw( indicator ); @@ -258,8 +220,6 @@ public void testSetActiveColorDrawsIndicator() { @Test public void testSetInactiveColorDrawsIndicator() { - PagingIndicator indicator = new PagingIndicator( parent ); - indicator.setInactiveColor( new Color( parent.getDisplay(), 0, 0, 0 ) ); verifyDraw( indicator ); @@ -267,27 +227,35 @@ public void testSetInactiveColorDrawsIndicator() { @Test public void testUpdateDrawsIndicator() { - PagingIndicator indicator = new PagingIndicator( parent ); - indicator.update(); verifyDraw( indicator ); } private void verifyDraw( PagingIndicator indicator ) { - boolean found = false; + renderChanges( indicator ); String gcId = WidgetUtil.getId( indicator.getCanvas() ) + ".gc"; - Fixture.executeLifeCycleFromServerThread(); - Message message = Fixture.getProtocolMessage(); - for( int i = 0; i < message.getOperationCount(); i++ ) { - Operation operation = message.getOperation( i ); - if( operation instanceof CallOperation && operation.getTarget().equals( gcId ) ) { - CallOperation call = ( CallOperation )operation; - assertEquals( "init", call.getMethodName() ); - found = true; - break; - } + JsonObject properties = MessageUtil.getOperationProperties( gcId, CALL, "init" ); + assertNotNull( properties ); + } + + @SuppressWarnings("deprecation") + private void renderChanges( PagingIndicator indicator ) { + CanvasLCA adapter = ( CanvasLCA )indicator.getCanvas().getAdapter( org.eclipse.rap.rwt.lifecycle.WidgetLifeCycleAdapter.class ); + try { + adapter.renderChanges( indicator.getCanvas() ); + } catch( IOException shouldNotHappen ) { + fail( shouldNotHappen.getMessage() ); + } + } + + @SuppressWarnings("deprecation") + private void renderInitialization( PagingIndicator indicator ) { + CanvasLCA adapter = ( CanvasLCA )indicator.getCanvas().getAdapter( org.eclipse.rap.rwt.lifecycle.WidgetLifeCycleAdapter.class ); + try { + adapter.renderInitialization( indicator.getCanvas() ); + } catch( IOException shouldNotHappen ) { + fail( shouldNotHappen.getMessage() ); } - assertTrue( found ); } } diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/RefreshCompositeTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/RefreshCompositeTest.java index b26ae68..a2ea79c 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/RefreshCompositeTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/RefreshCompositeTest.java @@ -21,34 +21,31 @@ import java.util.List; import org.eclipse.rap.rwt.internal.lifecycle.WidgetLifeCycleAdapter; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; -import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; import com.eclipsesource.tabris.internal.RefreshCompositeLCA; import com.eclipsesource.tabris.internal.RefreshCompositeLCA.RefreshAdapter; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; @SuppressWarnings("restriction") public class RefreshCompositeTest { + @Rule + public TabrisEnvironment environment = new TabrisEnvironment(); + private Shell shell; @Before public void setUp() { - Fixture.setUp(); shell = new Shell( new Display() ); } - @After - public void tearDown() { - Fixture.tearDown(); - } - @Test( expected = IllegalArgumentException.class ) public void testFailsWithNullParent() { new RefreshComposite( null, SWT.NONE ); diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/ScrollingCompositeTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/ScrollingCompositeTest.java index d3cb9c2..85bad02 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/ScrollingCompositeTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/ScrollingCompositeTest.java @@ -31,13 +31,13 @@ import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class ScrollingCompositeTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Shell shell; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/VideoTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/VideoTest.java index 90d07d3..b7a9dc2 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/VideoTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/VideoTest.java @@ -34,7 +34,7 @@ import com.eclipsesource.tabris.internal.VideoLifeCycleAdapter; import com.eclipsesource.tabris.internal.VideoLifeCycleAdapter.PlaybackOptions; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.widgets.Video.Playback; import com.eclipsesource.tabris.widgets.Video.PlaybackAdapter; import com.eclipsesource.tabris.widgets.Video.Presentation; @@ -44,7 +44,7 @@ public class VideoTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Video video; private Shell parent; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/CompositeDecoratorTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/CompositeDecoratorTest.java index 99fa0ff..f7bcbd8 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/CompositeDecoratorTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/CompositeDecoratorTest.java @@ -35,13 +35,13 @@ import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class CompositeDecoratorTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Composite composite; private CompositeDecorator decorator; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/ProgressBarDecoratorTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/ProgressBarDecoratorTest.java index 6394be2..050db73 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/ProgressBarDecoratorTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/ProgressBarDecoratorTest.java @@ -13,32 +13,30 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.ProgressBar; import org.eclipse.swt.widgets.Shell; -import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; + public class ProgressBarDecoratorTest { + @Rule + public TabrisEnvironment environment = new TabrisEnvironment(); + private ProgressBar progressBar; @Before public void setUp() { - Fixture.setUp(); Shell shell = new Shell( new Display() ); progressBar = new ProgressBar( shell, SWT.INDETERMINATE ); } - @After - public void tearDown() { - Fixture.tearDown(); - } - @Test public void testSetsSpinningIndicator() { ProgressBarDecorator decorator = new ProgressBarDecorator( progressBar ); diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/ShellDecoratorTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/ShellDecoratorTest.java index db73724..aed8d39 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/ShellDecoratorTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/ShellDecoratorTest.java @@ -22,13 +22,13 @@ import org.junit.Test; import com.eclipsesource.tabris.internal.DataWhitelist.WhiteListEntry; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class ShellDecoratorTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Shell shell; private ShellDecorator decorator; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/TextDecoratorTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/TextDecoratorTest.java index 0d9251d..f0be9c0 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/TextDecoratorTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/TextDecoratorTest.java @@ -21,36 +21,32 @@ import static org.mockito.Mockito.when; import org.eclipse.rap.rwt.client.WebClient; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.eclipse.swt.widgets.Text; -import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import com.eclipsesource.tabris.TabrisClient; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; @RunWith( MockitoJUnitRunner.class ) public class TextDecoratorTest { + @Rule + public TabrisEnvironment environment = new TabrisEnvironment(); + @Mock private Text text; private TextDecorator decorator; @Before public void setUp() { - Fixture.setUp(); decorator = Widgets.onText( text ); } - @After - public void tearDown() { - Fixture.tearDown(); - } - @Test public void testSetAutoCorrectEnabled() { decorator.setAutoCorrectionEnabled( true ); @@ -137,7 +133,6 @@ public void testUseDecimalKeyboard() { @Test public void testSetsTextReplacement() { - Fixture.fakeClient( mock( TabrisClient.class ) ); TextReplacementData data = mock( TextReplacementData.class ); when( data.getId() ).thenReturn( "r42" ); @@ -153,7 +148,7 @@ public void testSetTextReplacementFailsWithNullData() { @Test public void testDoesNotSetTextReplacementWithWebClient() { - Fixture.fakeClient( mock( WebClient.class ) ); + environment.setClient( mock( WebClient.class ) ); TextReplacementData data = mock( TextReplacementData.class ); when( data.getId() ).thenReturn( "r42" ); diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/TextReplacementDataTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/TextReplacementDataTest.java index 87105e5..9840cf1 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/TextReplacementDataTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/TextReplacementDataTest.java @@ -27,28 +27,24 @@ import org.eclipse.rap.rwt.client.WebClient; import org.eclipse.rap.rwt.remote.Connection; import org.eclipse.rap.rwt.remote.RemoteObject; -import org.eclipse.rap.rwt.testfixture.Fixture; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; -import com.eclipsesource.tabris.TabrisClient; -import com.eclipsesource.tabris.test.RWTEnvironment; -import com.eclipsesource.tabris.test.TabrisTestUtil; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class TextReplacementDataTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private RemoteObject remoteObject; @Before public void setUp() { - Fixture.fakeClient( mock( TabrisClient.class ) ); - remoteObject = TabrisTestUtil.mockRemoteObject(); + remoteObject = environment.getRemoteObject(); } @Test @@ -63,7 +59,7 @@ public void testCreatesRemoteObject() { @Test public void testCreatesNoRemoteObjectWithWebClient() { - Fixture.fakeClient( mock( WebClient.class ) ); + environment.setClient( mock( WebClient.class ) ); TextReplacementData data = new TextReplacementData(); data.put( "shortcut", "replacement" ); @@ -83,7 +79,7 @@ public void testHasRemoteObjectId() { @Test public void testHasNullIdWithWebClient() { - Fixture.fakeClient( mock( WebClient.class ) ); + environment.setClient( mock( WebClient.class ) ); TextReplacementData data = new TextReplacementData(); String id = data.getId(); diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/TreeDecoratorTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/TreeDecoratorTest.java index ddbc1d4..cae6ebe 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/TreeDecoratorTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/enhancement/TreeDecoratorTest.java @@ -30,14 +30,14 @@ import org.junit.Rule; import org.junit.Test; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.widgets.enhancement.TreeDecorator.TreePart; public class TreeDecoratorTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Tree tree; private TreeDecorator decorator; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/swipe/SwipeCommunicationTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/swipe/SwipeCommunicationTest.java index 0786be1..afdab03 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/swipe/SwipeCommunicationTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/swipe/SwipeCommunicationTest.java @@ -37,15 +37,14 @@ import org.mockito.ArgumentCaptor; import org.mockito.InOrder; -import com.eclipsesource.tabris.test.RWTEnvironment; -import com.eclipsesource.tabris.test.TabrisTestUtil; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; import com.eclipsesource.tabris.widgets.swipe.SwipeTest.TestItem; public class SwipeCommunicationTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private RemoteObject remoteObject; private Shell shell; @@ -53,7 +52,7 @@ public class SwipeCommunicationTest { @Before public void setUp() { shell = new Shell( new Display() ); - remoteObject = TabrisTestUtil.mockRemoteObject(); + remoteObject = environment.getRemoteObject(); } @Test diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/swipe/SwipeTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/swipe/SwipeTest.java index 0b4b57c..50bc632 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/swipe/SwipeTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/widgets/swipe/SwipeTest.java @@ -41,13 +41,13 @@ import com.eclipsesource.tabris.internal.SwipeItemHolder; import com.eclipsesource.tabris.internal.ZIndexStackLayout; -import com.eclipsesource.tabris.test.RWTEnvironment; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class SwipeTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); private Shell shell; diff --git a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/xcallbackurl/XCallbackTest.java b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/xcallbackurl/XCallbackTest.java index a68aadb..deef978 100644 --- a/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/xcallbackurl/XCallbackTest.java +++ b/com.eclipsesource.tabris.test/src/com/eclipsesource/tabris/xcallbackurl/XCallbackTest.java @@ -17,14 +17,13 @@ import org.mockito.ArgumentCaptor; import org.mockito.InOrder; -import com.eclipsesource.tabris.test.RWTEnvironment; -import com.eclipsesource.tabris.test.TabrisTestUtil; +import com.eclipsesource.tabris.test.util.TabrisEnvironment; public class XCallbackTest { @Rule - public RWTEnvironment environment = new RWTEnvironment(); + public TabrisEnvironment environment = new TabrisEnvironment(); @Test( expected = IllegalArgumentException.class ) public void testFailsWithNullConfiguration() { @@ -47,7 +46,7 @@ public void testFailsWithRemovingNullCallback() { @Test public void testUsesConfigAsCallParameter() { - RemoteObject remoteObject = TabrisTestUtil.mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); XCallbackConfiguration configuration = new XCallbackConfiguration( "foo", "bar" ); XCallback xCallback = new XCallback( configuration ); @@ -61,7 +60,7 @@ public void testUsesConfigAsCallParameter() { @Test public void testUsesConfigAsCallParameterWithXSource() { - RemoteObject remoteObject = TabrisTestUtil.mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); XCallbackConfiguration configuration = new XCallbackConfiguration( "foo", "bar" ); XCallback xCallback = new XCallback( configuration ); configuration.setXSource( "foo" ); @@ -75,7 +74,7 @@ public void testUsesConfigAsCallParameterWithXSource() { @Test public void testUsesConfigAsCallParameterWithActionParameters() { - RemoteObject remoteObject = TabrisTestUtil.mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); XCallbackConfiguration configuration = new XCallbackConfiguration( "foo", "bar" ); XCallback xCallback = new XCallback( configuration ); configuration.addActionParameter( "foo1", "bar1" ); @@ -202,7 +201,7 @@ public void testGetsConfigurationAsAdapter() { @Test public void testDisposeDestroysRemoteObject() { - RemoteObject remoteObject = TabrisTestUtil.mockRemoteObject(); + RemoteObject remoteObject = environment.getRemoteObject(); XCallbackConfiguration configuration = mock( XCallbackConfiguration.class ); XCallback xCallback = new XCallback( configuration ); diff --git a/com.eclipsesource.tabris/src/com/eclipsesource/tabris/internal/ClientCanvasOperator.java b/com.eclipsesource.tabris/src/com/eclipsesource/tabris/internal/ClientCanvasOperator.java index 4fd8903..8d799cd 100644 --- a/com.eclipsesource.tabris/src/com/eclipsesource/tabris/internal/ClientCanvasOperator.java +++ b/com.eclipsesource.tabris/src/com/eclipsesource/tabris/internal/ClientCanvasOperator.java @@ -11,7 +11,6 @@ package com.eclipsesource.tabris.internal; import static com.eclipsesource.tabris.internal.Clauses.whenNull; -import static org.eclipse.rap.rwt.internal.protocol.ProtocolUtil.readEventPropertyValue; import java.util.ArrayList; import java.util.List; @@ -19,7 +18,6 @@ import org.eclipse.rap.json.JsonObject; import org.eclipse.rap.json.JsonValue; import org.eclipse.rap.rwt.internal.lifecycle.ProcessActionRunner; -import org.eclipse.rap.rwt.lifecycle.WidgetUtil; import org.eclipse.swt.internal.widgets.canvaskit.CanvasOperationHandler; import org.eclipse.swt.widgets.Canvas; @@ -41,19 +39,19 @@ public ClientCanvasOperator( ClientCanvas canvas ) { @Override public void handleNotify( final Canvas control, String eventName, JsonObject properties ) { if( eventName.equals( DRAWING_EVENT ) ) { - handleDrawings( control ); + handleDrawings( control, properties ); } else { super.handleNotify( control, eventName, properties ); } } - private void handleDrawings( final Canvas control ) { + private void handleDrawings( final Canvas control, final JsonObject properties ) { ProcessActionRunner.add( new Runnable() { @Override public void run() { DrawingsCache cache = control.getAdapter( DrawingsCache.class ); - JsonValue drawings = readEventPropertyValue( WidgetUtil.getId( control ), DRAWING_EVENT, DRAWINGS_PROPERTY ); + JsonValue drawings = properties.get( DRAWINGS_PROPERTY ); if( drawings != null ) { cache.cache( drawings.asString() ); cache.clearRemoved(); diff --git a/com.eclipsesource.tabris/src/com/eclipsesource/tabris/internal/VideoLifeCycleAdapter.java b/com.eclipsesource.tabris/src/com/eclipsesource/tabris/internal/VideoLifeCycleAdapter.java index 4615b5e..8ed080d 100644 --- a/com.eclipsesource.tabris/src/com/eclipsesource/tabris/internal/VideoLifeCycleAdapter.java +++ b/com.eclipsesource.tabris/src/com/eclipsesource/tabris/internal/VideoLifeCycleAdapter.java @@ -21,21 +21,21 @@ import static org.eclipse.rap.rwt.internal.lifecycle.WidgetLCAUtil.preserveProperty; import static org.eclipse.rap.rwt.internal.lifecycle.WidgetLCAUtil.renderListener; import static org.eclipse.rap.rwt.internal.lifecycle.WidgetLCAUtil.renderProperty; -import static org.eclipse.rap.rwt.internal.protocol.ProtocolUtil.readEventPropertyValue; -import static org.eclipse.rap.rwt.internal.protocol.ProtocolUtil.wasEventSent; -import static org.eclipse.rap.rwt.lifecycle.WidgetUtil.getId; import java.io.IOException; import java.io.Serializable; import java.util.Map; import java.util.Map.Entry; +import org.eclipse.rap.json.JsonObject; import org.eclipse.rap.rwt.internal.lifecycle.AbstractWidgetLCA; import org.eclipse.rap.rwt.internal.lifecycle.ControlLCAUtil; import org.eclipse.rap.rwt.internal.lifecycle.ProcessActionRunner; import org.eclipse.rap.rwt.internal.protocol.RemoteObjectFactory; import org.eclipse.rap.rwt.lifecycle.WidgetUtil; import org.eclipse.rap.rwt.remote.RemoteObject; +import org.eclipse.swt.internal.widgets.compositekit.CompositeOperationHandler; +import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Widget; @@ -52,50 +52,6 @@ public static enum PlaybackOptions { SPEED, REPEAT, CONTROLS_VISIBLE, PLAYBACK, PRESENTATION, HEAD_POSITION } - @Override - public void readData( Widget widget ) { - readPlaybackMode( widget ); - readPresentationMode( widget ); - } - - private void readPlaybackMode( Widget widget ) { - if( wasEventSent( getId( widget ), EVENT_PLAYBACK ) ) { - String playbackMode = readEventPropertyValue( getId( widget ), EVENT_PLAYBACK, PROPERTY_PLAYBACK ).asString(); - Playback newMode = Playback.valueOf( playbackMode.toUpperCase() ); - Video video = ( Video )widget; - video.getAdapter( PlaybackAdapter.class ).setPlaybackMode( newMode ); - notifyListenersAboutPlaybackModeChange( newMode, video ); - } - } - - private void notifyListenersAboutPlaybackModeChange( final Playback newMode, final Video video ) { - ProcessActionRunner.add( new Runnable() { - @Override - public void run() { - video.getAdapter( PlaybackAdapter.class ).firePlaybackChange( newMode ); - } - } ); - } - - private void readPresentationMode( Widget widget ) { - if( wasEventSent( getId( widget ), EVENT_PRESENTATION ) ) { - String presentationMode = readEventPropertyValue( getId( widget ), EVENT_PRESENTATION, PROPERTY_PRESENTATION ).asString(); - Presentation newMode = Presentation.valueOf( presentationMode.toUpperCase() ); - Video video = ( Video )widget; - video.getAdapter( PlaybackAdapter.class ).getOptions().put( PlaybackOptions.PRESENTATION, newMode ); - notifyListenersAboutPresentationModeChange( newMode, video ); - } - } - - private void notifyListenersAboutPresentationModeChange( final Presentation newMode, final Video video ) { - ProcessActionRunner.add( new Runnable() { - @Override - public void run() { - video.getAdapter( PlaybackAdapter.class ).firePresentationChange( newMode ); - } - } ); - } - @Override public void preserveValues( Widget widget ) { ControlLCAUtil.preserveValues( ( Control )widget ); @@ -124,12 +80,65 @@ public void renderChanges( Widget widget ) throws IOException { @Override public void renderInitialization( Widget widget ) throws IOException { - Video video = ( Video ) widget; + Video video = ( Video )widget; RemoteObject remoteObject = RemoteObjectFactory.createRemoteObject( video, TYPE_VIDEO ); + remoteObject.setHandler( new VideoOperationHandler( video ) ); remoteObject.set( PROPERTY_PARENT, WidgetUtil.getId( video.getParent() ) ); remoteObject.set( PROPERTY_URL, video.getURL().toString() ); } + public static class VideoOperationHandler extends CompositeOperationHandler { + + public VideoOperationHandler( Composite composite ) { + super( composite ); + } + + @Override + public void handleNotify( Composite control, String eventName, JsonObject properties ) { + if( eventName.equals( EVENT_PLAYBACK ) ) { + handlePlaybackMode( control, properties ); + } else if( eventName.equals( EVENT_PRESENTATION ) ) { + handlePresentationMode( control, properties ); + } else { + super.handleNotify( control, eventName, properties ); + } + } + + private void handlePlaybackMode( Widget widget, JsonObject properties ) { + String playbackMode = properties.get( PROPERTY_PLAYBACK ).asString(); + Playback newMode = Playback.valueOf( playbackMode.toUpperCase() ); + Video video = ( Video )widget; + video.getAdapter( PlaybackAdapter.class ).setPlaybackMode( newMode ); + notifyListenersAboutPlaybackModeChange( newMode, video ); + } + + private void notifyListenersAboutPlaybackModeChange( final Playback newMode, final Video video ) { + ProcessActionRunner.add( new Runnable() { + @Override + public void run() { + video.getAdapter( PlaybackAdapter.class ).firePlaybackChange( newMode ); + } + } ); + } + + private void handlePresentationMode( Widget widget, JsonObject properties ) { + String presentationMode = properties.get( PROPERTY_PRESENTATION ).asString(); + Presentation newMode = Presentation.valueOf( presentationMode.toUpperCase() ); + Video video = ( Video )widget; + video.getAdapter( PlaybackAdapter.class ).getOptions().put( PlaybackOptions.PRESENTATION, newMode ); + notifyListenersAboutPresentationModeChange( newMode, video ); + } + + private void notifyListenersAboutPresentationModeChange( final Presentation newMode, final Video video ) { + ProcessActionRunner.add( new Runnable() { + @Override + public void run() { + video.getAdapter( PlaybackAdapter.class ).firePresentationChange( newMode ); + } + } ); + } + } + private static Object jsonizeValue( Entry<PlaybackOptions, Object> entry ) { Object value = entry.getValue(); if( value instanceof Playback || value instanceof Presentation ) {
06b1f1ec2fc0bca8f4d6d5345cbf42777b4d89ff
kotlin
Smart completion: code improvements and- refactorings after code review--
p
https://github.com/JetBrains/kotlin
diff --git a/idea/src/org/jetbrains/jet/plugin/completion/CompletionSession.java b/idea/src/org/jetbrains/jet/plugin/completion/CompletionSession.java index c0ad01c314051..b6f90474e431d 100644 --- a/idea/src/org/jetbrains/jet/plugin/completion/CompletionSession.java +++ b/idea/src/org/jetbrains/jet/plugin/completion/CompletionSession.java @@ -16,6 +16,8 @@ package org.jetbrains.jet.plugin.completion; +import com.google.common.base.Predicate; +import com.google.common.collect.Collections2; import com.intellij.codeInsight.completion.CompletionParameters; import com.intellij.codeInsight.completion.CompletionResultSet; import com.intellij.codeInsight.completion.CompletionType; @@ -43,7 +45,6 @@ import org.jetbrains.jet.plugin.references.JetSimpleNameReference; import java.util.Collection; -import java.util.Collections; class CompletionSession { @Nullable @@ -52,13 +53,6 @@ class CompletionSession { private final JetCompletionResultSet jetResult; private final JetSimpleNameReference jetReference; - private final Condition<DeclarationDescriptor> descriptorFilter = new Condition<DeclarationDescriptor>() { - @Override - public boolean value(DeclarationDescriptor descriptor) { - return isVisibleDescriptor(descriptor); - } - }; - public CompletionSession( @NotNull CompletionParameters parameters, @NotNull CompletionResultSet result, @@ -75,10 +69,17 @@ public CompletionSession( inDescriptor = scope != null ? scope.getContainingDeclaration() : null; + Condition<DeclarationDescriptor> descriptorFilter = new Condition<DeclarationDescriptor>() { + @Override + public boolean value(DeclarationDescriptor descriptor) { + return isVisibleDescriptor(descriptor); + } + }; this.jetResult = new JetCompletionResultSet( WeigherPackage.addJetSorting(result, parameters), resolveSession, - expressionBindingContext, descriptorFilter); + expressionBindingContext, + descriptorFilter); } public void completeForReference() { @@ -134,20 +135,18 @@ public boolean value(DeclarationDescriptor descriptor) { public void completeSmart() { assert parameters.getCompletionType() == CompletionType.SMART; - final SmartCompletionData data = CompletionPackage.buildSmartCompletionData(jetReference.getExpression(), getResolveSession(), new Function1<DeclarationDescriptor, Boolean>() { + Collection<DeclarationDescriptor> descriptors = TipsManager.getReferenceVariants( + jetReference.getExpression(), getExpressionBindingContext()); + Function1<DeclarationDescriptor, Boolean> visibilityFilter = new Function1<DeclarationDescriptor, Boolean>() { @Override public Boolean invoke(DeclarationDescriptor descriptor) { return isVisibleDescriptor(descriptor); } - }); - if (data != null) { - addReferenceVariants(new Function1<DeclarationDescriptor, Iterable<LookupElement>>(){ - @Override - public Iterable<LookupElement> invoke(DeclarationDescriptor descriptor) { - return data.toElements(descriptor); - } - }); - for (LookupElement element : data.getAdditionalElements()) { + }; + Collection<LookupElement> elements = CompletionPackage.buildSmartCompletionData( + jetReference.getExpression(), getResolveSession(), descriptors, visibilityFilter); + if (elements != null) { + for (LookupElement element : elements) { jetResult.addElement(element); } } @@ -244,33 +243,21 @@ private boolean shouldRunTopLevelCompletion() { } private boolean shouldRunExtensionsCompletion() { - return !(parameters.getInvocationCount() <= 1 && jetResult.getResult().getPrefixMatcher().getPrefix().length() < 3); + return parameters.getInvocationCount() > 1 || jetResult.getResult().getPrefixMatcher().getPrefix().length() >= 3; } private void addReferenceVariants(@NotNull final Condition<DeclarationDescriptor> filterCondition) { - addReferenceVariants(new Function1<DeclarationDescriptor, Iterable<LookupElement>>(){ - @Override - public Iterable<LookupElement> invoke(DeclarationDescriptor descriptor) { - return filterCondition.value(descriptor) - ? Collections.singletonList( - DescriptorLookupConverter.createLookupElement(getResolveSession(), getExpressionBindingContext(), descriptor)) - : Collections.<LookupElement>emptyList(); - } - }); - } - - private void addReferenceVariants(@NotNull Function1<DeclarationDescriptor, Iterable<LookupElement>> filter) { Collection<DeclarationDescriptor> descriptors = TipsManager.getReferenceVariants( jetReference.getExpression(), getExpressionBindingContext()); - for (DeclarationDescriptor descriptor : descriptors) { - if (descriptor != null && descriptorFilter.value(descriptor)) { - Iterable<LookupElement> elements = filter.invoke(descriptor); - for (LookupElement element : elements) { - jetResult.addElement(element); - } + Collection<DeclarationDescriptor> filterDescriptors = Collections2.filter(descriptors, new Predicate<DeclarationDescriptor>() { + @Override + public boolean apply(@Nullable DeclarationDescriptor descriptor) { + return descriptor != null && filterCondition.value(descriptor); } - } + }); + + jetResult.addAllElements(filterDescriptors); } private boolean isVisibleDescriptor(DeclarationDescriptor descriptor) { diff --git a/idea/src/org/jetbrains/jet/plugin/completion/SmartCompletion.kt b/idea/src/org/jetbrains/jet/plugin/completion/SmartCompletion.kt index 3927afd51c0c9..1df1c07aac818 100644 --- a/idea/src/org/jetbrains/jet/plugin/completion/SmartCompletion.kt +++ b/idea/src/org/jetbrains/jet/plugin/completion/SmartCompletion.kt @@ -34,11 +34,6 @@ import org.jetbrains.jet.lang.resolve.scopes.receivers.ReceiverValue import com.intellij.lang.ASTNode import org.jetbrains.jet.lang.resolve.scopes.JetScope -trait SmartCompletionData{ - fun toElements(descriptor: DeclarationDescriptor): Iterable<LookupElement> - val additionalElements: Iterable<LookupElement> -} - enum class Tail { COMMA PARENTHESIS @@ -48,7 +43,8 @@ data class ExpectedTypeInfo(val `type`: JetType, val tail: Tail?) fun buildSmartCompletionData(expression: JetSimpleNameExpression, resolveSession: ResolveSessionForBodies, - visibilityFilter: (DeclarationDescriptor) -> Boolean): SmartCompletionData? { + referenceVariants: Iterable<DeclarationDescriptor>, + visibilityFilter: (DeclarationDescriptor) -> Boolean): Collection<LookupElement>? { val parent = expression.getParent() val expressionWithType: JetExpression; val receiver: JetExpression? @@ -67,104 +63,72 @@ fun buildSmartCompletionData(expression: JetSimpleNameExpression, val expectedTypes = allExpectedTypes.filter { !it.`type`.isError() } if (expectedTypes.isEmpty()) return null - val itemsToSkip = calcItemsToSkip(expressionWithType, resolveSession) - - val additionalElements = ArrayList<LookupElement>() - - if (receiver == null) { - additionalElements.addTypeInstantiationItems(expectedTypes, resolveSession, bindingContext) + val result = ArrayList<LookupElement>() - additionalElements.addStaticMembers(expressionWithType, expectedTypes, resolveSession, bindingContext) + val typesOf: (DeclarationDescriptor) -> Iterable<JetType> = dataFlowToDescriptorTypes(expressionWithType, receiver, bindingContext) - additionalElements.addThisItems(expressionWithType, expectedTypes, bindingContext) - } + val itemsToSkip = calcItemsToSkip(expressionWithType, resolveSession) - val dataFlowInfo = bindingContext[BindingContext.EXPRESSION_DATA_FLOW_INFO, expressionWithType] - val (variableToTypes: Map<VariableDescriptor, Collection<JetType>>, notNullVariables: Set<VariableDescriptor>) = processDataFlowInfo(dataFlowInfo, receiver, bindingContext) + for (descriptor in referenceVariants) { + if (itemsToSkip.contains(descriptor)) continue - fun typesOf(descriptor: DeclarationDescriptor): Iterable<JetType> { - if (descriptor is CallableDescriptor) { - var returnType = descriptor.getReturnType() - if (returnType != null && KotlinBuiltIns.getInstance().isNothing(returnType!!)) { //TODO: maybe we should include them on the second press? - return listOf() + run { + val matchedExpectedTypes = expectedTypes.filter { expectedType -> + typesOf(descriptor).any { descriptorType -> isSubtypeOf(descriptorType, expectedType.`type`) } } - if (descriptor is VariableDescriptor) { - if (notNullVariables.contains(descriptor) && returnType != null) { - returnType = TypeUtils.makeNotNullable(returnType!!) - } - - val autoCastTypes = variableToTypes[descriptor] - if (autoCastTypes != null && !autoCastTypes.isEmpty()) { - return autoCastTypes + returnType.toList() - } + if (matchedExpectedTypes.isNotEmpty()) { + val lookupElement = DescriptorLookupConverter.createLookupElement(resolveSession, bindingContext, descriptor) + result.add(addTailToLookupElement(lookupElement, matchedExpectedTypes)) } - return returnType.toList() - } - else if (descriptor is ClassDescriptor && descriptor.getKind() == ClassKind.ENUM_ENTRY) { - return listOf(descriptor.getDefaultType()) } - else { - return listOf() - } - } - return object: SmartCompletionData { - override fun toElements(descriptor: DeclarationDescriptor): Iterable<LookupElement> { - if (itemsToSkip.contains(descriptor)) return listOf() - - val result = ArrayList<LookupElement>() - - run { - val matchedExpectedTypes = expectedTypes.filter { expectedType -> typesOf(descriptor).any { descriptorType -> isSubtypeOf(descriptorType, expectedType.`type`) } } - if (matchedExpectedTypes.isNotEmpty()) { - val tail = mergeTails(matchedExpectedTypes.map { it.tail }) - result.add(addTailToLookupElement(DescriptorLookupConverter.createLookupElement(resolveSession, bindingContext, descriptor), tail)) - } - } - - val functionExpectedTypes = expectedTypes.filter { KotlinBuiltIns.getInstance().isExactFunctionOrExtensionFunctionType(it.`type`) } - if (functionExpectedTypes.isNotEmpty()) { - fun functionReferenceLookupElement(descriptor: FunctionDescriptor): LookupElement? { - val functionType = functionType(descriptor) - if (functionType == null) return null - - val matchedExpectedTypes = functionExpectedTypes.filter { isSubtypeOf(functionType, it.`type`) } - if (matchedExpectedTypes.isEmpty()) return null - val lookupElement = DescriptorLookupConverter.createLookupElement(resolveSession, bindingContext, descriptor) - val text = "::" + (if (descriptor is ConstructorDescriptor) descriptor.getContainingDeclaration().getName() else descriptor.getName()) - val lookupElementDecorated = object: LookupElementDecorator<LookupElement>(lookupElement) { - override fun getLookupString() = text - - override fun renderElement(presentation: LookupElementPresentation) { - super.renderElement(presentation) - presentation.setItemText(text) - presentation.setTypeText("") - } - - override fun handleInsert(context: InsertionContext) { - } + val functionExpectedTypes = expectedTypes.filter { KotlinBuiltIns.getInstance().isExactFunctionOrExtensionFunctionType(it.`type`) } + if (functionExpectedTypes.isNotEmpty()) { + fun functionReferenceLookupElement(descriptor: FunctionDescriptor): LookupElement? { + val functionType = functionType(descriptor) + if (functionType == null) return null + + val matchedExpectedTypes = functionExpectedTypes.filter { isSubtypeOf(functionType, it.`type`) } + if (matchedExpectedTypes.isEmpty()) return null + val lookupElement = DescriptorLookupConverter.createLookupElement(resolveSession, bindingContext, descriptor) + val text = "::" + (if (descriptor is ConstructorDescriptor) descriptor.getContainingDeclaration().getName() else descriptor.getName()) + val lookupElementDecorated = object: LookupElementDecorator<LookupElement>(lookupElement) { + override fun getLookupString() = text + + override fun renderElement(presentation: LookupElementPresentation) { + super.renderElement(presentation) + presentation.setItemText(text) + presentation.setTypeText("") } - val tail = mergeTails(matchedExpectedTypes.map { it.tail }) - return addTailToLookupElement(lookupElementDecorated, tail) - } - - if (descriptor is SimpleFunctionDescriptor) { - functionReferenceLookupElement(descriptor)?.let { result.add(it) } - } - else if (descriptor is ClassDescriptor && descriptor.getModality() != Modality.ABSTRACT) { - val constructors = descriptor.getConstructors().filter(visibilityFilter) - if (constructors.size == 1) { //TODO: this code is to be changed if overloads to start work after :: - functionReferenceLookupElement(constructors.single())?.let { result.add(it) } + override fun handleInsert(context: InsertionContext) { } } + + return addTailToLookupElement(lookupElementDecorated, matchedExpectedTypes) } - return result + if (descriptor is SimpleFunctionDescriptor) { + functionReferenceLookupElement(descriptor)?.let { result.add(it) } + } + else if (descriptor is ClassDescriptor && descriptor.getModality() != Modality.ABSTRACT) { + val constructors = descriptor.getConstructors().filter(visibilityFilter) + if (constructors.size == 1) { //TODO: this code is to be changed if overloads to start work after :: + functionReferenceLookupElement(constructors.single())?.let { result.add(it) } + } + } } + } + + if (receiver == null) { + result.addTypeInstantiationItems(expectedTypes, resolveSession, bindingContext) + + result.addStaticMembers(expressionWithType, expectedTypes, resolveSession, bindingContext) - override val additionalElements = additionalElements + result.addThisItems(expressionWithType, expectedTypes, bindingContext) } + + return result } private fun calcExpectedTypes(expressionWithType: JetExpression, bindingContext: BindingContext, moduleDescriptor: ModuleDescriptor): Collection<ExpectedTypeInfo>? { @@ -364,8 +328,7 @@ private fun MutableCollection<LookupElement>.addThisItems(context: JetExpression val qualifier = if (i == 0) null else thisQualifierName(receiver, bindingContext) ?: continue val expressionText = if (qualifier == null) "this" else "this@" + qualifier val lookupElement = LookupElementBuilder.create(expressionText).withTypeText(DescriptorRenderer.TEXT.renderType(thisType)) - val tailType = mergeTails(matchedExpectedTypes.map { it.tail }) - add(addTailToLookupElement(lookupElement, tailType)) + add(addTailToLookupElement(lookupElement, matchedExpectedTypes)) } } } @@ -388,6 +351,40 @@ private fun thisQualifierName(receiver: ReceiverParameterDescriptor, bindingCont ?.getReferencedName() } +private fun dataFlowToDescriptorTypes(expression: JetExpression, receiver: JetExpression?, bindingContext: BindingContext): (DeclarationDescriptor) -> Iterable<JetType> { + val dataFlowInfo = bindingContext[BindingContext.EXPRESSION_DATA_FLOW_INFO, expression] + val (variableToTypes: Map<VariableDescriptor, Collection<JetType>>, notNullVariables: Set<VariableDescriptor>) + = processDataFlowInfo(dataFlowInfo, receiver, bindingContext) + + fun typesOf(descriptor: DeclarationDescriptor): Iterable<JetType> { + if (descriptor is CallableDescriptor) { + var returnType = descriptor.getReturnType() + if (returnType != null && KotlinBuiltIns.getInstance().isNothing(returnType!!)) { //TODO: maybe we should include them on the second press? + return listOf() + } + if (descriptor is VariableDescriptor) { + if (notNullVariables.contains(descriptor) && returnType != null) { + returnType = TypeUtils.makeNotNullable(returnType!!) + } + + val autoCastTypes = variableToTypes[descriptor] + if (autoCastTypes != null && !autoCastTypes.isEmpty()) { + return autoCastTypes + returnType.toList() + } + } + return returnType.toList() + } + else if (descriptor is ClassDescriptor && descriptor.getKind() == ClassKind.ENUM_ENTRY) { + return listOf(descriptor.getDefaultType()) + } + else { + return listOf() + } + } + + return ::typesOf +} + private data class ProcessDataFlowInfoResult( val variableToTypes: Map<VariableDescriptor, Collection<JetType>> = Collections.emptyMap(), val notNullVariables: Set<VariableDescriptor> = Collections.emptySet() @@ -550,8 +547,7 @@ private fun MutableCollection<LookupElement>.addStaticMembers(classDescriptor: C } } - val tail = mergeTails(descriptorExpectedTypes.map { it.tail }) - add(addTailToLookupElement(lookupElementDecorated, tail)) + add(addTailToLookupElement(lookupElementDecorated, descriptorExpectedTypes)) } } @@ -578,6 +574,9 @@ private fun addTailToLookupElement(lookupElement: LookupElement, tail: Tail?): L } } +private fun addTailToLookupElement(lookupElement: LookupElement, expectedTypes: Collection<ExpectedTypeInfo>): LookupElement + = addTailToLookupElement(lookupElement, mergeTails(expectedTypes.map { it.tail })) + private fun functionType(function: FunctionDescriptor): JetType? { return KotlinBuiltIns.getInstance().getKFunctionType(function.getAnnotations(), null, diff --git a/idea/src/org/jetbrains/jet/plugin/completion/WithTailInsertHandler.kt b/idea/src/org/jetbrains/jet/plugin/completion/handlers/WithTailInsertHandler.kt similarity index 69% rename from idea/src/org/jetbrains/jet/plugin/completion/WithTailInsertHandler.kt rename to idea/src/org/jetbrains/jet/plugin/completion/handlers/WithTailInsertHandler.kt index 7986994773850..bfa508bf7cad7 100644 --- a/idea/src/org/jetbrains/jet/plugin/completion/WithTailInsertHandler.kt +++ b/idea/src/org/jetbrains/jet/plugin/completion/handlers/WithTailInsertHandler.kt @@ -1,9 +1,8 @@ -package org.jetbrains.jet.plugin.completion +package org.jetbrains.jet.plugin.completion.handlers -import com.intellij.codeInsight.lookup.* import com.intellij.codeInsight.completion.* -import com.intellij.openapi.editor.event.DocumentListener -import com.intellij.openapi.editor.event.DocumentEvent +import com.intellij.codeInsight.lookup.LookupElement +import com.intellij.openapi.editor.event.* import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager @@ -29,18 +28,22 @@ class WithTailInsertHandler(val tailChar: Char, val spaceAfter: Boolean) : Inser } document.addDocumentListener(documentListener) - - item.handleInsert(context) - PsiDocumentManager.getInstance(context.getProject()).doPostponedOperationsAndUnblockDocument(document) - - document.removeDocumentListener(documentListener) + try{ + item.handleInsert(context) + PsiDocumentManager.getInstance(context.getProject()).doPostponedOperationsAndUnblockDocument(document) + } + finally { + document.removeDocumentListener(documentListener) + } val moveCaret = caretModel.getOffset() == maxChangeOffset - if (maxChangeOffset < document.getTextLength() && document.getText(TextRange(maxChangeOffset, maxChangeOffset + 1))[0] == tailChar) { + fun isCharAt(offset: Int, c: Char) = offset < document.getTextLength() && document.getText(TextRange(offset, offset + 1))[0] == c + + if (isCharAt(maxChangeOffset, tailChar)) { document.deleteString(maxChangeOffset, maxChangeOffset + 1) - if (spaceAfter && maxChangeOffset < document.getTextLength() && document.getText(TextRange(maxChangeOffset, maxChangeOffset + 1)) == " ") { + if (spaceAfter && isCharAt(maxChangeOffset, ' ')) { document.deleteString(maxChangeOffset, maxChangeOffset + 1) } }
25b42d9807047c9d58eb2035f38554383de318d7
tapiji
Fixes minor bugs
c
https://github.com/tapiji/tapiji
diff --git a/org.eclipselabs.tapiji.tools.jsf/plugin.xml b/org.eclipselabs.tapiji.tools.jsf/plugin.xml index 6c7bf706..090b7fcd 100644 --- a/org.eclipselabs.tapiji.tools.jsf/plugin.xml +++ b/org.eclipselabs.tapiji.tools.jsf/plugin.xml @@ -21,7 +21,7 @@ <extension point="org.eclipse.ui.ide.markerResolution"> <markerResolutionGenerator - class="org.eclipselabs.tapiji.tools.jsf.builder.JSFViolationResolutionGenerator" + class="quickfix.JSFViolationResolutionGenerator" markerType="org.eclipse.jst.jsf.ui.JSPSemanticsValidatorMarker"> </markerResolutionGenerator> </extension> diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java index bced7ad7..b60d946c 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java @@ -35,7 +35,7 @@ public Image getImage() { @Override public String getLabel() { - return "Export to resource bundle"; + return "Export to Resource-Bundle"; } @Override @@ -79,8 +79,8 @@ public void run(IMarker marker) { int quoteSingleIdx = document.get().substring(0, startPos).lastIndexOf ("'"); String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'"; - document.replace(startPos, endPos, bundleVar + "[" + quoteSign + - key + quoteSign + "]"); + document.replace(startPos, endPos, "#{" + bundleVar + "[" + quoteSign + + key + quoteSign + "]}"); } else { document.replace(startPos, endPos, "#{" + bundleVar + "." + key +"}"); } diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java new file mode 100644 index 00000000..7618d69d --- /dev/null +++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java @@ -0,0 +1,16 @@ +package quickfix; + +import org.eclipse.core.resources.IMarker; +import org.eclipse.ui.IMarkerResolution; +import org.eclipse.ui.IMarkerResolutionGenerator; + +public class JSFViolationResolutionGenerator implements + IMarkerResolutionGenerator { + + @Override + public IMarkerResolution[] getResolutions(IMarker marker) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java index e165e8ba..5b6eae5c 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java @@ -14,8 +14,6 @@ import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IMarkerResolution2; -import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; -import org.eclipselabs.tapiji.tools.core.ui.dialogs.InsertResourceBundleReferenceDialog; import org.eclipselabs.tapiji.tools.core.ui.dialogs.ResourceBundleSelectionDialog; diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java index c2f2c6ca..0e3d98f4 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java @@ -15,7 +15,7 @@ import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IMarkerResolution2; import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; -import org.eclipselabs.tapiji.tools.core.ui.dialogs.InsertResourceBundleReferenceDialog; +import org.eclipselabs.tapiji.tools.core.ui.dialogs.ResourceBundleEntrySelectionDialog; import auditor.JSFResourceBundleDetector; @@ -23,7 +23,7 @@ public class ReplaceResourceBundleReference implements IMarkerResolution2 { private String key; private String bundleId; - + public ReplaceResourceBundleReference(String key, String bundleId) { this.key = key; this.bundleId = bundleId; @@ -52,37 +52,43 @@ public void run(IMarker marker) { int startPos = marker.getAttribute(IMarker.CHAR_START, 0); int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos; IResource resource = marker.getResource(); - - ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager(); - IPath path = resource.getRawLocation(); + + ITextFileBufferManager bufferManager = FileBuffers + .getTextFileBufferManager(); + IPath path = resource.getRawLocation(); try { - bufferManager.connect(path, null); - ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path); - IDocument document = textFileBuffer.getDocument(); - - InsertResourceBundleReferenceDialog dialog = new InsertResourceBundleReferenceDialog( + bufferManager.connect(path, null); + ITextFileBuffer textFileBuffer = bufferManager + .getTextFileBuffer(path); + IDocument document = textFileBuffer.getDocument(); + + ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog( Display.getDefault().getActiveShell(), ResourceBundleManager.getManager(resource.getProject()), bundleId); if (dialog.open() != InputDialog.OK) return; - + String key = dialog.getSelectedResource(); Locale locale = dialog.getSelectedLocale(); - - String jsfBundleVar = JSFResourceBundleDetector.getBundleVariableName(document.get().substring(startPos, startPos + endPos)); - + + String jsfBundleVar = JSFResourceBundleDetector + .getBundleVariableName(document.get().substring(startPos, + startPos + endPos)); + if (key.indexOf(".") >= 0) { - int quoteDblIdx = document.get().substring(0, startPos).lastIndexOf("\""); - int quoteSingleIdx = document.get().substring(0, startPos).lastIndexOf ("'"); + int quoteDblIdx = document.get().substring(0, startPos) + .lastIndexOf("\""); + int quoteSingleIdx = document.get().substring(0, startPos) + .lastIndexOf("'"); String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'"; - - document.replace(startPos, endPos, jsfBundleVar + "[" + quoteSign + - key + quoteSign + "]"); + + document.replace(startPos, endPos, jsfBundleVar + "[" + + quoteSign + key + quoteSign + "]"); } else { document.replace(startPos, endPos, jsfBundleVar + "." + key); } - + textFileBuffer.commit(null, false); } catch (Exception e) { e.printStackTrace(); @@ -91,7 +97,7 @@ public void run(IMarker marker) { bufferManager.disconnect(path, null); } catch (CoreException e) { e.printStackTrace(); - } + } } } diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java index 797c1e87..401a67ab 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java @@ -23,15 +23,17 @@ public class NewResourceBundleEntryProposal implements IJavaCompletionProposal { private IResource resource; private String bundleName; private String reference; + private boolean isKey; public NewResourceBundleEntryProposal(IResource resource, String str, int startPos, int endPos, - ResourceBundleManager manager, String bundleName) { + ResourceBundleManager manager, String bundleName, boolean isKey) { this.startPos = startPos; this.endPos = endPos; this.manager = manager; this.value = str; this.resource = resource; this.bundleName = bundleName; + this.isKey = isKey; } @Override @@ -39,8 +41,8 @@ public void apply(IDocument document) { CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( Display.getDefault().getActiveShell(), manager, - "", - value, + isKey ? value : "", + !isKey ? value : "", bundleName == null ? "" : bundleName, ""); if (dialog.open() != InputDialog.OK) @@ -76,11 +78,16 @@ public IContextInformation getContextInformation() { @Override public String getDisplayString() { String displayStr = ""; - displayStr = "Create a new localized string literal"; - if (value != null && value.length() > 0) - displayStr += " for '" + value + "'"; + displayStr = "Create a new localized string literal"; + if (this.isKey) { + if (value != null && value.length() > 0) + displayStr += " with the key '" + value + "'"; + } else { + if (value != null && value.length() > 0) + displayStr += " for '" + value + "'"; + } return displayStr; } diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java index cf9fcdc4..6b4c63e6 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java @@ -59,7 +59,7 @@ public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int length = key.length(); proposals.add(new NewResourceBundleEntryProposal(resource, key, startpos, length, ResourceBundleManager.getManager(project) - , bundleId)); + , bundleId, true)); } return proposals.toArray(new ICompletionProposal[proposals.size()]);
d616c6056add234aad29168ad1eca3a1cc14cd08
apache$mina
Related issue: DIRMINA-495 (IoConnector needs a way to store information into the IoSession before the IoHandler gets ahold of it) * Changed IoSessionInitializer<ConnectFuture> to IoSessionInitializer<? extends ConnectFuture> for more API flexibility * Introduced @SuppressWarning inevitably eek! git-svn-id: https://svn.apache.org/repos/asf/mina/trunk@607163 13f79535-47bb-0310-9956-ffa450edef68
p
https://github.com/apache/mina
diff --git a/core/src/main/java/org/apache/mina/common/AbstractIoConnector.java b/core/src/main/java/org/apache/mina/common/AbstractIoConnector.java index cfe7f16e3..2eb0e9c88 100644 --- a/core/src/main/java/org/apache/mina/common/AbstractIoConnector.java +++ b/core/src/main/java/org/apache/mina/common/AbstractIoConnector.java @@ -80,13 +80,13 @@ public final ConnectFuture connect() { return connect(defaultRemoteAddress, null, null); } - public ConnectFuture connect(IoSessionInitializer<ConnectFuture> ioSessionInitializer) { + public ConnectFuture connect(IoSessionInitializer<? extends ConnectFuture> sessionInitializer) { SocketAddress defaultRemoteAddress = getDefaultRemoteAddress(); if (defaultRemoteAddress == null) { throw new IllegalStateException("defaultRemoteAddress is not set."); } - return connect(defaultRemoteAddress, null, ioSessionInitializer); + return connect(defaultRemoteAddress, null, sessionInitializer); } public final ConnectFuture connect(SocketAddress remoteAddress) { @@ -94,8 +94,8 @@ public final ConnectFuture connect(SocketAddress remoteAddress) { } public ConnectFuture connect(SocketAddress remoteAddress, - IoSessionInitializer<ConnectFuture> callback) { - return connect(remoteAddress, null, callback); + IoSessionInitializer<? extends ConnectFuture> sessionInitializer) { + return connect(remoteAddress, null, sessionInitializer); } public ConnectFuture connect(SocketAddress remoteAddress, @@ -104,7 +104,7 @@ public ConnectFuture connect(SocketAddress remoteAddress, } public final ConnectFuture connect(SocketAddress remoteAddress, - SocketAddress localAddress, IoSessionInitializer<ConnectFuture> ioSessionInitializer) { + SocketAddress localAddress, IoSessionInitializer<? extends ConnectFuture> sessionInitializer) { if (isDisposing()) { throw new IllegalStateException("Already disposed."); } @@ -164,7 +164,7 @@ public void sessionOpened(IoSession session) } } - return connect0(remoteAddress, localAddress, ioSessionInitializer); + return connect0(remoteAddress, localAddress, sessionInitializer); } /** @@ -173,7 +173,7 @@ public void sessionOpened(IoSession session) * @param localAddress <tt>null</tt> if no local address is specified */ protected abstract ConnectFuture connect0(SocketAddress remoteAddress, - SocketAddress localAddress, IoSessionInitializer<ConnectFuture> ioSessionInitializer); + SocketAddress localAddress, IoSessionInitializer<? extends ConnectFuture> sessionInitializer); /** * Adds required internal attributes and {@link IoFutureListener}s diff --git a/core/src/main/java/org/apache/mina/common/AbstractIoService.java b/core/src/main/java/org/apache/mina/common/AbstractIoService.java index ff9420e7e..004a211bd 100644 --- a/core/src/main/java/org/apache/mina/common/AbstractIoService.java +++ b/core/src/main/java/org/apache/mina/common/AbstractIoService.java @@ -703,7 +703,10 @@ protected final IoServiceListenerSupport getListeners() { return listeners; } - protected final <T extends IoFuture> void finishSessionInitialization(IoSession session, T future, IoSessionInitializer<T> ioSessionInitializer) { + // TODO Figure out make it work without causing a compiler error / warning. + @SuppressWarnings("unchecked") + protected final void finishSessionInitialization( + IoSession session, IoFuture future, IoSessionInitializer sessionInitializer) { // Update lastIoTime if needed. if (getLastReadTime() == 0) { setLastReadTime(getActivationTime()); @@ -741,8 +744,8 @@ protected final <T extends IoFuture> void finishSessionInitialization(IoSession session.setAttribute(DefaultIoFilterChain.SESSION_OPENED_FUTURE, future); } - if (ioSessionInitializer != null) { - ioSessionInitializer.initializeSession(session, future); + if (sessionInitializer != null) { + sessionInitializer.initializeSession(session, future); } finishSessionInitialization0(session, future); diff --git a/core/src/main/java/org/apache/mina/common/AbstractPollingIoConnector.java b/core/src/main/java/org/apache/mina/common/AbstractPollingIoConnector.java index 155b35485..71fd014f0 100644 --- a/core/src/main/java/org/apache/mina/common/AbstractPollingIoConnector.java +++ b/core/src/main/java/org/apache/mina/common/AbstractPollingIoConnector.java @@ -145,8 +145,9 @@ protected final IoFuture dispose0() throws Exception { @Override @SuppressWarnings("unchecked") - protected final ConnectFuture connect0(SocketAddress remoteAddress, - SocketAddress localAddress, IoSessionInitializer<ConnectFuture> callback) { + protected final ConnectFuture connect0( + SocketAddress remoteAddress, SocketAddress localAddress, + IoSessionInitializer<? extends ConnectFuture> sessionInitializer) { H handle = null; boolean success = false; try { @@ -154,7 +155,7 @@ protected final ConnectFuture connect0(SocketAddress remoteAddress, if (connect(handle, remoteAddress)) { ConnectFuture future = new DefaultConnectFuture(); T session = newSession(processor, handle); - finishSessionInitialization(session, future, callback); + finishSessionInitialization(session, future, sessionInitializer); // Forward the remaining process to the IoProcessor. session.getProcessor().add(session); success = true; @@ -174,7 +175,7 @@ protected final ConnectFuture connect0(SocketAddress remoteAddress, } } - ConnectionRequest request = new ConnectionRequest(handle, callback); + ConnectionRequest request = new ConnectionRequest(handle, sessionInitializer); connectQueue.add(request); startupWorker(); wakeup(); @@ -252,7 +253,7 @@ private int processSessions(Iterator<H> handlers) { try { if (finishConnect(handle)) { T session = newSession(processor, handle); - finishSessionInitialization(session, entry, entry.getSessionCallback()); + finishSessionInitialization(session, entry, entry.getSessionInitializer()); // Forward the remaining process to the IoProcessor. session.getProcessor().add(session); nHandles ++; @@ -346,9 +347,9 @@ public void run() { protected final class ConnectionRequest extends DefaultConnectFuture { private final H handle; private final long deadline; - private final IoSessionInitializer<ConnectFuture> ioSessionInitializer; + private final IoSessionInitializer<? extends ConnectFuture> sessionInitializer; - public ConnectionRequest(H handle, IoSessionInitializer<ConnectFuture> callback) { + public ConnectionRequest(H handle, IoSessionInitializer<? extends ConnectFuture> callback) { this.handle = handle; long timeout = getConnectTimeoutMillis(); if (timeout <= 0L) { @@ -356,7 +357,7 @@ public ConnectionRequest(H handle, IoSessionInitializer<ConnectFuture> callback) } else { this.deadline = System.currentTimeMillis() + timeout; } - this.ioSessionInitializer = callback; + this.sessionInitializer = callback; } public H getHandle() { @@ -367,8 +368,8 @@ public long getDeadline() { return deadline; } - public IoSessionInitializer<ConnectFuture> getSessionCallback() { - return ioSessionInitializer; + public IoSessionInitializer<? extends ConnectFuture> getSessionInitializer() { + return sessionInitializer; } @Override diff --git a/core/src/main/java/org/apache/mina/common/IoConnector.java b/core/src/main/java/org/apache/mina/common/IoConnector.java index c271fac83..e71e3fdfe 100644 --- a/core/src/main/java/org/apache/mina/common/IoConnector.java +++ b/core/src/main/java/org/apache/mina/common/IoConnector.java @@ -82,11 +82,11 @@ public interface IoConnector extends IoService { * is invoked. There is <em>no</em> guarantee that the <code>ioSessionInitializer</code> * will be invoked before this method returns. * - * @param ioSessionInitializer the callback to invoke when the {@link IoSession} object is created + * @param sessionInitializer the callback to invoke when the {@link IoSession} object is created * * @throws IllegalStateException if no default remote address is set. */ - ConnectFuture connect(IoSessionInitializer<ConnectFuture> ioSessionInitializer); + ConnectFuture connect(IoSessionInitializer<? extends ConnectFuture> sessionInitializer); /** * Connects to the specified remote address. @@ -104,12 +104,12 @@ public interface IoConnector extends IoService { * this method returns. * * @param remoteAddress the remote address to connect to - * @param ioSessionInitializer the callback to invoke when the {@link IoSession} object is created + * @param sessionInitializer the callback to invoke when the {@link IoSession} object is created * * @return the {@link ConnectFuture} instance which is completed when the * connection attempt initiated by this call succeeds or fails. */ - ConnectFuture connect(SocketAddress remoteAddress, IoSessionInitializer<ConnectFuture> ioSessionInitializer); + ConnectFuture connect(SocketAddress remoteAddress, IoSessionInitializer<? extends ConnectFuture> sessionInitializer); /** * Connects to the specified remote address binding to the specified local address. @@ -117,8 +117,7 @@ public interface IoConnector extends IoService { * @return the {@link ConnectFuture} instance which is completed when the * connection attempt initiated by this call succeeds or fails. */ - ConnectFuture connect(SocketAddress remoteAddress, - SocketAddress localAddress); + ConnectFuture connect(SocketAddress remoteAddress, SocketAddress localAddress); /** * Connects to the specified remote address binding to the specified local @@ -129,11 +128,11 @@ ConnectFuture connect(SocketAddress remoteAddress, * * @param remoteAddress the remote address to connect to * @param localAddress the local interface to bind to - * @param ioSessionInitializer the callback to invoke when the {@link IoSession} object is created + * @param sessionInitializer the callback to invoke when the {@link IoSession} object is created * * @return the {@link ConnectFuture} instance which is completed when the * connection attempt initiated by this call succeeds or fails. */ ConnectFuture connect(SocketAddress remoteAddress, - SocketAddress localAddress, IoSessionInitializer<ConnectFuture> ioSessionInitializer); + SocketAddress localAddress, IoSessionInitializer<? extends ConnectFuture> sessionInitializer); } \ No newline at end of file diff --git a/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeConnector.java b/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeConnector.java index e8b7fe12b..d86f39ac7 100644 --- a/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeConnector.java +++ b/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeConnector.java @@ -64,7 +64,7 @@ public VmPipeSessionConfig getSessionConfig() { @Override protected ConnectFuture connect0(SocketAddress remoteAddress, SocketAddress localAddress, - IoSessionInitializer<ConnectFuture> ioSessionInitializer) { + IoSessionInitializer<? extends ConnectFuture> sessionInitializer) { VmPipe entry = VmPipeAcceptor.boundHandlers.get(remoteAddress); if (entry == null) { return DefaultConnectFuture.newFailedFuture(new IOException( @@ -84,7 +84,7 @@ protected ConnectFuture connect0(SocketAddress remoteAddress, VmPipeSessionImpl localSession = new VmPipeSessionImpl(this, getListeners(), actualLocalAddress, getHandler(), entry); - finishSessionInitialization(localSession, future, ioSessionInitializer); + finishSessionInitialization(localSession, future, sessionInitializer); // and reclaim the local address when the connection is closed. localSession.getCloseFuture().addListener(LOCAL_ADDRESS_RECLAIMER); diff --git a/transport-serial/src/main/java/org/apache/mina/transport/serial/SerialConnector.java b/transport-serial/src/main/java/org/apache/mina/transport/serial/SerialConnector.java index 4589ba91c..b3ee1f310 100644 --- a/transport-serial/src/main/java/org/apache/mina/transport/serial/SerialConnector.java +++ b/transport-serial/src/main/java/org/apache/mina/transport/serial/SerialConnector.java @@ -54,8 +54,9 @@ public SerialConnector() { } @Override - protected ConnectFuture connect0(SocketAddress remoteAddress, - SocketAddress localAddress, IoSessionInitializer<ConnectFuture> ioSessionInitializer) { + protected ConnectFuture connect0( + SocketAddress remoteAddress, SocketAddress localAddress, + IoSessionInitializer<? extends ConnectFuture> sessionInitializer) { CommPortIdentifier portId; Enumeration<?> portList = CommPortIdentifier.getPortIdentifiers(); @@ -83,7 +84,7 @@ protected ConnectFuture connect0(SocketAddress remoteAddress, ConnectFuture future = new DefaultConnectFuture(); SerialSessionImpl session = new SerialSessionImpl( this, getListeners(), portAddress, serialPort); - finishSessionInitialization(session, future, ioSessionInitializer); + finishSessionInitialization(session, future, sessionInitializer); session.start(); return future; } catch (PortInUseException e) {
fac86445f596bd7d688b5a25ae1d61840bfd9ecb
Delta Spike
fix broken unit test when testing remote containers
c
https://github.com/apache/deltaspike
diff --git a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java index 6aa81dae6..1f23a211c 100644 --- a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java +++ b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java @@ -23,6 +23,7 @@ import org.apache.deltaspike.core.spi.config.ConfigFilter; import org.apache.deltaspike.core.util.ProjectStageProducer; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; import java.util.List; @@ -30,6 +31,13 @@ public class ConfigResolverTest { private static final String DEFAULT_VALUE = "defaultValue"; + + @Before + public void init() + { + ProjectStageProducer.setProjectStage(ProjectStage.UnitTest); + } + @Test public void testOverruledValue() {
d065328e1522270f60fc9039f184c958ed7f053f
frontlinesms-credit$plugin-paymentview
delete client functionality -> active field set to false
p
https://github.com/frontlinesms-credit/plugin-paymentview
diff --git a/src/main/java/org/creditsms/plugins/paymentview/data/domain/Client.java b/src/main/java/org/creditsms/plugins/paymentview/data/domain/Client.java index 3a5d8af6..7726fc57 100644 --- a/src/main/java/org/creditsms/plugins/paymentview/data/domain/Client.java +++ b/src/main/java/org/creditsms/plugins/paymentview/data/domain/Client.java @@ -27,6 +27,7 @@ public class Client { private static final String FIELD_FIRST_NAME = "firstName"; private static final String FIELD_OTHER_NAME = "otherName"; private static final String FIELD_PHONE_NUMBER = "phoneNumber"; + private static final String FIELD_ACTIVE = "active"; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -42,6 +43,9 @@ public class Client { @Column(name = FIELD_PHONE_NUMBER, nullable = false, unique = true) private String phoneNumber; + + @Column(name = FIELD_ACTIVE) + private boolean active = true; //@OneToMany(fetch = FetchType.EAGER) //private Set<Account> accounts = new HashSet<Account>(); @@ -53,7 +57,8 @@ public enum Field implements EntityField<Client> { ID(FIELD_ID), FIRST_NAME(FIELD_FIRST_NAME), OTHER_NAME(FIELD_OTHER_NAME), - PHONE_NUMBER(FIELD_PHONE_NUMBER); + PHONE_NUMBER(FIELD_PHONE_NUMBER), + ACTIVE(FIELD_ACTIVE); /** name of a field */ private final String fieldName; @@ -121,6 +126,14 @@ public String getPhoneNumber() { return phoneNumber; } + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; + } + @Override public int hashCode() { final int prime = 31; diff --git a/src/main/java/org/creditsms/plugins/paymentview/data/repository/ClientDao.java b/src/main/java/org/creditsms/plugins/paymentview/data/repository/ClientDao.java index 885aedc5..b63cd869 100644 --- a/src/main/java/org/creditsms/plugins/paymentview/data/repository/ClientDao.java +++ b/src/main/java/org/creditsms/plugins/paymentview/data/repository/ClientDao.java @@ -28,6 +28,18 @@ public interface ClientDao { * @return */ public List<Client> getAllClients(int startIndex, int limit); + + /** + * Returns all active clients from a particular start index with a maximum number + * of returned clients set. + * + * @param startIndex + * index of the first client to fetch + * @param limit + * Maximum number of clients to fetch from the start index + * @return + */ + public List<Client> getAllActiveClients(int startIndex, int limit); /** * Returns a client with the same id as the passed id diff --git a/src/main/java/org/creditsms/plugins/paymentview/data/repository/hibernate/HibernateClientDao.java b/src/main/java/org/creditsms/plugins/paymentview/data/repository/hibernate/HibernateClientDao.java index a5ac8d43..11436742 100644 --- a/src/main/java/org/creditsms/plugins/paymentview/data/repository/hibernate/HibernateClientDao.java +++ b/src/main/java/org/creditsms/plugins/paymentview/data/repository/hibernate/HibernateClientDao.java @@ -5,6 +5,7 @@ import net.frontlinesms.data.repository.hibernate.BaseHibernateDao; import org.creditsms.plugins.paymentview.data.domain.Client; +import org.creditsms.plugins.paymentview.data.domain.CustomField; import org.creditsms.plugins.paymentview.data.repository.ClientDao; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.MatchMode; @@ -40,9 +41,9 @@ public Client getClientByPhoneNumber(String phoneNumber) { criteria.add(Restrictions.eq("phoneNumber", phoneNumber)); return super.getUnique(criteria); } - + public int getClientCount() { - return super.getAll().size(); + return getAllActiveClients().size(); } public List<Client> getClientsByName(String clientName) { @@ -52,7 +53,9 @@ public List<Client> getClientsByName(String clientName) { .add(Restrictions.ilike("firstName", clientName.trim(), MatchMode.ANYWHERE)) .add(Restrictions.ilike("otherName", clientName.trim(), - MatchMode.ANYWHERE))); + MatchMode.ANYWHERE)) + .add(Restrictions.eq(Client.Field.ACTIVE.getFieldName(), + Boolean.TRUE))); return super.getList(criteria); } @@ -64,7 +67,24 @@ public List<Client> getClientsByName(String clientName, int startIndex, .add(Restrictions.ilike("firstName", clientName.trim(), MatchMode.ANYWHERE)) .add(Restrictions.ilike("otherName", clientName.trim(), - MatchMode.ANYWHERE))); + MatchMode.ANYWHERE)) + .add(Restrictions.eq(Client.Field.ACTIVE.getFieldName(), + Boolean.TRUE))); + return super.getList(criteria, startIndex, limit); + } + + public List<Client> getAllActiveClients() { + DetachedCriteria criteria = super.getCriterion(); + criteria.add(Restrictions.eq(Client.Field.ACTIVE.getFieldName(), + Boolean.TRUE)); + return super.getList(criteria); + } + + public List<Client> getAllActiveClients(int startIndex, + int limit) { + DetachedCriteria criteria = super.getCriterion(); + criteria.add(Restrictions.eq(Client.Field.ACTIVE.getFieldName(), + Boolean.TRUE)); return super.getList(criteria, startIndex, limit); } diff --git a/src/main/java/org/creditsms/plugins/paymentview/data/repository/hibernate/HibernateOutgoingPaymentDao.java b/src/main/java/org/creditsms/plugins/paymentview/data/repository/hibernate/HibernateOutgoingPaymentDao.java index 77258cd4..aef21e21 100644 --- a/src/main/java/org/creditsms/plugins/paymentview/data/repository/hibernate/HibernateOutgoingPaymentDao.java +++ b/src/main/java/org/creditsms/plugins/paymentview/data/repository/hibernate/HibernateOutgoingPaymentDao.java @@ -9,9 +9,11 @@ import net.frontlinesms.data.Order; import net.frontlinesms.data.repository.hibernate.BaseHibernateDao; +import org.creditsms.plugins.paymentview.data.domain.Client; import org.creditsms.plugins.paymentview.data.domain.OutgoingPayment; import org.creditsms.plugins.paymentview.data.repository.OutgoingPaymentDao; import org.hibernate.criterion.DetachedCriteria; +import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Restrictions; public class HibernateOutgoingPaymentDao extends @@ -31,13 +33,17 @@ public List<OutgoingPayment> getAllOutgoingPayments() { public List<OutgoingPayment> getAllOutgoingPayments(int startIndex, int limit) { - return super.getAll(startIndex, limit); + DetachedCriteria criteria = super.getCriterion(); + DetachedCriteria clientCriteria = criteria.createCriteria("client"); + clientCriteria.add(Restrictions.eq("active", + Boolean.TRUE)); + return super.getList(criteria, startIndex, limit); } public int getOutgoingPaymentsCount() { return super.countAll(); } - + public List<OutgoingPayment> getOutgoingPaymentsByClientId(long clientId) { DetachedCriteria criteria = super.getCriterion(); DetachedCriteria clientCriteria = criteria.createCriteria("client"); @@ -86,7 +92,11 @@ public List<OutgoingPayment> getOutgoingPaymentsByDateRange( public List<OutgoingPayment> getOutgoingPaymentsByPhoneNo(String phoneNo) { DetachedCriteria criteria = super.getCriterion(); DetachedCriteria clientCriteria = criteria.createCriteria("client"); - clientCriteria.add(Restrictions.eq("phoneNumber", phoneNo)); + clientCriteria.add(Restrictions + .disjunction() + .add(Restrictions.eq("phoneNumber", phoneNo)) + .add(Restrictions.eq(Client.Field.ACTIVE.getFieldName(), + Boolean.TRUE))); return super.getList(criteria); } diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/BaseClientTable.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/BaseClientTable.java index f0249531..111e49b7 100644 --- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/BaseClientTable.java +++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/BaseClientTable.java @@ -84,7 +84,7 @@ protected List<Client> getClients(String filter, int startIndex, int limit) { if (!filter.trim().isEmpty()) { return this.clientDao.getClientsByName(filter, startIndex, limit); }else{ - return this.clientDao.getAllClients(startIndex, limit); + return this.clientDao.getAllActiveClients(startIndex, limit); } }else{ //FIXME: Make this stable diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabanalytics/innertabs/steps/viewdashboard/SelectTargetSavingsHandler.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabanalytics/innertabs/steps/viewdashboard/SelectTargetSavingsHandler.java index 465e6689..8d5b3814 100644 --- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabanalytics/innertabs/steps/viewdashboard/SelectTargetSavingsHandler.java +++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabanalytics/innertabs/steps/viewdashboard/SelectTargetSavingsHandler.java @@ -71,7 +71,9 @@ public void next() { for(Target target : targets){ Account a = target.getAccount(); if ((a != null) & (a.getClient() != null)) { - clients_serviceItems.put(a.getClient(), target.getServiceItem()); + if (a.getClient().isActive()){ + clients_serviceItems.put(a.getClient(), target.getServiceItem()); + } } } viewDashBoardTabHandler.setCurrentStepPanel(new SelectClientsHandler( diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/ClientTableHandler.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/ClientTableHandler.java index acee7371..c9617d07 100644 --- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/ClientTableHandler.java +++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/ClientTableHandler.java @@ -1,5 +1,4 @@ package org.creditsms.plugins.paymentview.ui.handler.tabclients; - import net.frontlinesms.ui.UiGeneratorController; import org.creditsms.plugins.paymentview.PaymentViewPluginController; diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/ClientsTabHandler.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/ClientsTabHandler.java index 6b1a2217..aa628704 100644 --- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/ClientsTabHandler.java +++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/ClientsTabHandler.java @@ -3,12 +3,14 @@ import java.util.ArrayList; import java.util.List; +import net.frontlinesms.data.DuplicateKeyException; import net.frontlinesms.ui.ThinletUiEventHandler; import net.frontlinesms.ui.UiGeneratorController; import net.frontlinesms.ui.UiGeneratorControllerConstants; import org.creditsms.plugins.paymentview.PaymentViewPluginController; import org.creditsms.plugins.paymentview.data.domain.Client; +import org.creditsms.plugins.paymentview.data.domain.CustomField; import org.creditsms.plugins.paymentview.data.repository.ClientDao; import org.creditsms.plugins.paymentview.data.repository.CustomFieldDao; import org.creditsms.plugins.paymentview.data.repository.CustomValueDao; @@ -72,16 +74,16 @@ public void customizeClientDB() { } public void deleteClient() { - Object[] selectedClients = this.ui - .getSelectedItems(clientsTableComponent); + Object[] selectedClients = this.ui.getSelectedItems(clientsTableComponent); for (Object selectedClient : selectedClients) { - Client c = ui.getAttachedObject(selectedClient, Client.class); - clientDao.deleteClient(c); + Client attachedClient = ui.getAttachedObject(selectedClient, Client.class); + attachedClient.setActive(false); + clientDao.updateClient(attachedClient); } ui.removeDialog(ui .find(UiGeneratorControllerConstants.COMPONENT_CONFIRM_DIALOG)); - ui.infoMessage("You have succesfully deleted from the client!"); + ui.infoMessage("You have successfully deleted client."); this.refresh(); } diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/dialogs/EditClientHandler.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/dialogs/EditClientHandler.java index 5126a755..b5c0be9d 100644 --- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/dialogs/EditClientHandler.java +++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/tabclients/dialogs/EditClientHandler.java @@ -209,8 +209,19 @@ public void saveClient() { String phone = ui.getText(fieldPhoneNumber); //test if phoneNumber already linked to another client Client clientInDb = clientDao.getClientByPhoneNumber(phone); - if (clientInDb!=null){ - ui.infoMessage("The phone number " + phone + " is already set up for "+ clientInDb.getFullName() + "."); + if (clientInDb!=null ){ + if (clientInDb.isActive()){ + ui.infoMessage("The phone number " + phone + " is already set up for "+ clientInDb.getFullName() + "."); + } else { + //TODO: Make sure that the user is active if we add a client that has same phone number... + //ui.showConfirmationDialog("An inactive client with this phone number '" + phone + "' exists." + + // "Would you like to reactivate it?", "", this); + removeDialog(); + ui.infoMessage("The phone number " + phone + " was previously set up for "+ clientInDb.getFullName() + " and will be reactivated."); + clientInDb.setActive(true); + this.clientDao.updateClient(clientInDb); + } + } else { Client client = new Client(fn, on, phone); this.clientDao.saveClient(client); diff --git a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/taboutgoingpayments/SentPaymentsTabHandler.java b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/taboutgoingpayments/SentPaymentsTabHandler.java index 551857aa..d6da6028 100644 --- a/src/main/java/org/creditsms/plugins/paymentview/ui/handler/taboutgoingpayments/SentPaymentsTabHandler.java +++ b/src/main/java/org/creditsms/plugins/paymentview/ui/handler/taboutgoingpayments/SentPaymentsTabHandler.java @@ -18,6 +18,7 @@ import net.frontlinesms.ui.handler.PagedListDetails; import org.creditsms.plugins.paymentview.PaymentViewPluginController; +import org.creditsms.plugins.paymentview.data.domain.Client; import org.creditsms.plugins.paymentview.data.domain.OutgoingPayment; import org.creditsms.plugins.paymentview.data.repository.AccountDao; import org.creditsms.plugins.paymentview.data.repository.ClientDao; @@ -150,7 +151,7 @@ public void run() { } else { if (notification instanceof DatabaseEntityNotification){ Object entity = ((DatabaseEntityNotification) notification).getDatabaseEntity(); - if (entity instanceof OutgoingPayment) { + if (entity instanceof OutgoingPayment || entity instanceof Client) { SentPaymentsTabHandler.this.refresh(); } }
4a8ab4863510faef2cf81d887b63a80bce7b2830
Delta Spike
upgrade copyright to 2013
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/NOTICE b/deltaspike/NOTICE index 68c1e6d20..059d3ec2b 100644 --- a/deltaspike/NOTICE +++ b/deltaspike/NOTICE @@ -1,5 +1,5 @@ Apache DeltaSpike -Copyright 2011 - 2012 The Apache Software Foundation +Copyright 2011 - 2013 The Apache Software Foundation This product includes software developed by The Apache Software Foundation (http://www.apache.org/).
cd1025f047e151b40ac538a6a83754a49dfa634c
Vala
Add Description to known attrs
a
https://github.com/GNOME/vala/
diff --git a/vala/valausedattr.vala b/vala/valausedattr.vala index bb090fbc2b..9f29bdcdb0 100644 --- a/vala/valausedattr.vala +++ b/vala/valausedattr.vala @@ -57,6 +57,7 @@ public class Vala.UsedAttr : CodeVisitor { "ReturnsModifiedPointer", "", "Deprecated", "since", "replacement", "", "Signal", "detailed", "run", "no_recurse", "action", "no_hooks", "", + "Description", "nick", "blurb", "", "IntegerType", "rank", "min", "max", "", "FloatingType", "rank", "",
faeaecd49a7c17ec7631cec7a859933976ed7068
Valadoc
gir: ignore type struct docs
a
https://github.com/GNOME/vala/
diff --git a/src/libvaladoc/importer/girdocumentationimporter.vala b/src/libvaladoc/importer/girdocumentationimporter.vala index 4186c27e7e..9984dd59b4 100644 --- a/src/libvaladoc/importer/girdocumentationimporter.vala +++ b/src/libvaladoc/importer/girdocumentationimporter.vala @@ -510,10 +510,13 @@ public class Valadoc.Importer.GirDocumentationImporter : DocumentationImporter { return ; } + bool is_type_struct = (reader.get_attribute ("glib:is-gtype-struct-for") != null); next (); Api.GirSourceComment? comment = parse_symbol_doc (); - attach_comment (this.parent_c_identifier, comment); + if (is_type_struct == false) { + attach_comment (this.parent_c_identifier, comment); + } while (current_token == MarkupTokenType.START_ELEMENT) { if (reader.name == "field") {
bfd4d01fe4b2e28ca15374d1926553d38049e246
clafonta$mockey
Removed Inject URL, replaced with Twist User Experience. Since 'inject' was working properly, there is no loss of functionality. Twisting UX and persistence is ready, but not hooked into the working state yet; response servlet is not yet swapping, and history is not yet showing twisting information
p
https://github.com/clafonta/mockey
diff --git a/src/java/com/mockey/storage/InMemoryMockeyStorage.java b/src/java/com/mockey/storage/InMemoryMockeyStorage.java index d906fc9..81725d1 100755 --- a/src/java/com/mockey/storage/InMemoryMockeyStorage.java +++ b/src/java/com/mockey/storage/InMemoryMockeyStorage.java @@ -533,5 +533,6 @@ public Long getUniversalTwistInfoId() { @Override public void setUniversalTwistInfoId(Long twistInfoId) { this.univeralTwistInfoId = twistInfoId; + this.writeMemoryToFile(); } } diff --git a/src/java/com/mockey/storage/xml/MockeyXmlFileConfigurationGenerator.java b/src/java/com/mockey/storage/xml/MockeyXmlFileConfigurationGenerator.java index 7a1d967..05327cc 100644 --- a/src/java/com/mockey/storage/xml/MockeyXmlFileConfigurationGenerator.java +++ b/src/java/com/mockey/storage/xml/MockeyXmlFileConfigurationGenerator.java @@ -39,20 +39,24 @@ import com.mockey.model.Scenario; import com.mockey.model.Service; import com.mockey.model.ServicePlan; +import com.mockey.model.TwistInfo; import com.mockey.model.Url; import com.mockey.storage.IMockeyStorage; +import com.mockey.ui.PatternPair; /** - * Builds DOM representing Mockey Service configurations. + * Builds DOM representing Mockey Service configurations. + * * @author chad.lafontaine - * + * */ public class MockeyXmlFileConfigurationGenerator extends XmlGeneratorSupport { /** Basic logger */ - //private static Logger logger = Logger.getLogger(MockeyXmlFileConfigurationGenerator.class); + // private static Logger logger = + // Logger.getLogger(MockeyXmlFileConfigurationGenerator.class); /** - * Returns an element representing a mock service definitions file in XML. + * Returns an element representing a mock service definitions file in XML. * * @param document * parent DOM object of this element. @@ -62,39 +66,39 @@ public class MockeyXmlFileConfigurationGenerator extends XmlGeneratorSupport { * <code>null</code>, then empty element is returned e.g. * &lt;cXML/&gt; */ - @SuppressWarnings("unchecked") public Element getElement(Document document, IMockeyStorage store) { - + Element rootElement = document.createElement("mockservice"); - Scenario mssb = store.getUniversalErrorScenario(); + Scenario mssb = store.getUniversalErrorScenario(); this.setAttribute(rootElement, "xml:lang", "en-US"); this.setAttribute(rootElement, "version", "1.0"); // Universal Service settings - if(mssb!=null){ - this.setAttribute(rootElement,"universal_error_service_id", ""+mssb.getServiceId()); - this.setAttribute(rootElement,"universal_error_scenario_id", ""+mssb.getId()); - } + if (mssb != null) { + this.setAttribute(rootElement, "universal_error_service_id", "" + mssb.getServiceId()); + this.setAttribute(rootElement, "universal_error_scenario_id", "" + mssb.getId()); + } + this.setAttribute(rootElement, "universal_twist_info_id", "" + store.getUniversalTwistInfoId()); + // Proxy settings ProxyServerModel psm = store.getProxy(); - if(psm!=null){ - Element proxyElement = document.createElement("proxy_settings"); - proxyElement.setAttribute("proxy_url", psm.getProxyUrl()); - proxyElement.setAttribute("proxy_enabled", ""+psm.isProxyEnabled()); - rootElement.appendChild(proxyElement); + if (psm != null) { + Element proxyElement = document.createElement("proxy_settings"); + proxyElement.setAttribute("proxy_url", psm.getProxyUrl()); + proxyElement.setAttribute("proxy_enabled", "" + psm.isProxyEnabled()); + rootElement.appendChild(proxyElement); } - - Iterator iterator = store.getServices().iterator(); - //logger.debug("building DOM:"); - while (iterator.hasNext()) { - Service mockServiceBean = (Service) iterator.next(); + + for(Service mockServiceBean : store.getServices()) { Element serviceElement = document.createElement("service"); rootElement.appendChild(serviceElement); if (mockServiceBean != null) { - //logger.debug("building XML representation for MockServiceBean:\n" + mockServiceBean.toString()); + // logger.debug("building XML representation for MockServiceBean:\n" + // + mockServiceBean.toString()); // ************************************* // We do NOT want to write out ID. - // If we did, then someone uploading this xml definition may overwrite services + // If we did, then someone uploading this xml definition may + // overwrite services // defined with the same ID. // serviceElement.setAttribute("id", mockServiceBean.getId()); // ************************************* @@ -102,80 +106,93 @@ public Element getElement(Document document, IMockeyStorage store) { serviceElement.setAttribute("description", getSafeForXmlOutputString(mockServiceBean.getDescription())); serviceElement.setAttribute("hang_time", getSafeForXmlOutputString("" + mockServiceBean.getHangTime())); serviceElement.setAttribute("url", getSafeForXmlOutputString("" + mockServiceBean.getUrl())); - serviceElement.setAttribute("http_content_type", getSafeForXmlOutputString("" + mockServiceBean.getHttpContentType())); - serviceElement.setAttribute("default_scenario_id", getSafeForXmlOutputString("" + (mockServiceBean.getDefaultScenarioId()))); - serviceElement.setAttribute("service_response_type", getSafeForXmlOutputString("" + mockServiceBean.getServiceResponseType())); - serviceElement.setAttribute("default_real_url_index", getSafeForXmlOutputString(""+mockServiceBean.getDefaultRealUrlIndex())); + serviceElement.setAttribute("http_content_type", + getSafeForXmlOutputString("" + mockServiceBean.getHttpContentType())); + serviceElement.setAttribute("default_scenario_id", + getSafeForXmlOutputString("" + (mockServiceBean.getDefaultScenarioId()))); + serviceElement.setAttribute("service_response_type", + getSafeForXmlOutputString("" + mockServiceBean.getServiceResponseType())); + serviceElement.setAttribute("default_real_url_index", + getSafeForXmlOutputString("" + mockServiceBean.getDefaultRealUrlIndex())); // New real service URLs - for(Url realUrl: mockServiceBean.getRealServiceUrls()){ + for (Url realUrl : mockServiceBean.getRealServiceUrls()) { Element urlElement = document.createElement("real_url"); urlElement.setAttribute("url", getSafeForXmlOutputString(realUrl.getFullUrl())); - //urlElement.appendChild(cdataResponseElement); + // urlElement.appendChild(cdataResponseElement); serviceElement.appendChild(urlElement); } - - // Scenarios - List scenarios = mockServiceBean.getScenarios(); - Iterator iter = scenarios.iterator(); - while (iter.hasNext()) { - Scenario scenario = (Scenario) iter.next(); - //logger.debug("building XML representation for MockServiceScenarioBean:\n" + scenario.toString()); + // Scenarios + for(Scenario scenario : mockServiceBean.getScenarios() ) { + // logger.debug("building XML representation for MockServiceScenarioBean:\n" + // + scenario.toString()); Element scenarioElement = document.createElement("scenario"); scenarioElement.setAttribute("id", scenario.getId().toString()); scenarioElement.setAttribute("name", getSafeForXmlOutputString(scenario.getScenarioName())); Element scenarioMatchStringElement = document.createElement("scenario_match"); - CDATASection cdataMatchElement = document.createCDATASection(getSafeForXmlOutputString(scenario.getMatchStringArg())); + CDATASection cdataMatchElement = document.createCDATASection(getSafeForXmlOutputString(scenario + .getMatchStringArg())); scenarioMatchStringElement.appendChild(cdataMatchElement); scenarioElement.appendChild(scenarioMatchStringElement); - + Element scenarioResponseElement = document.createElement("scenario_response"); - CDATASection cdataResponseElement = document.createCDATASection(getSafeForXmlOutputString(scenario.getResponseMessage())); + CDATASection cdataResponseElement = document.createCDATASection(getSafeForXmlOutputString(scenario + .getResponseMessage())); scenarioResponseElement.appendChild(cdataResponseElement); scenarioElement.appendChild(scenarioResponseElement); serviceElement.appendChild(scenarioElement); } } } - + // SERVICE PLANS - - List servicePlans = store.getServicePlans(); - if(servicePlans!=null){ - Iterator iter = servicePlans.iterator(); - while(iter.hasNext()){ - ServicePlan servicePlan = (ServicePlan)iter.next(); + if (store.getServicePlans() != null) { + for (ServicePlan servicePlan : store.getServicePlans()) { Element servicePlanElement = document.createElement("service_plan"); servicePlanElement.setAttribute("name", servicePlan.getName()); servicePlanElement.setAttribute("description", servicePlan.getDescription()); - servicePlanElement.setAttribute("id", ""+servicePlan.getId()); - - Iterator planItemIter = servicePlan.getPlanItemList().iterator(); - while(planItemIter.hasNext()){ - PlanItem pi = (PlanItem)planItemIter.next(); + servicePlanElement.setAttribute("id", "" + servicePlan.getId()); + for (PlanItem pi : servicePlan.getPlanItemList()) { Element planItemElement = document.createElement("plan_item"); - planItemElement.setAttribute("hang_time", ""+pi.getHangTime()); - planItemElement.setAttribute("service_id", ""+pi.getServiceId()); - planItemElement.setAttribute("scenario_id", ""+pi.getScenarioId()); - planItemElement.setAttribute("service_response_type", ""+pi.getServiceResponseType()); - + planItemElement.setAttribute("hang_time", "" + pi.getHangTime()); + planItemElement.setAttribute("service_id", "" + pi.getServiceId()); + planItemElement.setAttribute("scenario_id", "" + pi.getScenarioId()); + planItemElement.setAttribute("service_response_type", "" + pi.getServiceResponseType()); + servicePlanElement.appendChild(planItemElement); } - + rootElement.appendChild(servicePlanElement); - + } } + // TWIST CONFIGURATION + if (store.getTwistInfoList() != null) { + for (TwistInfo twistInfo : store.getTwistInfoList()) { + Element twistConfigElement = document.createElement("twist_config"); + twistConfigElement.setAttribute("name", twistInfo.getName()); + twistConfigElement.setAttribute("id", "" + twistInfo.getId()); + for (PatternPair patternPair : twistInfo.getPatternPairList()) { + Element patternPairElement = document.createElement("twist_pattern"); + patternPairElement.setAttribute("origination", "" + patternPair.getOrigination()); + patternPairElement.setAttribute("destination", "" + patternPair.getDestination()); + twistConfigElement.appendChild(patternPairElement); + } + rootElement.appendChild(twistConfigElement); + } + + } + return rootElement; } - - private String getSafeForXmlOutputString(String arg){ - if(arg!=null){ + + private String getSafeForXmlOutputString(String arg) { + if (arg != null) { return arg.trim(); - }else { + } else { return ""; } } diff --git a/src/java/com/mockey/storage/xml/MockeyXmlFileConfigurationParser.java b/src/java/com/mockey/storage/xml/MockeyXmlFileConfigurationParser.java index f701f27..ddde220 100644 --- a/src/java/com/mockey/storage/xml/MockeyXmlFileConfigurationParser.java +++ b/src/java/com/mockey/storage/xml/MockeyXmlFileConfigurationParser.java @@ -27,12 +27,20 @@ */ package com.mockey.storage.xml; -import com.mockey.model.*; -import com.mockey.storage.IMockeyStorage; -import com.mockey.storage.InMemoryMockeyStorage; import org.apache.commons.digester.Digester; import org.xml.sax.InputSource; +import com.mockey.model.PlanItem; +import com.mockey.model.ProxyServerModel; +import com.mockey.model.Scenario; +import com.mockey.model.Service; +import com.mockey.model.ServicePlan; +import com.mockey.model.TwistInfo; +import com.mockey.model.Url; +import com.mockey.storage.IMockeyStorage; +import com.mockey.storage.InMemoryMockeyStorage; +import com.mockey.ui.PatternPair; + /** * This class consumes the mock service definitions file and saves it to the * store. @@ -49,6 +57,9 @@ public class MockeyXmlFileConfigurationParser { private final static String SCENARIO = SERVICE + "/scenario"; private final static String PLAN = ROOT + "/service_plan"; private final static String PLAN_ITEM = PLAN + "/plan_item"; + private final static String TWIST_CONFIG = ROOT + "/twist_config"; + private final static String TWIST_CONFIG_ITEM = TWIST_CONFIG + "/twist_pattern"; + private final static String SCENARIO_MATCH = SCENARIO + "/scenario_match"; private final static String SCENARIO_REQUEST = SCENARIO + "/scenario_request"; private final static String SCENARIO_RESPONSE = SCENARIO + "/scenario_response"; @@ -62,6 +73,7 @@ public IMockeyStorage getMockServices(InputSource inputSource) throws org.xml.sa digester.addSetProperties(ROOT, "universal_error_service_id", "universalErrorServiceId"); digester.addSetProperties(ROOT, "universal_error_scenario_id", "universalErrorScenarioId"); + digester.addSetProperties(ROOT, "universal_twist_info_id", "universalTwistInfoId"); digester.addObjectCreate(PROXYSERVER, ProxyServerModel.class); digester.addSetProperties(PROXYSERVER, "proxy_url", "proxyUrl"); @@ -85,7 +97,6 @@ public IMockeyStorage getMockServices(InputSource inputSource) throws org.xml.sa digester.addSetNext(SERVICE, "saveOrUpdateService"); digester.addObjectCreate(SERVICE_REAL_URL, Url.class); - //digester.addBeanPropertySetter(SERVICE_REAL_URL, "url"); digester.addSetProperties(SERVICE_REAL_URL, "url", "url"); digester.addSetNext(SERVICE_REAL_URL, "saveOrUpdateRealServiceUrl"); @@ -110,6 +121,21 @@ public IMockeyStorage getMockServices(InputSource inputSource) throws org.xml.sa digester.addSetProperties(PLAN_ITEM, "service_response_type", "serviceResponseType"); digester.addSetNext(PLAN_ITEM, "addPlanItem"); + // TWIST CONFIGURATION + digester.addObjectCreate(TWIST_CONFIG, TwistInfo.class); + digester.addSetProperties(TWIST_CONFIG, "name", "name");// + digester.addSetProperties(TWIST_CONFIG, "id", "id"); + digester.addSetNext(TWIST_CONFIG, "saveOrUpdateTwistInfo"); + digester.addObjectCreate(TWIST_CONFIG_ITEM, PatternPair.class); + digester.addSetProperties(TWIST_CONFIG_ITEM, "origination", "origination"); + digester.addSetProperties(TWIST_CONFIG_ITEM, "destination", "destination"); + digester.addSetNext(TWIST_CONFIG_ITEM, "addPatternPair"); + + + + + + IMockeyStorage c = (IMockeyStorage) digester.parse(inputSource); return c; } diff --git a/src/java/com/mockey/ui/ProxyInfoAJAXServlet.java b/src/java/com/mockey/ui/ConfigurationInfoAJAXServlet.java similarity index 84% rename from src/java/com/mockey/ui/ProxyInfoAJAXServlet.java rename to src/java/com/mockey/ui/ConfigurationInfoAJAXServlet.java index 970d748..c0fee6c 100644 --- a/src/java/com/mockey/ui/ProxyInfoAJAXServlet.java +++ b/src/java/com/mockey/ui/ConfigurationInfoAJAXServlet.java @@ -39,10 +39,11 @@ import org.json.JSONObject; import com.mockey.model.ProxyServerModel; +import com.mockey.model.TwistInfo; import com.mockey.storage.IMockeyStorage; import com.mockey.storage.StorageRegistry; -public class ProxyInfoAJAXServlet extends HttpServlet { +public class ConfigurationInfoAJAXServlet extends HttpServlet { private static final long serialVersionUID = 5503460488900643184L; private static IMockeyStorage store = StorageRegistry.MockeyStorage; @@ -67,6 +68,16 @@ public void service(HttpServletRequest req, HttpServletResponse resp) throws Ser JSONObject responseObject = new JSONObject(); JSONObject messageObject = new JSONObject(); messageObject.put("proxy_enabled", Boolean.toString(proxyInfo.isProxyEnabled())); + Long twistInfoId = store.getUniversalTwistInfoId(); + TwistInfo twistInfo = store.getTwistInfoById(twistInfoId); + if (twistInfo != null) { + messageObject.put("twist_enabled", true); + messageObject.put("twist-id", twistInfo.getId()); + messageObject.put("twist-name", twistInfo.getName()); + + } else { + messageObject.put("twist_enabled", false); + } resp.setContentType("application/json;"); responseObject.put("result", messageObject); @@ -78,5 +89,4 @@ public void service(HttpServletRequest req, HttpServletResponse resp) throws Ser out.close(); return; } - } diff --git a/src/java/com/mockey/ui/ConfigurationReader.java b/src/java/com/mockey/ui/ConfigurationReader.java index 0509839..b7727bc 100755 --- a/src/java/com/mockey/ui/ConfigurationReader.java +++ b/src/java/com/mockey/ui/ConfigurationReader.java @@ -41,6 +41,7 @@ import com.mockey.model.Scenario; import com.mockey.model.Service; import com.mockey.model.ServicePlan; +import com.mockey.model.TwistInfo; import com.mockey.model.Url; import com.mockey.storage.IMockeyStorage; import com.mockey.storage.StorageRegistry; @@ -67,8 +68,7 @@ public class ConfigurationReader { * @throws SAXException * @throws SAXParseException */ - public void inputFile(File file) throws IOException, SAXParseException, - SAXException { + public void inputFile(File file) throws IOException, SAXParseException, SAXException { InputStream is = new FileInputStream(file); long length = file.length(); @@ -83,15 +83,13 @@ public void inputFile(File file) throws IOException, SAXParseException, // Read in the bytes int offset = 0; int numRead = 0; - while (offset < bytes.length - && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { + while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } // Ensure all the bytes have been read in if (offset < bytes.length) { - throw new IOException("Could not completely read file " - + file.getName()); + throw new IOException("Could not completely read file " + file.getName()); } // Close the input stream and return bytes @@ -110,31 +108,24 @@ public void inputFile(File file) throws IOException, SAXParseException, * @throws SAXException * @throws SAXParseException */ - public ServiceMergeResults loadConfiguration(byte[] data) - throws IOException, SAXParseException, SAXException { + public ServiceMergeResults loadConfiguration(byte[] data) throws IOException, SAXParseException, SAXException { ServiceMergeResults mergeResults = new ServiceMergeResults(); String strXMLDefintion = new String(data); MockeyXmlFileConfigurationReader msfr = new MockeyXmlFileConfigurationReader(); - IMockeyStorage mockServiceStoreTemporary = msfr - .readDefinition(strXMLDefintion); + IMockeyStorage mockServiceStoreTemporary = msfr.readDefinition(strXMLDefintion); // PROXY SETTINGs store.setProxy(mockServiceStoreTemporary.getProxy()); // UNIVERSAL RESPONSE SETTINGS - if (store.getUniversalErrorScenario() != null - && mockServiceStoreTemporary.getUniversalErrorScenario() != null) { - mergeResults - .addConflictMsg("Universal error message already defined with name '" - + store.getUniversalErrorScenario() - .getScenarioName() + "'"); + if (store.getUniversalErrorScenario() != null && mockServiceStoreTemporary.getUniversalErrorScenario() != null) { + mergeResults.addConflictMsg("Universal error message already defined with name '" + + store.getUniversalErrorScenario().getScenarioName() + "'"); } else if (store.getUniversalErrorScenario() == null && mockServiceStoreTemporary.getUniversalErrorScenario() != null) { - store.setUniversalErrorScenarioId(mockServiceStoreTemporary - .getUniversalErrorScenario().getId()); - store.setUniversalErrorServiceId(mockServiceStoreTemporary - .getUniversalErrorScenario().getServiceId()); + store.setUniversalErrorScenarioId(mockServiceStoreTemporary.getUniversalErrorScenario().getId()); + store.setUniversalErrorServiceId(mockServiceStoreTemporary.getUniversalErrorScenario().getServiceId()); mergeResults.addAdditionMsg("Universal error response defined."); } @@ -151,27 +142,19 @@ public ServiceMergeResults loadConfiguration(byte[] data) // 2) NO MATCHING MOCK URL // If there is no matching service URL, then create a new // service and associated scenarios. - List<Service> uploadedServices = mockServiceStoreTemporary - .getServices(); - Iterator<Service> iter2 = uploadedServices.iterator(); - while (iter2.hasNext()) { - Service uploadedServiceBean = (Service) iter2.next(); + for (Service uploadedServiceBean : mockServiceStoreTemporary.getServices()) { List<Service> serviceBeansInMemory = store.getServices(); Iterator<Service> iter3 = serviceBeansInMemory.iterator(); boolean existingServiceWithMatchingMockUrl = false; Service inMemoryServiceBean = null; while (iter3.hasNext()) { inMemoryServiceBean = (Service) iter3.next(); - Url firstMatchingUrl = inMemoryServiceBean - .getFirstMatchingRealServiceUrl(uploadedServiceBean); + Url firstMatchingUrl = inMemoryServiceBean.getFirstMatchingRealServiceUrl(uploadedServiceBean); if (firstMatchingUrl != null) { existingServiceWithMatchingMockUrl = true; - mergeResults - .addConflictMsg("Service '" - + uploadedServiceBean.getServiceName() - + "' not created; will try to merge into existing service labeled '" - + inMemoryServiceBean.getServiceName() - + "' "); + mergeResults.addConflictMsg("Service '" + uploadedServiceBean.getServiceName() + + "' not created; will try to merge into existing service labeled '" + + inMemoryServiceBean.getServiceName() + "' "); break; } } @@ -179,24 +162,23 @@ public ServiceMergeResults loadConfiguration(byte[] data) // We null it, to not stomp on any services uploadedServiceBean.setId(null); store.saveOrUpdateService(uploadedServiceBean); - mergeResults.addAdditionMsg("Service '" - + uploadedServiceBean.getServiceName() + "' created. "); + mergeResults.addAdditionMsg("Service '" + uploadedServiceBean.getServiceName() + "' created. "); } else { // Just merge scenarios per matching services - mergeResults = mergeServices(uploadedServiceBean, - inMemoryServiceBean, mergeResults); + mergeResults = mergeServices(uploadedServiceBean, inMemoryServiceBean, mergeResults); } } // PLANS - List<ServicePlan> servicePlans = mockServiceStoreTemporary - .getServicePlans(); - Iterator<ServicePlan> iter3 = servicePlans.iterator(); - while (iter3.hasNext()) { - ServicePlan servicePlan = iter3.next(); + for (ServicePlan servicePlan : mockServiceStoreTemporary.getServicePlans()) { store.saveOrUpdateServicePlan(servicePlan); } + + // TWIST CONFIGURATION + for(TwistInfo twistInfo:mockServiceStoreTemporary.getTwistInfoList() ){ + store.saveOrUpdateTwistInfo(twistInfo); + } return mergeResults; } @@ -208,17 +190,15 @@ public ServiceMergeResults loadConfiguration(byte[] data) * @param readResults * @return */ - public ServiceMergeResults mergeServices(Service uploadedServiceBean, - Service inMemoryServiceBean, ServiceMergeResults readResults) { + public ServiceMergeResults mergeServices(Service uploadedServiceBean, Service inMemoryServiceBean, + ServiceMergeResults readResults) { if (uploadedServiceBean != null && inMemoryServiceBean != null) { // Merge Scenarios if (readResults == null) { readResults = new ServiceMergeResults(); } - Iterator<Scenario> uIter = uploadedServiceBean.getScenarios() - .iterator(); - Iterator<Scenario> mIter = inMemoryServiceBean.getScenarios() - .iterator(); + Iterator<Scenario> uIter = uploadedServiceBean.getScenarios().iterator(); + Iterator<Scenario> mIter = inMemoryServiceBean.getScenarios().iterator(); while (uIter.hasNext()) { Scenario uploadedScenario = (Scenario) uIter.next(); boolean existingScenario = false; @@ -234,15 +214,13 @@ public ServiceMergeResults mergeServices(Service uploadedServiceBean, uploadedScenario.setServiceId(inMemoryServiceBean.getId()); inMemoryServiceBean.saveOrUpdateScenario(uploadedScenario); store.saveOrUpdateService(inMemoryServiceBean); - readResults.addAdditionMsg("Scenario '" - + uploadedScenario.getScenarioName() - + "' added to service '" - + inMemoryServiceBean.getServiceName() + "' "); + readResults.addAdditionMsg("Scenario '" + uploadedScenario.getScenarioName() + + "' added to service '" + inMemoryServiceBean.getServiceName() + "' "); } else { - readResults.addConflictMsg("Scenario '" - + mBean.getScenarioName() - + "' not added, already defined in service '" - + inMemoryServiceBean.getServiceName() + "' "); + readResults + .addConflictMsg("Scenario '" + mBean.getScenarioName() + + "' not added, already defined in service '" + + inMemoryServiceBean.getServiceName() + "' "); } } diff --git a/src/java/com/mockey/ui/InjectRealUrlPerServiceServlet.java b/src/java/com/mockey/ui/InjectRealUrlPerServiceServlet.java deleted file mode 100644 index 9cc3eb1..0000000 --- a/src/java/com/mockey/ui/InjectRealUrlPerServiceServlet.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * This file is part of Mockey, a tool for testing application - * interactions over HTTP, with a focus on testing web services, - * specifically web applications that consume XML, JSON, and HTML. - * - * Copyright (C) 2009-2010 Authors: - * - * chad.lafontaine (chad.lafontaine AT gmail DOT com) - * neil.cronin (neil AT rackle DOT com) - * lorin.kobashigawa (lkb AT kgawa DOT com) - * rob.meyer (rob AT bigdis DOT com) - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * - */ -package com.mockey.ui; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONException; -import org.json.JSONObject; - -import com.mockey.model.Service; -import com.mockey.model.Url; -import com.mockey.storage.IMockeyStorage; -import com.mockey.storage.StorageRegistry; - -public class InjectRealUrlPerServiceServlet extends HttpServlet { - - /** - * - */ - private static final long serialVersionUID = -8696328817749243557L; - private static IMockeyStorage store = StorageRegistry.MockeyStorage; - - /** - * - * - * @param req - * basic request - * @param resp - * basic resp - * @throws ServletException - * basic - * @throws IOException - * basic - */ - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - RequestDispatcher dispatch = req - .getRequestDispatcher("/inject_realurl.jsp"); - dispatch.forward(req, resp); - } - - /** - * Injects real URLs per service. For example, if real url is - * - * <pre> - * http://qa1.google.com/search - * </pre> - * - * and match is - * - * <pre> - * http://qa3.google.com/ - * </pre> - * - * then this method builds URL as - * - * <pre> - * http://qa3.google.com/search - * </pre> - * - * - * @param req - * basic request - * @param resp - * basic resp - * @throws ServletException - * basic - * @throws IOException - * basic - */ - public void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - String matchPattern = req.getParameter("match"); - String[] replacementArray = req.getParameterValues("replacement[]"); - JSONObject successOrFail = new JSONObject(); - Map<String, String> statusMessage = new HashMap<String, String>(); - if (matchPattern != null && replacementArray != null) { - - for (Long serviceId : store.getServiceIds()) { - Service service = store.getServiceById(serviceId); - List<Url> newUrlList = new ArrayList<Url>(); - // Build a list of real Url objects. - for (Url realUrl : service.getRealServiceUrls()) { - for (String replacement : replacementArray) { - // We don't want to inject empty string match - if (replacement.trim().length() > 0) { - Url newUrl = new Url(realUrl.getFullUrl() - .replaceAll(matchPattern, replacement)); - if (!service.hasRealServiceUrl(newUrl)) { - newUrlList.add(newUrl); - // Note: you should not save or update - // the realServiceUrl or service while - // iterating through the list itself, or you'll - // get - // a java.util.ConcurrentModificationException - // Wait until 'after' - } - } - } - } - // Save/update this new Url object list. - for (Url newUrl : newUrlList) { - service.saveOrUpdateRealServiceUrl(newUrl); - } - - // Now update the service. - store.saveOrUpdateService(service); - } - - try { - successOrFail.put("success", "URL injecting complete."); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } else { - try { - successOrFail.put("fail", - "You didn't pass any match or inject URL arguments. "); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - JSONObject responseObject = new JSONObject(); - - try { - responseObject.put("result", successOrFail); - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - PrintWriter out = resp.getWriter(); - out.println(responseObject.toString()); - out.flush(); - out.close(); - return; - } -} diff --git a/src/java/com/mockey/ui/PatternPair.java b/src/java/com/mockey/ui/PatternPair.java index a89e7e1..a7d6c07 100644 --- a/src/java/com/mockey/ui/PatternPair.java +++ b/src/java/com/mockey/ui/PatternPair.java @@ -9,7 +9,7 @@ public class PatternPair { private String origination; private String destination; - + public PatternPair(){} public PatternPair(String origination, String destination) { this.origination = origination; this.destination = destination; diff --git a/src/java/com/mockey/ui/TwistInfoDeleteServlet.java b/src/java/com/mockey/ui/TwistInfoDeleteServlet.java index b53f2dd..74bb0c1 100644 --- a/src/java/com/mockey/ui/TwistInfoDeleteServlet.java +++ b/src/java/com/mockey/ui/TwistInfoDeleteServlet.java @@ -100,6 +100,8 @@ public void service(HttpServletRequest req, HttpServletResponse resp) throws Ser List<TwistInfo> twistInfoList = store.getTwistInfoList(); Util.saveSuccessMessage("Deleted", req); req.setAttribute("twistInfoList", twistInfoList); + req.setAttribute("twistInfoIdEnabled", store.getUniversalTwistInfoId()); + RequestDispatcher dispatch = req.getRequestDispatcher("/twistinfo_setup.jsp"); dispatch.forward(req, resp); return; diff --git a/src/java/com/mockey/ui/TwistInfoSetupServlet.java b/src/java/com/mockey/ui/TwistInfoSetupServlet.java index 58ced4e..662a47c 100644 --- a/src/java/com/mockey/ui/TwistInfoSetupServlet.java +++ b/src/java/com/mockey/ui/TwistInfoSetupServlet.java @@ -102,6 +102,7 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws Servl } else { req.setAttribute("twistInfoList", twistInfoList); + req.setAttribute("twistInfoIdEnabled", store.getUniversalTwistInfoId()); RequestDispatcher dispatch = req.getRequestDispatcher("/twistinfo_setup.jsp"); dispatch.forward(req, resp); return; @@ -187,6 +188,8 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws Serv } else { List<TwistInfo> twistInfoList = store.getTwistInfoList(); req.setAttribute("twistInfoList", twistInfoList); + req.setAttribute("twistInfoIdEnabled", store.getUniversalTwistInfoId()); + RequestDispatcher dispatch = req.getRequestDispatcher("/twistinfo_setup.jsp"); dispatch.forward(req, resp); return; diff --git a/src/java/com/mockey/ui/TwistInfoToggleServlet.java b/src/java/com/mockey/ui/TwistInfoToggleServlet.java index 9411db2..87b1703 100644 --- a/src/java/com/mockey/ui/TwistInfoToggleServlet.java +++ b/src/java/com/mockey/ui/TwistInfoToggleServlet.java @@ -37,6 +37,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.log4j.Logger; import org.json.JSONException; import org.json.JSONObject; @@ -46,12 +47,12 @@ public class TwistInfoToggleServlet extends HttpServlet implements TwistInfoConfigurationAPI { - /** * */ private static final long serialVersionUID = 8461665153162178045L; private static IMockeyStorage store = StorageRegistry.MockeyStorage; + private static final Logger logger = Logger.getLogger(TwistInfoToggleServlet.class); /** * Handles the following activities for <code>TwistInfo</code> @@ -66,14 +67,33 @@ public void service(HttpServletRequest req, HttpServletResponse resp) throws Ser Long twistInfoId = null; TwistInfo twistInfo = null; String coachingMessage = null; + JSONObject jsonObject = new JSONObject(); + try { twistInfoId = new Long(req.getParameter(PARAMETER_KEY_TWIST_ID)); + boolean enable = Boolean.parseBoolean(req.getParameter(PARAMETER_KEY_TWIST_ENABLE)); twistInfo = store.getTwistInfoById(twistInfoId); - store.setUniversalTwistInfoId(twistInfo.getId()); - coachingMessage = "Twist configuration on"; + if(enable){ + store.setUniversalTwistInfoId(twistInfo.getId()); + if (twistInfo != null) { + jsonObject.put(PARAMETER_KEY_TWIST_ID, "" + twistInfo.getId()); + jsonObject.put(PARAMETER_KEY_TWIST_NAME, "" + twistInfo.getName()); + coachingMessage = "Twist configuration on"; + } + + }else if(store.getUniversalTwistInfoId()!=null && store.getUniversalTwistInfoId().equals(twistInfoId)){ + // Disable + // The only way to DISABLE _all_ twist configurations, both ENABLE (false) and TWIST-ID value (equal + // to the current universal twist-id have to be passed in. + // Why? To prevent random 'ENABLE=false' arguments past to this service from users + // clicking OFF/disable when things are already disabled. + // + store.setUniversalTwistInfoId(null); + coachingMessage = "Twist configuration off"; + } + } catch (Exception e) { - coachingMessage = "Twist configuration off"; - store.setUniversalTwistInfoId(null); + logger.error("Unable to properly set Twist configuration.", e); } if (PARAMETER_KEY_RESPONSE_TYPE_VALUE_JSON.equalsIgnoreCase(responseType)) { @@ -83,13 +103,9 @@ public void service(HttpServletRequest req, HttpServletResponse resp) throws Ser PrintWriter out = resp.getWriter(); try { JSONObject jsonResponseObject = new JSONObject(); - JSONObject jsonObject = new JSONObject(); if (twistInfo != null) { jsonObject.put("success", coachingMessage); - if (twistInfo != null) { - jsonObject.put("id", "" + twistInfo.getId()); - jsonObject.put("name", "" + twistInfo.getName()); - } + } else { jsonObject.put("fail", "Unable to set twist configuration."); @@ -113,6 +129,7 @@ public void service(HttpServletRequest req, HttpServletResponse resp) throws Ser List<TwistInfo> twistInfoList = store.getTwistInfoList(); Util.saveSuccessMessage("Twist configuration updated", req); req.setAttribute("twistInfoList", twistInfoList); + req.setAttribute("twistInfoIdEnabled", store.getUniversalTwistInfoId()); RequestDispatcher dispatch = req.getRequestDispatcher("/twistinfo_setup.jsp"); dispatch.forward(req, resp); return; diff --git a/src/java/com/mockey/ui/Util.java b/src/java/com/mockey/ui/Util.java index e5e8269..705ae43 100755 --- a/src/java/com/mockey/ui/Util.java +++ b/src/java/com/mockey/ui/Util.java @@ -36,6 +36,9 @@ import javax.servlet.http.HttpServletRequest; +import org.json.JSONException; +import org.json.JSONObject; + import com.mockey.model.Scenario; import com.mockey.model.Service; import com.mockey.model.ServicePlan; @@ -51,21 +54,21 @@ public class Util { * @param message * @param req */ - private static void save(String message, String messageKey, - HttpServletRequest req) { - + private static void save(String message, String messageKey, HttpServletRequest req) { + // HISTORY: This method use to save a List of messages // for the purpose to display to the end user. But since - // this solution can be tweak by a head-less client, - // the list of informative messages to the user became - // perplexing. + // this solution can be tweak by a head-less client, + // the list of informative messages to the user became + // perplexing. List<String> msgs = new ArrayList<String>(); msgs.add(message); req.getSession().setAttribute(messageKey, msgs); } /** - * Saves the last (most recent) error message. + * Saves the last (most recent) error message. + * * @param message * @param req */ @@ -74,7 +77,8 @@ public static void saveErrorMessage(String message, HttpServletRequest req) { } /** - * Saves the last (most recent) success message. + * Saves the last (most recent) success message. + * * @param message * @param req */ @@ -98,71 +102,68 @@ public static void saveErrorMap(Map errorMap, HttpServletRequest req) { /** * Returns the services list ordered alphabetically. + * * @param services * @return */ - public static List<Service> orderAlphabeticallyByServiceName( - List<Service> services) { + public static List<Service> orderAlphabeticallyByServiceName(List<Service> services) { // Custom comparator class ServiceNameComparator implements Comparator<Service> { public int compare(Service s1, Service s2) { - return s1.getServiceName().compareToIgnoreCase( - s2.getServiceName()); + return s1.getServiceName().compareToIgnoreCase(s2.getServiceName()); } } - // Sort me. + // Sort me. Collections.sort(services, new ServiceNameComparator()); - + return services; } - + /** * Returns the services list ordered alphabetically. + * * @param services * @return */ - public static List<ServicePlan> orderAlphabeticallyByServicePlanName( - List<ServicePlan> servicePlans) { + public static List<ServicePlan> orderAlphabeticallyByServicePlanName(List<ServicePlan> servicePlans) { // Custom comparator class ServicePlanNameComparator implements Comparator<ServicePlan> { public int compare(ServicePlan s1, ServicePlan s2) { - return s1.getName().compareToIgnoreCase( - s2.getName()); + return s1.getName().compareToIgnoreCase(s2.getName()); } } - // Sort me. + // Sort me. Collections.sort(servicePlans, new ServicePlanNameComparator()); - + return servicePlans; } - + /** * Returns the services list ordered alphabetically. + * * @param services * @return */ - public static List<Scenario> orderAlphabeticallyByScenarioName( - List<Scenario> scenarios) { + public static List<Scenario> orderAlphabeticallyByScenarioName(List<Scenario> scenarios) { // Custom comparator class ScenarioNameComparator implements Comparator<Scenario> { public int compare(Scenario s1, Scenario s2) { - return s1.getScenarioName().compareToIgnoreCase( - s2.getScenarioName()); + return s1.getScenarioName().compareToIgnoreCase(s2.getScenarioName()); } } - // Sort me. + // Sort me. Collections.sort(scenarios, new ScenarioNameComparator()); - + return scenarios; } @@ -171,27 +172,25 @@ public int compare(Scenario s1, Scenario s2) { * @param objectMap * * @return - * @deprecated - Should use JSONObject API, not this crappola. */ public static String getJSON(Map<String, String> objectMap) { - StringBuffer returnErrorMap = new StringBuffer(); - + JSONObject jsonResult = new JSONObject(); + JSONObject jsonObject = new JSONObject(); Iterator<String> errorIter = objectMap.keySet().iterator(); - while (errorIter.hasNext()) { - String key = errorIter.next(); - String value = (String) objectMap.get(key); - - returnErrorMap.append("\"" + key + "\": \"" + value + "\""); - if (errorIter.hasNext()) { - - returnErrorMap.append(",\n"); + String result = null; + try { + while (errorIter.hasNext()) { + String key = errorIter.next(); + String value = (String) objectMap.get(key); + jsonObject.put(key, value); } + jsonResult.put("result", jsonObject); + result = jsonResult.toString(); + } catch (JSONException je) { + result = "Unable to create JSON format response. " + je.getMessage(); } - String resultingJSON = "{ \"result\": { " + returnErrorMap.toString() - + "}}"; - - return resultingJSON; + return result; } } \ No newline at end of file diff --git a/web/WEB-INF/common/header.jsp b/web/WEB-INF/common/header.jsp index 4dfa482..9f1d8bf 100644 --- a/web/WEB-INF/common/header.jsp +++ b/web/WEB-INF/common/header.jsp @@ -35,7 +35,7 @@ $(document).ready(function() { dropShadows: true // disable drop shadows }); // - $.getJSON('<c:url value="/proxystatus" />', function(data) { + $.getJSON('<c:url value="/configuration/info" />', function(data) { if(data.result.proxy_enabled=='true'){ $("#proxy_unknown").hide(); $("#proxy_on").show(); @@ -45,6 +45,15 @@ $(document).ready(function() { $("#proxy_on").hide(); $("#proxy_off").show(); } + if(data.result.twist_enabled==true){ + $("#twisting_unknown").hide(); + $("#twisting_on").show(); + $("#twisting_off").hide(); + }else { + $("#twisting_unknown").hide(); + $("#twisting_on").hide(); + $("#twisting_off").show(); + } }); $("#dialog-flush-confirm").dialog({ resizable: false, @@ -104,9 +113,6 @@ $(document).ready(function() { <li <c:if test="${currentTab == 'merge'}">class="current"</c:if>> <a title="Merge - combine services" href="<c:url value="/merge" />" style="">Merge Services</a></li> - <li <c:if test="${currentTab == 'inject'}">class="current"</c:if>> - <a title="Real URL injecting" href="<c:url value="/inject" />" - style="">URL injecting</a></li> <li <c:if test="${currentTab == 'twisting'}">class="current"</c:if>> <a title="Twisting" href="<c:url value="/twisting/setup" />" style="">Twisting</a></li> @@ -120,8 +126,7 @@ $(document).ready(function() { <a href="<c:url value="/history" />">History</a></li> <li <c:if test="${currentTab == 'proxy'}">class="current"</c:if>> <a href="<c:url value="/proxy/settings" />"> - Proxy (<span id="proxy_unknown" class="tiny" >___</span><span id="proxy_on" class="tiny" - style="display: none;">ON</span><span id="proxy_off" class="tiny" style="display: none;">OFF</span>)</a></li> + Proxy</a></li> <li><a id="flush" href="#">Flush</a></li> <li class="<c:if test="${currentTab == 'help'}">current</c:if>"><a href="<c:url value="/help" />">Help <span class="sf-sub-indicator"> &#187;</span></a> @@ -131,8 +136,22 @@ $(document).ready(function() { </ul> </li> </ul> + <div id="configuration-info" > + <span class="configuration-info" > + <a href="<c:url value="/proxy/settings"/>" id="proxy_unknown" class="tiny" >___</a> + <a href="<c:url value="/proxy/settings"/>" id="proxy_on" class="tiny" style="color: green; ">Proxy setting is ON</a> + <a href="<c:url value="/proxy/settings"/>" id="proxy_off" class="tiny" style="color: red; ">Proxy setting is OFF</a> + </span> + <span class="configuration-info" > + <a href="<c:url value="/twisting/setup"/>" id="twisting_unknown" class="tiny" >___</a> + <a href="<c:url value="/twisting/setup"/>" id="twisting_on" class="tiny" style="color: green; ">Twisting is on</a> + <a href="<c:url value="/twisting/setup"/>" id="twisting_off" class="tiny" style="color: red; ">Twisting is OFF</a> + </span> + </div> </div> + <div style="border-bottom:1px solid #CCCCCC;"></div> </div> + diff --git a/web/WEB-INF/web.xml b/web/WEB-INF/web.xml index 93cff29..ad9470b 100644 --- a/web/WEB-INF/web.xml +++ b/web/WEB-INF/web.xml @@ -82,17 +82,13 @@ <servlet-class>com.mockey.server.RedoRequestServlet</servlet-class> </servlet> <servlet> - <servlet-name>ProxyInfoAJAXServlet</servlet-name> - <servlet-class>com.mockey.ui.ProxyInfoAJAXServlet</servlet-class> + <servlet-name>ConfigurationInfoAJAXServlet</servlet-name> + <servlet-class>com.mockey.ui.ConfigurationInfoAJAXServlet</servlet-class> </servlet> <servlet> <servlet-name>ServiceMergeServlet</servlet-name> <servlet-class>com.mockey.ui.ServiceMergeServlet</servlet-class> </servlet> - <servlet> - <servlet-name>InjectRealUrlPerServiceServlet</servlet-name> - <servlet-class>com.mockey.ui.InjectRealUrlPerServiceServlet</servlet-class> - </servlet> <servlet> <servlet-name>ScenarioViewAjaxServlet</servlet-name> <servlet-class>com.mockey.ui.ScenarioViewAjaxServlet</servlet-class> @@ -141,17 +137,13 @@ <servlet-name>ScenarioViewAjaxServlet</servlet-name> <url-pattern>/view/scenario</url-pattern> </servlet-mapping> - <servlet-mapping> - <servlet-name>InjectRealUrlPerServiceServlet</servlet-name> - <url-pattern>/inject</url-pattern> - </servlet-mapping> <servlet-mapping> <servlet-name>ServiceMergeServlet</servlet-name> <url-pattern>/merge</url-pattern> </servlet-mapping> <servlet-mapping> - <servlet-name>ProxyInfoAJAXServlet</servlet-name> - <url-pattern>/proxystatus</url-pattern> + <servlet-name>ConfigurationInfoAJAXServlet</servlet-name> + <url-pattern>/configuration/info</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>RedoRequestServlet</servlet-name> diff --git a/web/css/style.css b/web/css/style.css index 43bcdaa..1b62e8f 100644 --- a/web/css/style.css +++ b/web/css/style.css @@ -237,6 +237,20 @@ padding: 8px; color:yellow; padding: 0.2em; } +.configuration-info { + text-align: right; + padding: 0.2em; + margin-left: 0.8em; + border: thin solid #EEEEEE; + -moz-border-radius: 0.2em; + -webkit-border-radius: 0.2em; + +} +.configuration-info {background-color:#FFFFE7;} +.configuration-info a:link {text-decoration: none;} +.configuration-info a:visited {text-decoration: none;} +.configuration-info a:active {text-decoration: none;} +.configuration-info a:hover {text-decoration: underline;} .power-link a:link {color:#FF0084;} .power-link a:visited {text-decoration: none;color:#FF0084;} diff --git a/web/twistinfo_setup.jsp b/web/twistinfo_setup.jsp index 1073cdf..c0fbe21 100755 --- a/web/twistinfo_setup.jsp +++ b/web/twistinfo_setup.jsp @@ -6,7 +6,7 @@ <%@include file="/WEB-INF/common/header.jsp" %> <script type="text/javascript"> $(document).ready( function() { - + $("#dialog-create-twist").dialog({minHeight: 450, height:250, width: 500, modal: true, autoOpen: false, resizable: true }); $('.createTwistLink').each( function() { @@ -26,7 +26,7 @@ $(document).ready( function() { var bValid = true; // 'valid' check here for those who want input validation. if (bValid) { - var twistConfigName = $('input[name=twist_config_name]').val(); + var twistConfigName = $('input[id=twist_config_name_new]').val(); $.post('<c:url value="/twisting/setup"/>', { 'response-type': 'json', 'twist-name': twistConfigName, 'twist-origination-values[]': originationValues,'twist-destination-values[]': destinationValues } ,function(data){ if(data.result.success && data.result.id){ $(this).dialog('close'); @@ -68,7 +68,7 @@ $(document).ready( function() { var bValid = true; // 'valid' check here for those who want input validation. if (bValid) { - var twistConfigName = $('input[name=twist_config_name_'+twistId+']').val(); + var twistConfigName = $('input[id=twist_config_name_'+twistId+']').val(); $.post('<c:url value="/twisting/setup"/>', { 'twist-id': twistId, 'response-type': 'json', 'twist-name': twistConfigName, 'twist-origination-values[]': originationValues,'twist-destination-values[]': destinationValues } ,function(data){ if(data.result.success && data.result.id){ $(this).dialog('close'); @@ -85,7 +85,7 @@ $(document).ready( function() { } }); // Reset the size. - $('#dialog-create-twist').dialog({height: 450 }); + $('#dialog-edit-twist_' + twistId).dialog({height: 450, width:400 }); return false; }); @@ -145,16 +145,25 @@ $(document).ready( function() { $('#dialog-delete-twist-config-confirm').dialog({autoOpen: false, minHeight: 300, width: 300, height: 300, modal: false, resizable: false }); <c:forEach var="twistInfo" items="${twistInfoList}" varStatus="status"> - $('#dialog-edit-twist_${twistInfo.id}').dialog({autoOpen: false, minHeight: 300, width: 300, height: 400, modal: false, resizable: true }); + $('#dialog-edit-twist_${twistInfo.id}').dialog({autoOpen: false, minHeight: 300, width: 450, height: 400, modal: false, resizable: true }); </c:forEach> $('.toggletwist').each( function() { $(this).click(function(){ var twistId = this.id.split("_")[1]; - //console.log("response type: "+response_type); - $.post('<c:url value="/twisting/toggle"/>', { 'response-type': 'json', 'twist-id': twistId } ,function(data){ + var enable = this.id.split("_")[2]; + + //console.log("response type: "+response_type); response_set + $.post('<c:url value="/twisting/toggle"/>', { 'response-type': 'json', 'twist-id': twistId, 'twist-enable': enable } ,function(data){ //console.log(data); if(data.result.success){ - $('#updated').fadeIn('fast').animate({opacity: 1.0}, 300).fadeOut('fast'); + // R + $('#updated').fadeIn('fast').animate({opacity: 1.0}, 300).fadeOut('fast', + function() {document.location="<c:url value="/twisting/setup" />"; }); + return false; + + }else { + $("#tmp-error").remove(); + $("#foo").append("<span id=\"tmp-error\">Unable to toggle</span>").fadeIn(1000).fadeTo(3000, 1).fadeOut(1000); } }, 'json' ); }); @@ -166,9 +175,9 @@ $(document).ready( function() { <h1>Twisting</h1> <div> <p><strong>Twisting</strong> refers to re-mapping incoming URL requests to other URLs. This is useful if - your code is pointing to DOMAIN-X and/or URL-PATH-X, and you need to point to DOMAIN-Y and/or URL-PATH-Y. + your code is pointing to DOMAIN-X and/or URL-PATH-X, and you need to point to DOMAIN-Y and/or URL-PATH-Y. <a id="more-help" class="more-help" href="#">More help.</a> </p> - <p class="info_message"><span style="color:red;">What? When would I need this?</span> When your client application doesn't + <p id="dialog-more-help" class="info_message" style=""><span style="color:red;">What? When would I need this?</span> When your client application doesn't easily allow you to point to different environments or when some requests should be answered by the real service but other requests need to be answered by your sandbox. </p> @@ -185,8 +194,8 @@ $(document).ready( function() { <span style="float:right;"> <a href="#" id="delete-twist-link_${twistInfo.id}" class="delete-twist-link remove_grey">x</a> </span> <h3>${twistInfo.name}</h3> <p> - <a id="toggle-twist_${twistInfo.id}" class="toggletwist response_not" style="text-decoration:none;" href="#"> On </a> - <a id="toggle-twist_OFF" class="toggletwist response_not" style="text-decoration:none; margin-left:2px;margin-right:2px;" href="#"> Off </a> + <a id="toggle-twist-on_${twistInfo.id}_true" class="toggletwist toggle-twist-on <c:if test="${twistInfoIdEnabled eq twistInfo.id}">response_set</c:if> <c:if test="${twistInfoIdEnabled ne twistInfo.id}">response_not</c:if>" style="text-decoration:none;" href="#"> On </a> + <a id="toggle-twist-off_${twistInfo.id}_false" class="toggletwist toggle-twist-off <c:if test="${twistInfoIdEnabled eq twistInfo.id}">response_not</c:if> <c:if test="${twistInfoIdEnabled ne twistInfo.id}">response_set</c:if>" style="text-decoration:none; margin-left:2px;margin-right:2px;" href="#"> Off </a> </p> <table class="api"> <tr><th>Find this pattern...</th><th>Replace with this...</th></tr> @@ -225,7 +234,7 @@ $(document).ready( function() { <div id="dialog-create-twist" title="Create Twist Configuration"> <p> <label for="twist-name">Twist Configuration name</label> - <input type="text" name="twist_config_name" id="twist_config_name" class="text ui-widget-content ui-corner-all" /> + <input type="text" name="twist_config_name" id="twist_config_name_new" class="text ui-widget-content ui-corner-all" /> <div style="text-align:right;"><a title="Add row" id="add-row" href="#" style="color:red;text-decoration:none;font-size:1em;">Add pattern twist</a></div> <div id="create-twist-pattern-list"> <!-- JQUERY Append content here -->
111d34b6af146f675dd6ccd9ba67fc826386542a
restlet-framework-java
- Fixed selector exhaustion issue with- Grizzly connector. Reported by Bruce Lee.--
c
https://github.com/restlet/restlet-framework-java
diff --git a/build/tmpl/eclipse/dictionary.xml b/build/tmpl/eclipse/dictionary.xml index 92e6fd8dd5..2a53b7b82a 100644 --- a/build/tmpl/eclipse/dictionary.xml +++ b/build/tmpl/eclipse/dictionary.xml @@ -30,3 +30,5 @@ rhett sutphin codec waldin +arcand +francois diff --git a/modules/org.restlet/src/org/restlet/engine/io/NbChannelOutputStream.java b/modules/org.restlet/src/org/restlet/engine/io/NbChannelOutputStream.java index d3d16e4f10..a7b8214248 100644 --- a/modules/org.restlet/src/org/restlet/engine/io/NbChannelOutputStream.java +++ b/modules/org.restlet/src/org/restlet/engine/io/NbChannelOutputStream.java @@ -74,12 +74,6 @@ public NbChannelOutputStream(WritableByteChannel channel) { this.selector = null; } - @Override - public void close() throws IOException { - NioUtils.release(this.selector, this.selectionKey); - super.close(); - } - /** * Effectively write the current byte buffer. * @@ -135,6 +129,7 @@ private void doWrite() throws IOException { + ioe.getLocalizedMessage()); } finally { this.bb.clear(); + NioUtils.release(this.selector, this.selectionKey); } } else { throw new IOException( diff --git a/modules/org.restlet/src/org/restlet/engine/io/SelectorFactory.java b/modules/org.restlet/src/org/restlet/engine/io/SelectorFactory.java index cd2220acf2..3e6b70a597 100644 --- a/modules/org.restlet/src/org/restlet/engine/io/SelectorFactory.java +++ b/modules/org.restlet/src/org/restlet/engine/io/SelectorFactory.java @@ -38,20 +38,23 @@ * @author Jean-Francois Arcand */ public class SelectorFactory { - /** The number of <code>Selector</code> to create. */ - public static int maxSelectors = 20; + /** The maximum number of <code>Selector</code> to create. */ + public static final int MAX_SELECTORS = 20; + + /** The number of attempts to find an available selector. */ + public static final int MAX_ATTEMPTS = 2; /** Cache of <code>Selector</code>. */ - private final static Stack<Selector> selectors = new Stack<Selector>(); + private static final Stack<Selector> SELECTORS = new Stack<Selector>(); /** The timeout before we exit. */ - public static long timeout = 5000; + public static final long TIMEOUT = 5000; /** Creates the <code>Selector</code>. */ static { try { - for (int i = 0; i < maxSelectors; i++) { - selectors.add(Selector.open()); + for (int i = 0; i < MAX_SELECTORS; i++) { + SELECTORS.add(Selector.open()); } } catch (IOException ex) { // do nothing. @@ -64,24 +67,24 @@ public class SelectorFactory { * @return An exclusive <code>Selector</code>. */ public final static Selector getSelector() { - synchronized (selectors) { + synchronized (SELECTORS) { Selector selector = null; try { - if (selectors.size() != 0) { - selector = selectors.pop(); + if (SELECTORS.size() != 0) { + selector = SELECTORS.pop(); } } catch (EmptyStackException ex) { } int attempts = 0; try { - while ((selector == null) && (attempts < 2)) { - selectors.wait(timeout); + while ((selector == null) && (attempts < MAX_ATTEMPTS)) { + SELECTORS.wait(TIMEOUT); try { - if (selectors.size() != 0) { - selector = selectors.pop(); + if (SELECTORS.size() != 0) { + selector = SELECTORS.pop(); } } catch (EmptyStackException ex) { break; @@ -103,10 +106,10 @@ public final static Selector getSelector() { * The <code>Selector</code> to return. */ public final static void returnSelector(Selector selector) { - synchronized (selectors) { - selectors.push(selector); - if (selectors.size() == 1) { - selectors.notify(); + synchronized (SELECTORS) { + SELECTORS.push(selector); + if (SELECTORS.size() == 1) { + SELECTORS.notify(); } } }
91a826c0fac91512f97f9e9df58c4a61db3bb8e3
Vala
gio-2.0: argument to BufferedInputStream.peek_buffer should be out Fixes bug 606627.
c
https://github.com/GNOME/vala/
diff --git a/vapi/gio-2.0.vapi b/vapi/gio-2.0.vapi index 260f495dc0..9b06128f43 100644 --- a/vapi/gio-2.0.vapi +++ b/vapi/gio-2.0.vapi @@ -20,7 +20,7 @@ namespace GLib { public size_t get_available (); public size_t get_buffer_size (); public size_t peek (void* buffer, size_t offset, size_t count); - public void* peek_buffer (size_t count); + public void* peek_buffer (out size_t count); public int read_byte (GLib.Cancellable? cancellable) throws GLib.Error; public void set_buffer_size (size_t size); [CCode (type = "GInputStream*", has_construct_function = false)] diff --git a/vapi/packages/gio-2.0/gio-2.0.metadata b/vapi/packages/gio-2.0/gio-2.0.metadata index 868600e93e..cebeaacd5c 100644 --- a/vapi/packages/gio-2.0/gio-2.0.metadata +++ b/vapi/packages/gio-2.0/gio-2.0.metadata @@ -4,6 +4,7 @@ g_app_info_launch.launch_context nullable="1" g_app_info_launch_default_for_uri.launch_context nullable="1" g_app_info_launch_uris.envp is_array="1" GAsyncReadyCallback.source_object nullable="1" +g_buffered_input_stream_peek_buffer.count is_out="1" g_content_type_guess.data_size hidden="1" g_content_type_guess.result_uncertain is_out="1" g_data_input_stream_read_line nullable="1" transfer_ownership="1"
31e0610c5117ca425c69d0b8b974a00caa7765a1
incf$eeg-database
Admin License management + Experiment license functionality
p
https://github.com/incf/eeg-database
diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/data/pojo/PersonMembershipPlan.java b/src/main/java/cz/zcu/kiv/eegdatabase/data/pojo/PersonMembershipPlan.java index 33c39b15..2e26b17c 100644 --- a/src/main/java/cz/zcu/kiv/eegdatabase/data/pojo/PersonMembershipPlan.java +++ b/src/main/java/cz/zcu/kiv/eegdatabase/data/pojo/PersonMembershipPlan.java @@ -53,11 +53,11 @@ public class PersonMembershipPlan implements Serializable { @ManyToOne @JoinColumn(name = "MEMBERSHIP_PLAN") private MembershipPlan membershipPlan; - +/* @ManyToOne @JoinColumn(name = "PROMO_CODE") private PromoCode promoCode; - +*/ public void setPersonMembershipPlanId(int personMembershipPlanId) { @@ -79,11 +79,11 @@ public void setFrom(Timestamp from) { public void setTo(Timestamp to) { this.to = to; } - +/* public void setPromoCode(PromoCode promoCode) { this.promoCode = promoCode; } - +*/ public int getPersonMembershipPlanId() { return personMembershipPlanId; } @@ -103,8 +103,9 @@ public Timestamp getFrom() { public Timestamp getTo() { return to; } - +/* public PromoCode getPromoCode() { return promoCode; } + */ } diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/data/pojo/PromoCode.java b/src/main/java/cz/zcu/kiv/eegdatabase/data/pojo/PromoCode.java index c4951937..8ed8c774 100644 --- a/src/main/java/cz/zcu/kiv/eegdatabase/data/pojo/PromoCode.java +++ b/src/main/java/cz/zcu/kiv/eegdatabase/data/pojo/PromoCode.java @@ -35,7 +35,7 @@ @Entity @Table(name="PROMO_CODE") -public class PromoCode implements Serializable { +public class PromoCode implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @@ -62,13 +62,13 @@ public class PromoCode implements Serializable { @Column(name="VALID") private boolean valid; - +/* @OneToMany(mappedBy = "promoCode") private Set<PersonMembershipPlan> personMembershipPlans; @OneToMany(mappedBy = "promoCode") private Set<ResearchGroupMembershipPlan> researchGroupMembershipPlans; - +*/ public void setPromoCode(PromoCode code) { this.keyword = code.keyword; this.discount = code.discount; @@ -102,7 +102,7 @@ public int getType() { public String getDescription() { return description; } - +/* public Set<PersonMembershipPlan> getPersonMembershipPlans() { return personMembershipPlans; } @@ -110,7 +110,7 @@ public Set<PersonMembershipPlan> getPersonMembershipPlans() { public Set<ResearchGroupMembershipPlan> getResearchGroupMembershipPlans() { return researchGroupMembershipPlans; } - +*/ public void setPromoCodeId(int promoCodeId) { this.promoCodeId = promoCodeId; } @@ -142,7 +142,7 @@ public void setType(int type) { public void setDescription(String description) { this.description = description; } - +/* public void setPersonMembershipPlans(Set<PersonMembershipPlan> personMembershipPlans) { this.personMembershipPlans = personMembershipPlans; } @@ -150,7 +150,7 @@ public void setPersonMembershipPlans(Set<PersonMembershipPlan> personMembershipP public void setResearchGroupMembershipPlans(Set<ResearchGroupMembershipPlan> researchGroupMembershipPlans) { this.researchGroupMembershipPlans = researchGroupMembershipPlans; } - +*/ public boolean isValid() { return valid; } diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/data/pojo/ResearchGroupMembershipPlan.java b/src/main/java/cz/zcu/kiv/eegdatabase/data/pojo/ResearchGroupMembershipPlan.java index 6523b669..e4873b34 100644 --- a/src/main/java/cz/zcu/kiv/eegdatabase/data/pojo/ResearchGroupMembershipPlan.java +++ b/src/main/java/cz/zcu/kiv/eegdatabase/data/pojo/ResearchGroupMembershipPlan.java @@ -54,10 +54,10 @@ public class ResearchGroupMembershipPlan implements Serializable { @JoinColumn(name = "MEMBERSHIP_PLAN") private MembershipPlan membershipPlan; - @ManyToOne +/* @ManyToOne @JoinColumn(name = "PROMO_CODE") private PromoCode promoCode; - +*/ public int getResearchGroupMembershipPlanId() { return researchGroupMembershipPlanId; } @@ -77,11 +77,11 @@ public ResearchGroup getResearchGroup() { public MembershipPlan getMembershipPlan() { return membershipPlan; } - +/* public PromoCode getPromoCode() { return promoCode; } - +*/ public void setResearchGroupMembershipPlanId(int researchGroupMembershipPlanId) { this.researchGroupMembershipPlanId = researchGroupMembershipPlanId; } @@ -101,8 +101,9 @@ public void setResearchGroup(ResearchGroup researchGroup) { public void setMembershipPlan(MembershipPlan membershipPlan) { this.membershipPlan = membershipPlan; } - +/* public void setPromoCode(PromoCode promoCode) { this.promoCode = promoCode; } + */ } diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/wui/components/table/DeleteLinkPanel.java b/src/main/java/cz/zcu/kiv/eegdatabase/wui/components/table/DeleteLinkPanel.java index 06d44f55..8a40fb30 100644 --- a/src/main/java/cz/zcu/kiv/eegdatabase/wui/components/table/DeleteLinkPanel.java +++ b/src/main/java/cz/zcu/kiv/eegdatabase/wui/components/table/DeleteLinkPanel.java @@ -1,9 +1,11 @@ package cz.zcu.kiv.eegdatabase.wui.components.table; +import cz.zcu.kiv.eegdatabase.data.pojo.License; import cz.zcu.kiv.eegdatabase.data.pojo.MembershipPlan; import cz.zcu.kiv.eegdatabase.data.pojo.PromoCode; import cz.zcu.kiv.eegdatabase.wui.components.form.input.AjaxConfirmLink; import cz.zcu.kiv.eegdatabase.wui.components.page.MenuPage; +import cz.zcu.kiv.eegdatabase.wui.core.license.LicenseFacade; import cz.zcu.kiv.eegdatabase.wui.core.membershipplan.MembershipPlanFacade; import cz.zcu.kiv.eegdatabase.wui.core.promocode.PromoCodeFacade; import org.apache.wicket.ajax.AjaxRequestTarget; @@ -31,6 +33,9 @@ public class DeleteLinkPanel extends Panel { @SpringBean PromoCodeFacade promoCodeFacade; + @SpringBean + LicenseFacade licenseFacade; + public DeleteLinkPanel(String id, final Class<? extends MenuPage> page,String propertyExpression, final IModel model, IModel<String> displayModel, String confirmMessage) { super(id); @@ -57,6 +62,10 @@ public void onClick(AjaxRequestTarget target) { promoCodeFacade.update(code); //System.out.println(promoCodeFacade.getPromoCodeByKeyword("ABCK")); //System.out.println(promoCodeFacade.getPromoCodeByKeyword("FFDSFSDG")); + } else if (model.getObject().getClass() == License.class) { + License license = licenseFacade.read((Integer)paramModel.getObject()); + licenseFacade.delete(license); + } setResponsePage(page); } diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/wui/core/license/LicenseFacade.java b/src/main/java/cz/zcu/kiv/eegdatabase/wui/core/license/LicenseFacade.java index b17d2dae..3fdaf983 100644 --- a/src/main/java/cz/zcu/kiv/eegdatabase/wui/core/license/LicenseFacade.java +++ b/src/main/java/cz/zcu/kiv/eegdatabase/wui/core/license/LicenseFacade.java @@ -195,5 +195,6 @@ public interface LicenseFacade extends GenericFacade<License, Integer> { public List<License> getLicensesForExperiment(int experimentId); public List<License> getPersonLicenses(int personId); - + + public List<License> getLicenseTemplates(); } diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/wui/core/license/LicenseService.java b/src/main/java/cz/zcu/kiv/eegdatabase/wui/core/license/LicenseService.java index fb566538..a02740f6 100644 --- a/src/main/java/cz/zcu/kiv/eegdatabase/wui/core/license/LicenseService.java +++ b/src/main/java/cz/zcu/kiv/eegdatabase/wui/core/license/LicenseService.java @@ -110,4 +110,6 @@ public interface LicenseService extends GenericService<License, Integer> { public List<License> getLicensesForExperiment(int experimentId); public List<License> getPersonLicenses(int personId); + + public List<License> getLicenseTemplates(); } diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/wui/core/license/impl/LicenseFacadeImpl.java b/src/main/java/cz/zcu/kiv/eegdatabase/wui/core/license/impl/LicenseFacadeImpl.java index 8c332032..02e97d85 100644 --- a/src/main/java/cz/zcu/kiv/eegdatabase/wui/core/license/impl/LicenseFacadeImpl.java +++ b/src/main/java/cz/zcu/kiv/eegdatabase/wui/core/license/impl/LicenseFacadeImpl.java @@ -203,5 +203,9 @@ public List<License> getLicensesForExperiment(int experimentId) { public List<License> getPersonLicenses(int personId) { return licenseService.getPersonLicenses(personId); } - + + @Override + public List<License> getLicenseTemplates() { + return licenseService.getLicenseTemplates(); + } } diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/wui/core/license/impl/LicenseServiceImpl.java b/src/main/java/cz/zcu/kiv/eegdatabase/wui/core/license/impl/LicenseServiceImpl.java index 9dad6b08..12e81c45 100644 --- a/src/main/java/cz/zcu/kiv/eegdatabase/wui/core/license/impl/LicenseServiceImpl.java +++ b/src/main/java/cz/zcu/kiv/eegdatabase/wui/core/license/impl/LicenseServiceImpl.java @@ -197,6 +197,14 @@ public List<License> getLicenseTemplates(ResearchGroup group) { return this.licenseDao.readByParameter(params); } + @Override + @Transactional(readOnly = true) + public List<License> getLicenseTemplates() { + Map<String, Object> params = new HashMap<String, Object>(); + params.put("template", true); + return this.licenseDao.readByParameter(params); + } + @Override @Transactional(readOnly = true) public byte[] getLicenseAttachmentContent(int licenseId) { diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/administration/AdminManageLicensesPage.html b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/administration/AdminManageLicensesPage.html index dbf893eb..b1c8a8ad 100644 --- a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/administration/AdminManageLicensesPage.html +++ b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/administration/AdminManageLicensesPage.html @@ -19,6 +19,11 @@ <h2> <table class="dataTable measurationListDataTable" wicket:id="licenseTemplates"></table> + <br/> + <a href="#" wicket:id="addLicense" class="lightButtonLink"><wicket:message key="link.addLicense"></wicket:message></a> + <br/> + + </div> </wicket:extend> </body> diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/administration/AdminManageLicensesPage.java b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/administration/AdminManageLicensesPage.java index 38b90856..cf012b60 100644 --- a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/administration/AdminManageLicensesPage.java +++ b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/administration/AdminManageLicensesPage.java @@ -3,6 +3,7 @@ import cz.zcu.kiv.eegdatabase.data.pojo.License; import cz.zcu.kiv.eegdatabase.wui.components.menu.button.ButtonPageMenu; import cz.zcu.kiv.eegdatabase.wui.components.page.MenuPage; +import cz.zcu.kiv.eegdatabase.wui.components.table.DeleteLinkPanel; import cz.zcu.kiv.eegdatabase.wui.components.table.ViewLinkPanel; import cz.zcu.kiv.eegdatabase.wui.components.utils.ResourceUtils; import cz.zcu.kiv.eegdatabase.wui.core.license.LicenseFacade; @@ -10,8 +11,10 @@ import cz.zcu.kiv.eegdatabase.wui.ui.administration.forms.MembershipPlanManageFormPage; import cz.zcu.kiv.eegdatabase.wui.ui.licenses.LicenseDetailPage; import cz.zcu.kiv.eegdatabase.wui.ui.licenses.ListLicensesDataProvider; +import cz.zcu.kiv.eegdatabase.wui.ui.licenses.components.LicenseDownloadLinkPanel; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; +import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.DefaultDataTable; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; @@ -45,8 +48,10 @@ public AdminManageLicensesPage() { DefaultDataTable<License, String> licenses = new DefaultDataTable<License, String>("licenseTemplates", createLicensesColumns(), new ListLicensesDataProvider(licenseFacade, true), ITEMS_PER_PAGE); - add(licenses); + BookmarkablePageLink<Void> addLicense = new BookmarkablePageLink<Void>("addLicense", LicenseManageFormPage.class); + + add(licenses,addLicense); } @@ -55,7 +60,14 @@ private List<? extends IColumn<License, String>> createLicensesColumns() { List<IColumn<License, String>> columns = new ArrayList<IColumn<License, String>>(); columns.add(new PropertyColumn<License, String>(ResourceUtils.getModel("dataTable.heading.title"), "title", "title")); - columns.add(new PropertyColumn<License, String>(ResourceUtils.getModel("dataTable.heading.description"), "description", "description")); + columns.add(new PropertyColumn<License, String>(ResourceUtils.getModel("dataTable.heading.price"), "price", "price")); + columns.add(new PropertyColumn<License, String>(ResourceUtils.getModel("dataTable.heading.attachmentFile"), null, null) { + @Override + public void populateItem(Item<ICellPopulator<License>> item, String componentId, IModel<License> rowModel) { + item.add(new LicenseDownloadLinkPanel(componentId, rowModel)); + } + }); + //columns.add(new PropertyColumn<License, String>(ResourceUtils.getModel("dataTable.heading.description"), "description", "description")); columns.add(new PropertyColumn<License, String>(ResourceUtils.getModel("dataTable.heading.detail"), null, null) { @Override public void populateItem(Item<ICellPopulator<License>> item, String componentId, IModel<License> rowModel) { @@ -68,34 +80,14 @@ public void populateItem(Item<ICellPopulator<License>> item, String componentId, item.add(new ViewLinkPanel(componentId, LicenseManageFormPage.class, "licenseId", rowModel, ResourceUtils.getModel("link.edit"))); } }); - - - /* - * List<IColumn<MembershipPlan, String>> columns = new ArrayList<IColumn<MembershipPlan, String>>(); - - columns.add(new PropertyColumn<MembershipPlan, String>(ResourceUtils.getModel("dataTable.heading.membershipName"), "name", "name")); - columns.add(new PropertyColumn<MembershipPlan, String>(ResourceUtils.getModel("dataTable.heading.dayslength"), "length", "length")); - columns.add(new PropertyColumn<MembershipPlan, String>(ResourceUtils.getModel("dataTable.heading.price"), "price", "price")); - columns.add(new PropertyColumn<MembershipPlan, String>(ResourceUtils.getModel("dataTable.heading.detail"), null, null) { + columns.add(new AbstractColumn<License, String>(ResourceUtils.getModel("dataTable.heading.delete")) { @Override - public void populateItem(Item<ICellPopulator<MembershipPlan>> item, String componentId, IModel<MembershipPlan> rowModel) { - item.add(new ViewLinkPanel(componentId, MembershipPlansDetailPage.class, "membershipId", rowModel, ResourceUtils.getModel("link.detail"))); - } - }); - columns.add(new PropertyColumn<MembershipPlan, String>(ResourceUtils.getModel("dataTable.heading.edit"), null, null) { - @Override - public void populateItem(Item<ICellPopulator<MembershipPlan>> item, String componentId, IModel<MembershipPlan> rowModel) { - item.add(new ViewLinkPanel(componentId, MembershipPlanManageFormPage.class, "membershipId", rowModel, ResourceUtils.getModel("link.edit"))); - } - }); - columns.add(new AbstractColumn<MembershipPlan, String>(ResourceUtils.getModel("dataTable.heading.delete")) { - @Override - public void populateItem(Item<ICellPopulator<MembershipPlan>> item, String componentId,final IModel<MembershipPlan> rowModel) { + public void populateItem(Item<ICellPopulator<License>> item, String componentId,final IModel<License> rowModel) { - item.add(new DeleteLinkPanel(componentId,AdminManageMembershipPlansPage.class,"membershipId", rowModel,ResourceUtils.getModel("link.delete"),ResourceUtils.getString("text.delete.membershipplan"))); + item.add(new DeleteLinkPanel(componentId,AdminManageLicensesPage.class,"licenseId", rowModel,ResourceUtils.getModel("link.delete"),ResourceUtils.getString("text.delete.licenseTemplate"))); } }); - return columns;*/ + return columns; } diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/administration/forms/LicenseManageFormPage.html b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/administration/forms/LicenseManageFormPage.html index 6241d3b5..bce663d1 100644 --- a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/administration/forms/LicenseManageFormPage.html +++ b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/administration/forms/LicenseManageFormPage.html @@ -37,11 +37,17 @@ <h1 wicket:id="headTitle"></h1> </span> </div> - <!-- + <div class="itemBox"> + <!--<label class="textFieldLabel" wicket:message="value:label.license.attachment.file"/>--> + <label for=licenseFile wicket:id="attachmentFileNameLb" class="textFieldLabel"> <wicket:message + key="label.licenseFile">[file]</wicket:message></label> + <input type="file" class="textField" wicket:id="attachmentFileName"/> + </div> + <div class="itemBox"> <input wicket:id="submit" class="submitButton lightButtonLink" type="submit" /> </div> - --> + </fieldset> </form> diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/administration/forms/LicenseManageFormPage.java b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/administration/forms/LicenseManageFormPage.java index 676ae10e..a1e44ca1 100644 --- a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/administration/forms/LicenseManageFormPage.java +++ b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/administration/forms/LicenseManageFormPage.java @@ -11,10 +11,16 @@ import cz.zcu.kiv.eegdatabase.wui.ui.administration.AdminManageLicensesPage; import cz.zcu.kiv.eegdatabase.wui.ui.administration.AdminManageMembershipPlansPage; import cz.zcu.kiv.eegdatabase.wui.ui.administration.AdministrationPageLeftMenu; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.apache.wicket.RestartResponseAtInterceptPageException; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.markup.html.form.AjaxButton; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.*; +import org.apache.wicket.markup.html.form.upload.FileUpload; +import org.apache.wicket.markup.html.form.upload.FileUploadField; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.IModel; @@ -22,12 +28,16 @@ import org.apache.wicket.model.PropertyModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.util.lang.Bytes; import org.apache.wicket.util.lang.Classes; import org.apache.wicket.util.string.StringValue; import org.apache.wicket.validation.validator.PatternValidator; import org.apache.wicket.validation.validator.RangeValidator; import org.apache.wicket.validation.validator.StringValidator; +import java.io.IOException; +import java.math.BigDecimal; + /** * Created by Lichous on 4.5.15. */ @@ -36,6 +46,8 @@ public class LicenseManageFormPage extends MenuPage { private static final long serialVersionUID = -1642766215588431080L; + protected Log log = LogFactory.getLog(getClass()); + @SpringBean LicenseFacade licenseFacade; @@ -53,14 +65,6 @@ public LicenseManageFormPage(PageParameters parameters) { License license = licenseFacade.read(licenseId.toInteger()); - /* - MembershipPlan newPlan = new MembershipPlan(); - newPlan.setPlan(membershipPlan); - membershipPlan.setValid(false); - membershipPlanFacade.update(membershipPlan); - membershipPlanFacade.create(newPlan); - */ - add(new Label("headTitle", ResourceUtils.getModel("pageTitle.editLicenseTemplate"))); add(new ButtonPageMenu("leftMenu", AdministrationPageLeftMenu.values())); add(new LicenseForm("form",new Model<License>(license),licenseFacade,getFeedback())); @@ -72,12 +76,6 @@ private class LicenseForm extends Form<License> { public LicenseForm(String id, IModel<License> model,final LicenseFacade licenseFacade, final FeedbackPanel feedback) { super(id,new CompoundPropertyModel<License>(model)); - - //headTitle - //title,titleLb - //descriptionLb,description - //priceLb,price - //typeLb TextField<String> name = new TextField<String>("title"); name.setLabel(ResourceUtils.getModel("label.name")); name.setRequired(true); @@ -95,7 +93,7 @@ public LicenseForm(String id, IModel<License> model,final LicenseFacade licenseF TextField<Integer> price = new TextField<Integer>("price",Integer.class); price.setLabel(ResourceUtils.getModel("label.price")); price.setRequired(false); - price.add(RangeValidator.minimum(1)); + price.add(RangeValidator.minimum(0)); FormComponentLabel priceLabel = new FormComponentLabel("priceLb", price); add(price,priceLabel); @@ -110,6 +108,57 @@ public LicenseForm(String id, IModel<License> model,final LicenseFacade licenseF FormComponentLabel typeLabel = new FormComponentLabel("typeLb", type); add(type,typeLabel); + final FileUploadField fileUpload = new FileUploadField("attachmentFileName"); + FormComponentLabel fileLabel = new FormComponentLabel("attachmentFileNameLb",fileUpload); + + setMaxSize(Bytes.megabytes(15)); + add(fileUpload,fileLabel); + + AjaxButton submit = new AjaxButton("submit", ResourceUtils.getModel("button.saveMembershipPlan"), this) { + + private static final long serialVersionUID = 1L; + + @Override + protected void onError(AjaxRequestTarget target, Form<?> form) { + target.add(feedback); + } + + @Override + protected void onSubmit(AjaxRequestTarget target, Form<?> form) { + + License license = LicenseForm.this.getModelObject(); + if (license.getPrice()==null) license.setPrice(new BigDecimal(0)); + FileUpload uploadedFile = fileUpload.getFileUpload(); + + if (uploadedFile != null) { + license.setAttachmentFileName(uploadedFile.getClientFileName()); + try { + license.setFileContentStream(uploadedFile.getInputStream()); + } catch (IOException e) { + log.error(e.getMessage(), e); + } + } + + if (license.getLicenseId() == 0) { + license.setTemplate(true); + licenseFacade.create(license); + + } else { + if (uploadedFile == null) { + license.setAttachmentFileName(licenseFacade.read(license.getLicenseId()).getAttachmentFileName()); + } + licenseFacade.update(license); + } + + license.setFileContentStream(null); + + setResponsePage(AdminManageLicensesPage.class); + + target.add(feedback); + + } + }; + add(submit); } } diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/experiments/components/ExperimentPackageManagePanel.java b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/experiments/components/ExperimentPackageManagePanel.java index cab53cd9..b3d3cfa4 100644 --- a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/experiments/components/ExperimentPackageManagePanel.java +++ b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/experiments/components/ExperimentPackageManagePanel.java @@ -359,10 +359,13 @@ protected List<License> load() { protected void onSubmitAction(IModel<License> model, AjaxRequestTarget target, Form<?> form) { License obj = model.getObject(); - FileUploadField fileUploadField = this.getFileUpload(); - FileUpload uploadedFile = fileUploadField.getFileUpload(); - + //FileUploadField fileUploadField = this.getFileUpload(); + //FileUpload uploadedFile = fileUploadField.getFileUpload(); + + //System.out.println("FileField: "+fileUploadField.toString() + ", UploadFile: "+uploadedFile.getClientFileName()); + /* if (uploadedFile != null) { + System.out.println("==ISN'T NULL!"); obj.setAttachmentFileName(uploadedFile.getClientFileName()); try { obj.setFileContentStream(uploadedFile.getInputStream()); @@ -370,7 +373,7 @@ protected void onSubmitAction(IModel<License> model, AjaxRequestTarget target, F log.error(e.getMessage(), e); } } - + */ if (obj.getLicenseId() == 0) { if(selectedBlueprintModel.getObject() != null && !obj.getTitle().equals(selectedBlueprintModel.getObject().getTitle())) { obj.setTemplate(true); diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/LicenseDetailPage.html b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/LicenseDetailPage.html index 49a6c0bd..1bc9c03a 100644 --- a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/LicenseDetailPage.html +++ b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/LicenseDetailPage.html @@ -33,6 +33,15 @@ <h1> <th><wicket:message key="label.type" /></th> <td wicket:id="type"></td> </tr> + <wicket:enclosure child="download"> + <tr> + <th colspan="2"><wicket:message key="label.license.attachment.file"></wicket:message></th> + </tr> + <tr> + <td wicket:id="attachmentFileName"></td> + <td><a href="#" wicket:id="download"><wicket:message key="link.download"></wicket:message></a></td> + </tr> + </wicket:enclosure> </table> diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/LicenseDetailPage.java b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/LicenseDetailPage.java index d5e5351a..3a6912d4 100644 --- a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/LicenseDetailPage.java +++ b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/LicenseDetailPage.java @@ -13,7 +13,9 @@ import org.apache.wicket.RestartResponseAtInterceptPageException; import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation; import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.link.ResourceLink; import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.request.resource.ByteArrayResource; import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.wicket.util.string.StringValue; @@ -48,5 +50,18 @@ private void setupPageComponents(Integer licenseId) { add(new Label("description", license.getDescription())); add(new Label("price", license.getPrice())); add(new Label("type", license.getLicenseType().toString())); + add(new Label("attachmentFileName", license.getAttachmentFileName())); + + boolean isContent = license != null && license.getAttachmentFileName() != null; + + ByteArrayResource res; + if (isContent) { + res = new ByteArrayResource("", licenseFacade.getLicenseAttachmentContent(license.getLicenseId()), license.getAttachmentFileName()); + } else { + res = new ByteArrayResource(""); + } + ResourceLink<Void> downloadLink = new ResourceLink<Void>("download", res); + downloadLink.setVisible(isContent); + add(downloadLink); } } diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/components/LicenseDownloadLinkPanel.html b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/components/LicenseDownloadLinkPanel.html new file mode 100644 index 00000000..0123bce2 --- /dev/null +++ b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/components/LicenseDownloadLinkPanel.html @@ -0,0 +1,11 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" + xmlns:wicket="http://wicket.apache.org/dtds.data/wicket-xhtml1.4-strict.dtd" xml:lang="en" + lang="en"> +<body> +<wicket:panel> + <a href="#" wicket:id="download"><wicket:container wicket:id="fileName" /></a> + <!--<wicket:container wicket:id="noFile" />--> +</wicket:panel> +</body> +</html> \ No newline at end of file diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/components/LicenseDownloadLinkPanel.java b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/components/LicenseDownloadLinkPanel.java new file mode 100644 index 00000000..4612c47f --- /dev/null +++ b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/components/LicenseDownloadLinkPanel.java @@ -0,0 +1,47 @@ +package cz.zcu.kiv.eegdatabase.wui.ui.licenses.components; + +import cz.zcu.kiv.eegdatabase.data.pojo.License; +import cz.zcu.kiv.eegdatabase.wui.components.utils.ResourceUtils; +import cz.zcu.kiv.eegdatabase.wui.core.license.LicenseFacade; +import org.apache.wicket.markup.html.basic.Label; + +import org.apache.wicket.markup.html.link.ResourceLink; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.request.resource.ByteArrayResource; +import org.apache.wicket.spring.injection.annot.SpringBean; +import org.apache.wicket.markup.html.panel.Panel; + +/** + * Created by Lichous on 5.5.15. + */ +public class LicenseDownloadLinkPanel extends Panel { + + + @SpringBean + LicenseFacade licenseFacade; + + public LicenseDownloadLinkPanel(String id, IModel<License> model) { + super(id); + + final License license = model.getObject(); + + boolean isContent = license != null && license.getAttachmentFileName() != null; + + ByteArrayResource res; + if (isContent) { + res = new ByteArrayResource("", licenseFacade.getLicenseAttachmentContent(license.getLicenseId()), license.getAttachmentFileName()); + } else { + res = new ByteArrayResource(""); + } + ResourceLink<Void> downloadLink = new ResourceLink<Void>("download", res); + downloadLink.setVisibilityAllowed(isContent); + downloadLink.add(new Label("fileName", new Model<String>(license.getAttachmentFileName())).setVisibilityAllowed(isContent)); + add(downloadLink); + //add(new Label("noFile", new Model<String>("")).setVisibilityAllowed(!isContent)); + + + } +} + + diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/components/LicenseDropDownChoicePanel.java b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/components/LicenseDropDownChoicePanel.java index be56ff16..36f7ccce 100644 --- a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/components/LicenseDropDownChoicePanel.java +++ b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/components/LicenseDropDownChoicePanel.java @@ -107,15 +107,16 @@ private void addLicenseAddWindow() { addLicenseWindow.setResizable(false); addLicenseWindow.setMinimalWidth(600); addLicenseWindow.setWidthUnit("px"); + addLicenseWindow.showUnloadConfirmation(false); IModel<List<License>> blpModel = new LoadableDetachableModel<List<License>>() { @Override protected List<License> load() { - return licenseFacade.getPersonLicenses(loggedUser.getPersonId()); + return licenseFacade.getLicenseTemplates(); } }; - LicenseEditForm content = new LicenseEditForm(addLicenseWindow.getContentId(), licenseModel, blpModel, new Model<Boolean>(true)) { + final LicenseEditForm content = new LicenseEditForm(addLicenseWindow.getContentId(), licenseModel, blpModel, new Model<Boolean>(true)) { @Override protected void onSubmitAction(IModel<License> model, AjaxRequestTarget target, Form<?> form) { @@ -123,21 +124,9 @@ protected void onSubmitAction(IModel<License> model, AjaxRequestTarget target, F System.out.println("LICECNE: "+obj+"id: "+obj.getLicenseId()); - FileUploadField fileUploadField = this.getFileUpload(); - FileUpload uploadedFile = fileUploadField.getFileUpload(); - - if (uploadedFile != null) { - obj.setAttachmentFileName(uploadedFile.getClientFileName()); - try { - obj.setFileContentStream(uploadedFile.getInputStream()); - } catch (IOException e) { - log.error(e.getMessage(), e); - } - } - if (obj.getLicenseId() == 0) { //if(selectedBlueprintModel.getObject() != null && !obj.getTitle().equals(selectedBlueprintModel.getObject().getTitle())) { - obj.setTemplate(true); + obj.setTemplate(false); //obj.setResearchGroup(epModel.getObject().getResearchGroup()); licenseFacade.create(obj); System.out.println("PO CREATEU: "+obj.getLicenseId()); @@ -186,6 +175,7 @@ public void onClick(AjaxRequestTarget target) { //License l = this.getModelObject(); //if (l!=null) System.out.println(l.getTitle()); licenseModel.setObject(new License()); + content.setLicenseModel(new License()); addLicenseWindow.show(target); } diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/components/LicenseEditForm.html b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/components/LicenseEditForm.html index 6ed2426f..fb0a22ec 100644 --- a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/components/LicenseEditForm.html +++ b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/components/LicenseEditForm.html @@ -52,6 +52,7 @@ <wicket:enclosure> <input type="radio" wicket:id="business"/><wicket:message key="LicenseType.BUSINESS"/> </wicket:enclosure> + <input type="radio" wicket:id="public"/><wicket:message key="LicenseType.PUBLIC"/> </span> <div wicket:id="licenseType.feedback"/> </div> @@ -61,11 +62,26 @@ <textarea class="textareaField" wicket:id="description"/> <div wicket:id="description.feedback"/> </div> + <hr> + <div class="itemBox"> + <wicket:enclosure child="download"> + + <h3><wicket:message key="label.license.attachment.file"></wicket:message></h3> + <div wicket:id="attachmentFileName"></div> + <a href="#" wicket:id="download"><wicket:message key="link.download"></wicket:message></a> + + </wicket:enclosure> + </div> + <hr> + <!-- <div class="itemBox"> <label class="textFieldLabel" wicket:message="value:label.license.attachment.file"/> <input type="file" class="textField" wicket:id="licenseFile"/> </div> + --> + + <div class="itemBox"> <input type="submit" wicket:id="submitButton" class="lightButtonLink" /> diff --git a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/components/LicenseEditForm.java b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/components/LicenseEditForm.java index 34b7737e..f3f9d4ca 100644 --- a/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/components/LicenseEditForm.java +++ b/src/main/java/cz/zcu/kiv/eegdatabase/wui/ui/licenses/components/LicenseEditForm.java @@ -22,11 +22,14 @@ ******************************************************************************/ package cz.zcu.kiv.eegdatabase.wui.ui.licenses.components; +import java.io.ByteArrayInputStream; import java.math.BigDecimal; import java.util.List; +import cz.zcu.kiv.eegdatabase.wui.core.license.LicenseFacade; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.form.AjaxButton; +import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.ChoiceRenderer; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.FormComponent; @@ -36,10 +39,13 @@ import org.apache.wicket.markup.html.form.RequiredTextField; import org.apache.wicket.markup.html.form.TextArea; import org.apache.wicket.markup.html.form.upload.FileUploadField; +import org.apache.wicket.markup.html.link.ResourceLink; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.request.resource.ByteArrayResource; +import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.wicket.util.lang.Bytes; import cz.zcu.kiv.eegdatabase.data.pojo.License; @@ -55,7 +61,9 @@ public class LicenseEditForm extends Panel { private static final long serialVersionUID = -3134581180799936781L; - + + + private IModel<List<License>> blueprintsModel; protected IModel<License> licenseModel; protected IModel<License> selectedBlueprintModel; @@ -63,7 +71,12 @@ public class LicenseEditForm extends Panel { private boolean displayControls = true; private IModel<Boolean> allowBusiness; private boolean displayRemoveButton = true; - private FileUploadField fileUpload; + private AjaxButton saveButton; + private FormComponent priceInput; + private ResourceLink<Void> downloadLink; + + @SpringBean + LicenseFacade licenseFacade; public LicenseEditForm(String id, IModel<License> model, IModel<Boolean> allowBusiness) { this(id, model, null, allowBusiness); @@ -88,17 +101,23 @@ public LicenseEditForm(String id, IModel<License> model, IModel<List<License>> b private void addFormFields() { FormComponent c = new RequiredTextField("title", new PropertyModel(licenseModel, "title")); c.setLabel(ResourceUtils.getModel("label.license.title")); + c.setEnabled(false); form.add(c); + Label l = new Label("attachmentFileName", new PropertyModel(licenseModel, "attachmentFileName")); + form.add(l); + c = new TextArea("description", new PropertyModel(licenseModel, "description")); c.setLabel(ResourceUtils.getModel("label.license.description")); c.setRequired(true); + c.setEnabled(false); form.add(c); - c = new NumberTextField<BigDecimal>("price", new PropertyModel(licenseModel, "price"), BigDecimal.class).setMinimum(BigDecimal.ZERO); - c.setRequired(true); - c.setLabel(ResourceUtils.getModel("label.license.price")); - form.add(c); + priceInput = new NumberTextField<BigDecimal>("price", new PropertyModel(licenseModel, "price"), BigDecimal.class).setMinimum(BigDecimal.ZERO); + priceInput.setRequired(true); + priceInput.setEnabled(false); + priceInput.setLabel(ResourceUtils.getModel("label.license.price")); + form.add(priceInput); c = new RadioGroup<LicenseType>("licenseType", new PropertyModel<LicenseType>(licenseModel, "licenseType")); c.setLabel(ResourceUtils.getModel("label.license.type")); @@ -111,15 +130,18 @@ protected void onConfigure() { this.setVisible(allowBusiness.getObject()); } }); + c.add(new Radio("public",new Model(LicenseType.OPEN_DOMAIN))); + c.setEnabled(false); form.add(c); WicketUtils.addLabelsAndFeedback(form); - - fileUpload = new FileUploadField("licenseFile"); - fileUpload.setLabel(ResourceUtils.getModel("label.license.attachment.file")); - - form.add(fileUpload); - form.setMaxSize(Bytes.megabytes(15)); + + ByteArrayResource res; + res = new ByteArrayResource(""); + downloadLink = new ResourceLink<Void>("download", res); + downloadLink.setVisible(false); + + form.add(downloadLink); } /** @@ -128,7 +150,7 @@ protected void onConfigure() { * @param cont */ private void addControls() { - AjaxButton button = new AjaxButton("submitButton", ResourceUtils.getModel("button.save")) { + saveButton = new AjaxButton("submitButton", ResourceUtils.getModel("button.save")) { @Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { onSubmitAction(licenseModel, target, form); @@ -147,9 +169,9 @@ protected void onConfigure() { this.setVisible(displayControls); } }; - form.add(button); - - button = new AjaxButton("cancelButton", ResourceUtils.getModel("button.cancel")) { + saveButton.setVisibilityAllowed(false); + form.add(saveButton); + AjaxButton button = new AjaxButton("cancelButton", ResourceUtils.getModel("button.cancel")) { @Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { onCancelAction(licenseModel, target, form); @@ -195,28 +217,70 @@ protected void onConfigure() { viz = false; } this.setVisible(viz); + + } @Override protected void onSelectionChangeAjaxified(AjaxRequestTarget target, License option) { if (option == null || option.getLicenseId() == 0) { licenseModel.setObject(new License()); + saveButton.setVisibilityAllowed(false); + priceInput.setEnabled(false); + downloadLink.setVisible(false); + + } else { + if (option.getLicenseType()== LicenseType.BUSINESS && option.getPrice().intValue() == 0) { + priceInput.setEnabled(true); + } else { + priceInput.setEnabled(false); + } License l = new License(); l.setTitle(option.getTitle()); l.setDescription(option.getDescription()); l.setLicenseType(option.getLicenseType()); l.setPrice(option.getPrice()); - licenseModel.setObject(l); + l.setAttachmentFileName(option.getAttachmentFileName()); + + //l.setFileContentStream(); + + + if (option.getAttachmentFileName()!= null) { + ByteArrayResource res; + System.out.println("---Novy ID: "+option.getLicenseId()+", FileName: "+option.getAttachmentFileName()); + res = new ByteArrayResource("", licenseFacade.getLicenseAttachmentContent(option.getLicenseId()), option.getAttachmentFileName()); + + ResourceLink<Void> newLink = new ResourceLink<Void>("download", res); + + ByteArrayInputStream bis = new ByteArrayInputStream(licenseFacade.getLicenseAttachmentContent(option.getLicenseId())); + l.setFileContentStream(bis); + + downloadLink.remove(); + downloadLink = newLink; + form.add(newLink); + //downloadLink = (ResourceLink<Void>) downloadLink.replaceWith(newLink); + downloadLink.setVisible(true); + + } else { + downloadLink.setVisible(false); + } + licenseModel.setObject(l); + saveButton.setVisibilityAllowed(true); } target.add(form); } }; ddc.setNullValid(true); + form.add(ddc); } + public void setLicenseModel (License license) { + licenseModel.setObject(license); + } + public boolean isDisplayControls() { return displayControls; } @@ -228,10 +292,6 @@ public void setDisplayControls(boolean displayControls) { public boolean isDisplayRemoveButton() { return displayRemoveButton; } - - public FileUploadField getFileUpload() { - return fileUpload; - } public LicenseEditForm setDisplayRemoveButton(boolean displayRemoveButton) { this.displayRemoveButton = displayRemoveButton; diff --git a/src/main/resources/cz/zcu/kiv/eegdatabase/wui/app/EEGDataBaseApplication.properties b/src/main/resources/cz/zcu/kiv/eegdatabase/wui/app/EEGDataBaseApplication.properties index 030385b9..a27d5a19 100644 --- a/src/main/resources/cz/zcu/kiv/eegdatabase/wui/app/EEGDataBaseApplication.properties +++ b/src/main/resources/cz/zcu/kiv/eegdatabase/wui/app/EEGDataBaseApplication.properties @@ -267,6 +267,7 @@ currency.euro=\u20ac dataTable.heading.articleTitle=Article title dataTable.heading.articleText=Article text dataTable.heading.buy=Buy +dataTable.heading.attachmentFile=Attachment file dataTable.heading.addlicence=Add licence dataTable.heading.licenses=Licenses dataTable.heading.count=Count @@ -980,11 +981,14 @@ pageTitle.addWeather=Add weather definition button.addWeatherDefinition=Add weather definition dataTable.heading.type=Type label.type=Type +label.licenseFile=License File +label.file=File pageTitle.editHearingImpairment=Edit hearing impairment button.edit=Edit link.edit=Edit link.addMembershipPlan=Add Membership Plan link.addPromoCode=Add Promo Code +link.addLicense=Add License pageTitle.addEditHearingImpairment=Add/edit hearing impairment pageTitle.editVisualImpairment=Edit visual impairment pageTitle.addEditVisualImpairment=Add/edit visual impairment @@ -1026,6 +1030,7 @@ author=Author text.delete.article=Are you sure you want to delete this article? text.delete.datafile=Are you sure you want delete this data file {0}? text.delete.membershipplan=Are you sure you want to delete this membership plan? +text.delete.licenseTemplate=Are you sure you want to delete this license template? text.delete.promocode=Are you sure you want to delete this promo code? #Search Page
493e8ad45f39306754484ada51bfe397928404fd
ReactiveX-RxJava
additions to tests--
p
https://github.com/ReactiveX/RxJava
diff --git a/language-adaptors/rxjava-groovy/src/test/groovy/rx/lang/groovy/ObservableTests.groovy b/language-adaptors/rxjava-groovy/src/test/groovy/rx/lang/groovy/ObservableTests.groovy index 45b4436724..ceeb25dcf6 100644 --- a/language-adaptors/rxjava-groovy/src/test/groovy/rx/lang/groovy/ObservableTests.groovy +++ b/language-adaptors/rxjava-groovy/src/test/groovy/rx/lang/groovy/ObservableTests.groovy @@ -298,6 +298,31 @@ def class ObservableTests { verify(a, times(1)).received(true); } + + @Test + public void testZip() { + Observable o1 = Observable.from(1, 2, 3); + Observable o2 = Observable.from(4, 5, 6); + Observable o3 = Observable.from(7, 8, 9); + + List values = Observable.zip(o1, o2, o3, {a, b, c -> [a, b, c] }).toList().toBlockingObservable().single(); + assertEquals([1, 4, 7], values.get(0)); + assertEquals([2, 5, 8], values.get(1)); + assertEquals([3, 6, 9], values.get(2)); + } + + @Test + public void testZipWithIterable() { + Observable o1 = Observable.from(1, 2, 3); + Observable o2 = Observable.from(4, 5, 6); + Observable o3 = Observable.from(7, 8, 9); + + List values = Observable.zip([o1, o2, o3], {a, b, c -> [a, b, c] }).toList().toBlockingObservable().single(); + assertEquals([1, 4, 7], values.get(0)); + assertEquals([2, 5, 8], values.get(1)); + assertEquals([3, 6, 9], values.get(2)); + } + @Test public void testGroupBy() { int count=0; diff --git a/rxjava-core/src/test/java/rx/ReduceTests.java b/rxjava-core/src/test/java/rx/ReduceTests.java index 822001e615..1f7ea5550c 100644 --- a/rxjava-core/src/test/java/rx/ReduceTests.java +++ b/rxjava-core/src/test/java/rx/ReduceTests.java @@ -27,6 +27,22 @@ public Integer call(Integer t1, Integer t2) { @Test public void reduceWithObjects() { + Observable<Movie> horrorMovies = Observable.<Movie> from(new HorrorMovie()); + + Func2<Movie, Movie, Movie> chooseSecondMovie = + new Func2<Movie, Movie, Movie>() { + public Movie call(Movie t1, Movie t2) { + return t2; + } + }; + + Observable<Movie> reduceResult = Observable.create(OperationScan.scan(horrorMovies, chooseSecondMovie)).takeLast(1); + + Observable<Movie> reduceResult2 = horrorMovies.reduce(chooseSecondMovie); + } + + @Test + public void reduceWithCovariantObjects() { Observable<HorrorMovie> horrorMovies = Observable.from(new HorrorMovie()); Func2<Movie, Movie, Movie> chooseSecondMovie = @@ -61,8 +77,10 @@ public Movie call(Movie t1, Movie t2) { } }; + Observable<Movie> reduceResult = Observable.create(OperationScan.scan(obs, chooseSecondMovie)).takeLast(1); + //TODO this isn't compiling - // Observable<Movie> reduceResult = obs.reduce((Func2<? super Movie, ? super Movie, ? extends Movie>) chooseSecondMovie); + // Observable<Movie> reduceResult2 = obs.reduce(chooseSecondMovie); // do something with reduceResult... }
fd80155a60d24bee03f7ca0ebeca8d564c87e763
tapiji
Cleans up build scripts. (cherry picked from commit 217a1d57903e87fc44a3ece7a69940943f33cb9f) Conflicts: org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesDeserializer.java org.eclipse.babel.editor/build.properties org.eclipse.babel.tapiji.tools.build/build/maps/tapiji.map
p
https://github.com/tapiji/tapiji
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesDeserializer.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesDeserializer.java index b94146d5..7a78106d 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesDeserializer.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/PropertiesDeserializer.java @@ -1,272 +1,272 @@ -/******************************************************************************* - * Copyright (c) 2007 Pascal Essiembre. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Pascal Essiembre - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.core.message.resource.ser; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Locale; -import java.util.Properties; - -import org.eclipse.babel.core.message.IMessage; -import org.eclipse.babel.core.message.IMessagesBundle; -import org.eclipse.babel.core.message.internal.Message; -import org.eclipse.babel.core.message.internal.MessagesBundle; -import org.eclipse.babel.core.util.BabelUtils; - -/** - * Class responsible for deserializing {@link Properties}-like text into a - * {@link MessagesBundle}. - * - * @author Pascal Essiembre ([email protected]) - */ -public class PropertiesDeserializer { - - /** System line separator. */ - private static final String SYSTEM_LINE_SEPARATOR = System - .getProperty("line.separator"); //$NON-NLS-1$ - - /** Characters accepted as key value separators. */ - private static final String KEY_VALUE_SEPARATORS = "=:"; //$NON-NLS-1$ - - /** MessagesBundle deserializer configuration. */ - private IPropertiesDeserializerConfig config; - - /** - * Constructor. - */ - public PropertiesDeserializer(IPropertiesDeserializerConfig config) { - super(); - this.config = config; - } - - /** - * Parses a string and populates a <code>MessagesBundle</code>. The string - * is expected to match the documented structure of a properties file. - * - * @param messagesBundle - * the target {@link MessagesBundle} - * @param properties - * the string containing the properties to parse - */ - public void deserialize(IMessagesBundle messagesBundle, String properties) { - Locale locale = messagesBundle.getLocale(); - - Collection<String> oldKeys = new ArrayList<String>( - Arrays.asList(messagesBundle.getKeys())); - Collection<String> newKeys = new ArrayList<String>(); - - String[] lines = properties.split("\r\n|\r|\n"); //$NON-NLS-1$ - - boolean doneWithFileComment = false; - StringBuffer fileComment = new StringBuffer(); - StringBuffer lineComment = new StringBuffer(); - StringBuffer lineBuf = new StringBuffer(); - for (int i = 0; i < lines.length; i++) { - String line = lines[i]; - lineBuf.setLength(0); - lineBuf.append(line); - - int equalPosition = findKeyValueSeparator(line); - boolean isRegularLine = line.matches("^[^#].*"); //$NON-NLS-1$ - boolean isCommentedLine = doneWithFileComment - && line.matches("^##[^#].*"); //$NON-NLS-1$ - - // parse regular and commented lines - if (equalPosition >= 1 && (isRegularLine || isCommentedLine)) { - doneWithFileComment = true; - String comment = ""; //$NON-NLS-1$ - if (lineComment.length() > 0) { - comment = lineComment.toString(); - lineComment.setLength(0); - } - - if (isCommentedLine) { - lineBuf.delete(0, 2); // remove ## - equalPosition -= 2; - } - String backslash = "\\"; //$NON-NLS-1$ - while (lineBuf.lastIndexOf(backslash) == lineBuf.length() - 1) { - int lineBreakPosition = lineBuf.lastIndexOf(backslash); - lineBuf.replace(lineBreakPosition, lineBreakPosition + 1, - ""); //$NON-NLS-1$ - if (++i < lines.length) { - String wrappedLine = lines[i].replaceFirst("^\\s*", ""); //$NON-NLS-1$ //$NON-NLS-2$ - if (isCommentedLine) { - lineBuf.append(wrappedLine.replaceFirst("^##", "")); //$NON-NLS-1$ //$NON-NLS-2$ - } else { - lineBuf.append(wrappedLine); - } - } - } - String key = lineBuf.substring(0, equalPosition).trim(); - key = unescapeKey(key); - - String value = lineBuf.substring(equalPosition + 1) - .replaceFirst("^\\s*", ""); //$NON-NLS-1$//$NON-NLS-2$ - // Unescape leading spaces - if (value.startsWith("\\ ")) { //$NON-NLS-1$ - value = value.substring(1); - } - - if (this.config != null && config.isUnicodeUnescapeEnabled()) { - key = convertEncodedToUnicode(key); - value = convertEncodedToUnicode(value); - } else { - value = value.replaceAll("\\\\r", "\r"); //$NON-NLS-1$ //$NON-NLS-2$ - value = value.replaceAll("\\\\n", "\n"); //$NON-NLS-1$//$NON-NLS-2$ - } - IMessage entry = messagesBundle.getMessage(key); - if (entry == null) { - entry = new Message(key, locale); - messagesBundle.addMessage(entry); - } - entry.setActive(!isCommentedLine); - entry.setComment(comment); - entry.setText(value); - newKeys.add(key); - // parse comment line - } else if (lineBuf.indexOf("#") == 0) { //$NON-NLS-1$ - if (!doneWithFileComment) { - fileComment.append(lineBuf); - fileComment.append(SYSTEM_LINE_SEPARATOR); - } else { - lineComment.append(lineBuf); - lineComment.append(SYSTEM_LINE_SEPARATOR); - } - // handle blank or unsupported line - } else { - doneWithFileComment = true; - } - } - oldKeys.removeAll(newKeys); - messagesBundle - .removeMessages(oldKeys.toArray(BabelUtils.EMPTY_STRINGS)); - messagesBundle.setComment(fileComment.toString()); - } - - /** - * Converts encoded &#92;uxxxx to unicode chars and changes special saved - * chars to their original forms - * - * @param str - * the string to convert - * @return converted string - * @see java.util.Properties - */ - private String convertEncodedToUnicode(String str) { - char aChar; - int len = str.length(); - StringBuffer outBuffer = new StringBuffer(len); - - for (int x = 0; x < len;) { - aChar = str.charAt(x++); - if (aChar == '\\' && x + 1 <= len) { - aChar = str.charAt(x++); - if (aChar == 'u' && x + 4 <= len) { - // Read the xxxx - int value = 0; - for (int i = 0; i < 4; i++) { - aChar = str.charAt(x++); - switch (aChar) { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - value = (value << 4) + aChar - '0'; - break; - case 'a': - case 'b': - case 'c': - case 'd': - case 'e': - case 'f': - value = (value << 4) + 10 + aChar - 'a'; - break; - case 'A': - case 'B': - case 'C': - case 'D': - case 'E': - case 'F': - value = (value << 4) + 10 + aChar - 'A'; - break; - default: - value = aChar; - System.err.println("PropertiesDeserializer: " //$NON-NLS-1$ - + "bad character " //$NON-NLS-1$ - + "encoding for string:" //$NON-NLS-1$ - + str); - } - } - outBuffer.append((char) value); - } else { - if (aChar == 't') { - aChar = '\t'; - } else if (aChar == 'r') { - aChar = '\r'; - } else if (aChar == 'n') { - aChar = '\n'; - } else if (aChar == 'f') { - aChar = '\f'; - } else if (aChar == 'u') { - outBuffer.append("\\"); //$NON-NLS-1$ - } - outBuffer.append(aChar); - } - } else { - outBuffer.append(aChar); - } - } - return outBuffer.toString(); - } - - /** - * Finds the separator symbol that separates keys and values. - * - * @param str - * the string on which to find seperator - * @return the separator index or -1 if no separator was found - */ - private int findKeyValueSeparator(String str) { - int index = -1; - int length = str.length(); - for (int i = 0; i < length; i++) { - char currentChar = str.charAt(i); - if (currentChar == '\\') { - i++; - } else if (KEY_VALUE_SEPARATORS.indexOf(currentChar) != -1) { - index = i; - break; - } - } - return index; - } - - private String unescapeKey(String key) { - int length = key.length(); - StringBuffer buf = new StringBuffer(); - for (int index = 0; index < length; index++) { - char currentChar = key.charAt(index); - if (currentChar != '\\') { - buf.append(currentChar); - } - } - return buf.toString(); - } - -} +/******************************************************************************* + * Copyright (c) 2007 Pascal Essiembre. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Pascal Essiembre - initial API and implementation + ******************************************************************************/ +package org.eclipse.babel.core.message.resource.ser; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Locale; + +import org.eclipse.babel.core.message.IMessage; +import org.eclipse.babel.core.message.IMessagesBundle; +import org.eclipse.babel.core.message.internal.Message; +import org.eclipse.babel.core.message.internal.MessagesBundle; +import org.eclipse.babel.core.util.BabelUtils; + +/** + * Class responsible for deserializing {@link Properties}-like text into a + * {@link MessagesBundle}. + * + * @author Pascal Essiembre ([email protected]) + */ +public class PropertiesDeserializer { + + /** System line separator. */ + private static final String SYSTEM_LINE_SEPARATOR = System + .getProperty("line.separator"); //$NON-NLS-1$ + + /** Characters accepted as key value separators. */ + private static final String KEY_VALUE_SEPARATORS = "=:"; //$NON-NLS-1$ + + /** MessagesBundle deserializer configuration. */ + private IPropertiesDeserializerConfig config; + + /** + * Constructor. + */ + public PropertiesDeserializer(IPropertiesDeserializerConfig config) { + super(); + this.config = config; + } + + /** + * Parses a string and populates a <code>MessagesBundle</code>. The string + * is expected to match the documented structure of a properties file. + * + * @param messagesBundle + * the target {@link MessagesBundle} + * @param properties + * the string containing the properties to parse + */ + public void deserialize(IMessagesBundle messagesBundle, String properties) { + Locale locale = messagesBundle.getLocale(); + + Collection<String> oldKeys = new ArrayList<String>( + Arrays.asList(messagesBundle.getKeys())); + Collection<String> newKeys = new ArrayList<String>(); + + String[] lines = properties.split("\r\n|\r|\n"); //$NON-NLS-1$ + + boolean doneWithFileComment = false; + StringBuffer fileComment = new StringBuffer(); + StringBuffer lineComment = new StringBuffer(); + StringBuffer lineBuf = new StringBuffer(); + for (int i = 0; i < lines.length; i++) { + String line = lines[i]; + lineBuf.setLength(0); + lineBuf.append(line); + + int equalPosition = findKeyValueSeparator(line); + boolean isRegularLine = line.matches("^[^#].*"); //$NON-NLS-1$ + boolean isCommentedLine = doneWithFileComment + && line.matches("^##[^#].*"); //$NON-NLS-1$ + + // parse regular and commented lines + if (equalPosition >= 1 && (isRegularLine || isCommentedLine)) { + doneWithFileComment = true; + String comment = ""; //$NON-NLS-1$ + if (lineComment.length() > 0) { + comment = lineComment.toString(); + lineComment.setLength(0); + } + + if (isCommentedLine) { + lineBuf.delete(0, 2); // remove ## + equalPosition -= 2; + } + String backslash = "\\"; //$NON-NLS-1$ + while (lineBuf.lastIndexOf(backslash) == lineBuf.length() - 1) { + int lineBreakPosition = lineBuf.lastIndexOf(backslash); + lineBuf.replace(lineBreakPosition, lineBreakPosition + 1, + ""); //$NON-NLS-1$ + if (++i < lines.length) { + String wrappedLine = lines[i].replaceFirst("^\\s*", ""); //$NON-NLS-1$ //$NON-NLS-2$ + if (isCommentedLine) { + lineBuf.append(wrappedLine.replaceFirst("^##", "")); //$NON-NLS-1$ //$NON-NLS-2$ + } else { + lineBuf.append(wrappedLine); + } + } + } + String key = lineBuf.substring(0, equalPosition).trim(); + key = unescapeKey(key); + + String value = lineBuf.substring(equalPosition + 1) + .replaceFirst("^\\s*", ""); //$NON-NLS-1$//$NON-NLS-2$ + // Unescape leading spaces + if (value.startsWith("\\ ")) { //$NON-NLS-1$ + value = value.substring(1); + } + + if (this.config != null && config.isUnicodeUnescapeEnabled()) { + key = convertEncodedToUnicode(key); + value = convertEncodedToUnicode(value); + } else { + value = value.replaceAll("\\\\r", "\r"); //$NON-NLS-1$ //$NON-NLS-2$ + value = value.replaceAll("\\\\n", "\n"); //$NON-NLS-1$//$NON-NLS-2$ + } + IMessage entry = messagesBundle.getMessage(key); + if (entry == null) { + entry = new Message(key, locale); + messagesBundle.addMessage(entry); + } + entry.setActive(!isCommentedLine); + entry.setComment(comment); + entry.setText(value); + newKeys.add(key); + // parse comment line + } else if (lineBuf.indexOf("#") == 0) { //$NON-NLS-1$ + if (!doneWithFileComment) { + fileComment.append(lineBuf); + fileComment.append(SYSTEM_LINE_SEPARATOR); + } else { + lineComment.append(lineBuf); + lineComment.append(SYSTEM_LINE_SEPARATOR); + } + // handle blank or unsupported line + } else { + doneWithFileComment = true; + } + } + oldKeys.removeAll(newKeys); + messagesBundle + .removeMessages(oldKeys.toArray(BabelUtils.EMPTY_STRINGS)); + messagesBundle.setComment(fileComment.toString()); + } + + /** + * Converts encoded &#92;uxxxx to unicode chars and changes special saved + * chars to their original forms + * + * @param str + * the string to convert + * @return converted string + * @see java.util.Properties + */ + private String convertEncodedToUnicode(String str) { + char aChar; + int len = str.length(); + StringBuffer outBuffer = new StringBuffer(len); + + for (int x = 0; x < len;) { + aChar = str.charAt(x++); + if (aChar == '\\' && x + 1 <= len) { + aChar = str.charAt(x++); + if (aChar == 'u' && x + 4 <= len) { + // Read the xxxx + int value = 0; + for (int i = 0; i < 4; i++) { + aChar = str.charAt(x++); + switch (aChar) { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + value = (value << 4) + aChar - '0'; + break; + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + value = (value << 4) + 10 + aChar - 'a'; + break; + case 'A': + case 'B': + case 'C': + case 'D': + case 'E': + case 'F': + value = (value << 4) + 10 + aChar - 'A'; + break; + default: + value = aChar; + System.err.println("PropertiesDeserializer: " //$NON-NLS-1$ + + "bad character " //$NON-NLS-1$ + + "encoding for string:" //$NON-NLS-1$ + + str); + } + } + outBuffer.append((char) value); + } else { + if (aChar == 't') { + aChar = '\t'; + } else if (aChar == 'r') { + aChar = '\r'; + } else if (aChar == 'n') { + aChar = '\n'; + } else if (aChar == 'f') { + aChar = '\f'; + } else if (aChar == 'u') { + outBuffer.append("\\"); //$NON-NLS-1$ + } + outBuffer.append(aChar); + } + } else { + outBuffer.append(aChar); + } + } + return outBuffer.toString(); + } + + /** + * Finds the separator symbol that separates keys and values. + * + * @param str + * the string on which to find seperator + * @return the separator index or -1 if no separator was found + */ + private int findKeyValueSeparator(String str) { + int index = -1; + int length = str.length(); + for (int i = 0; i < length; i++) { + char currentChar = str.charAt(i); + if (currentChar == '\\') { + i++; + } else if (KEY_VALUE_SEPARATORS.indexOf(currentChar) != -1) { + index = i; + break; + } + } + return index; + } + + private String unescapeKey(String key) { + int length = key.length(); + StringBuffer buf = new StringBuffer(); + for (int index = 0; index < length; index++) { + char currentChar = key.charAt(index); + if (currentChar != '\\') { + buf.append(currentChar); + } + } + return buf.toString(); + } + +} + diff --git a/org.eclipse.babel.editor/build.properties b/org.eclipse.babel.editor/build.properties index 4362a25f..0cedbb06 100644 --- a/org.eclipse.babel.editor/build.properties +++ b/org.eclipse.babel.editor/build.properties @@ -1,14 +1,13 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - plugin.xml,\ - icons/,\ - plugin.properties,\ - messages.properties -src.includes = bin/,\ - icons/,\ - messages.properties,\ - src/,\ - plugin.properties,\ - plugin.xml +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + plugin.xml,\ + icons/,\ + bin/,\ + plugin.properties,\ + messages.properties +src.includes = bin/,\ + icons/,\ + messages.properties + diff --git a/org.eclipse.babel.tapiji.tools.build/build/maps/tapiji.map b/org.eclipse.babel.tapiji.tools.build/build/maps/tapiji.map new file mode 100644 index 00000000..2d2724d8 --- /dev/null +++ b/org.eclipse.babel.tapiji.tools.build/build/maps/tapiji.map @@ -0,0 +1,31 @@ [email protected]=GIT,\ + repo=git.eclipse.org/gitroot/babel/plugins.git,\ + path=org.eclipse.babel.core + [email protected]=GIT,\ + repo=git.eclipse.org/gitroot/babel/plugins.git,\ + path=org.eclipse.babel.editor + [email protected]=GIT,\ + repo=git.eclipse.org/gitroot/babel/plugins.git,\ + path=org.eclipse.babel.editor.nls + [email protected]=GIT,\ + repo=git.eclipse.org/gitroot/babel/plugins.git,\ + path=org.eclipse.babel.tapiji.tools.core + [email protected]=GIT,\ + repo=git.eclipse.org/gitroot/babel/plugins.git,\ + path=org.eclipse.babel.tapiji.tools.core.ui + [email protected]=GIT,\ + repo=git.eclipse.org/gitroot/babel/plugins.git,\ + path=org.eclipse.babel.tapiji.tools.java + [email protected]=GIT,\ + repo=git.eclipse.org/gitroot/babel/plugins.git,\ + path=org.eclipse.babel.tapiji.tools.java.ui + [email protected]=GIT,\ + repo=git.eclipse.org/gitroot/babel/plugins.git,\ + path=/plugins \ No newline at end of file
b629226237ca0f2301da2e9e5899d56a4468012b
Vala
glib-2.0: support Variant objv Fixes bug 729695
a
https://github.com/GNOME/vala/
diff --git a/vapi/glib-2.0.vapi b/vapi/glib-2.0.vapi index a2d8a1be30..531e2129d9 100644 --- a/vapi/glib-2.0.vapi +++ b/vapi/glib-2.0.vapi @@ -4926,6 +4926,18 @@ namespace GLib { [CCode (array_length_type = "size_t")] public string[] dup_bytestring_array (); + #if GLIB_2_30 + public Variant.objv (string[] value); + [CCode (array_length_type = "size_t")] + #if VALA_0_26 + public (unowned string)[] get_objv (); + #else + public string*[] get_objv (); + #endif + [CCode (array_length_type = "size_t")] + public string[] dup_objv (); + #endif + public Variant (string format, ...); // note: the function changes its behaviour when end_ptr is null, so 'out char *' is wrong public Variant.va (string format, char **end_ptr, va_list *app);
982eebf70ff4aebfc200c6373511f1ce0e8667ed
kotlin
better root ns--
p
https://github.com/JetBrains/kotlin
diff --git a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaBridgeConfiguration.java b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaBridgeConfiguration.java index 10f6b61ae373a..c41515e932cb0 100644 --- a/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaBridgeConfiguration.java +++ b/compiler/frontend.java/src/org/jetbrains/jet/lang/resolve/java/JavaBridgeConfiguration.java @@ -19,7 +19,6 @@ import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import org.jetbrains.jet.lang.ModuleConfiguration; -import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.descriptors.NamespaceDescriptor; import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor; import org.jetbrains.jet.lang.psi.JetImportDirective; @@ -72,24 +71,4 @@ public void extendNamespaceScope(@NotNull BindingTrace trace, @NotNull Namespace } - @Override - public NamespaceDescriptor getTopLevelNamespace(@NotNull String shortName) { - NamespaceDescriptor namespaceDescriptor = javaSemanticServices.getDescriptorResolver().resolveNamespace(FqName.topLevel(shortName)); - if (namespaceDescriptor != null) { - return namespaceDescriptor; - } - return delegateConfiguration.getTopLevelNamespace(shortName); - } - - @Override - public void addAllTopLevelNamespacesTo(@NotNull Collection<? super NamespaceDescriptor> topLevelNamespaces) { - NamespaceDescriptor defaultPackage = javaSemanticServices.getDescriptorResolver().resolveNamespace(FqName.ROOT); - assert defaultPackage != null : "Cannot resolve Java's default package"; - for (DeclarationDescriptor declarationDescriptor : defaultPackage.getMemberScope().getAllDescriptors()) { - if (declarationDescriptor instanceof NamespaceDescriptor) { - NamespaceDescriptor namespaceDescriptor = (NamespaceDescriptor) declarationDescriptor; - topLevelNamespaces.add(namespaceDescriptor); - } - } - } } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/DefaultModuleConfiguration.java b/compiler/frontend/src/org/jetbrains/jet/lang/DefaultModuleConfiguration.java index 790b1b184ee79..82bf46581b5ae 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/DefaultModuleConfiguration.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/DefaultModuleConfiguration.java @@ -53,13 +53,4 @@ public void addDefaultImports(@NotNull WritableScope rootScope, @NotNull Collect public void extendNamespaceScope(@NotNull BindingTrace trace, @NotNull NamespaceDescriptor namespaceDescriptor, @NotNull WritableScope namespaceMemberScope) { } - @Override - public NamespaceDescriptor getTopLevelNamespace(@NotNull String shortName) { - return null; - } - - @Override - public void addAllTopLevelNamespacesTo(@NotNull Collection<? super NamespaceDescriptor> topLevelNamespaces) { - } - } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/ModuleConfiguration.java b/compiler/frontend/src/org/jetbrains/jet/lang/ModuleConfiguration.java index 0ed59fcb0383d..5c9c34bedb3e9 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/ModuleConfiguration.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/ModuleConfiguration.java @@ -17,8 +17,6 @@ package org.jetbrains.jet.lang; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.jet.lang.descriptors.ModuleDescriptor; import org.jetbrains.jet.lang.descriptors.NamespaceDescriptor; import org.jetbrains.jet.lang.psi.JetImportDirective; import org.jetbrains.jet.lang.resolve.BindingTrace; @@ -39,14 +37,6 @@ public void addDefaultImports(@NotNull WritableScope rootScope, @NotNull Collect public void extendNamespaceScope(@NotNull BindingTrace trace, @NotNull NamespaceDescriptor namespaceDescriptor, @NotNull WritableScope namespaceMemberScope) { } - @Override - public NamespaceDescriptor getTopLevelNamespace(@NotNull String shortName) { - return null; - } - - @Override - public void addAllTopLevelNamespacesTo(@NotNull Collection<? super NamespaceDescriptor> topLevelNamespaces) { - } }; void addDefaultImports(@NotNull WritableScope rootScope, @NotNull Collection<JetImportDirective> directives); @@ -57,10 +47,4 @@ public void addAllTopLevelNamespacesTo(@NotNull Collection<? super NamespaceDesc */ void extendNamespaceScope(@NotNull BindingTrace trace, @NotNull NamespaceDescriptor namespaceDescriptor, @NotNull WritableScope namespaceMemberScope); - /** This method is called only if no namespace with the same short name is declared in the module itself, or to merge namespaces */ - @Nullable - NamespaceDescriptor getTopLevelNamespace(@NotNull String shortName); - - /** Add all the top-level namespaces from the dependencies of this module into the given collection */ - void addAllTopLevelNamespacesTo(@NotNull Collection<? super NamespaceDescriptor> topLevelNamespaces); } diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TopDownAnalyzer.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TopDownAnalyzer.java index 408fc93b1b543..1b6e1b055d7eb 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TopDownAnalyzer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TopDownAnalyzer.java @@ -288,28 +288,11 @@ private void doAnalyzeFilesWithGivenTrance2(Collection<JetFile> files) { // Import the lang package scope.importScope(JetStandardLibrary.getInstance().getLibraryScope()); + NamespaceDescriptorImpl rootNs = typeHierarchyResolver.createNamespaceDescriptorIfNeeded(null, moduleDescriptor, "<root>", true); + // Import a scope that contains all top-level namespaces that come from dependencies // This makes the namespaces visible at all, does not import themselves - scope.importScope(new JetScopeAdapter(JetScope.EMPTY) { - @Override - public NamespaceDescriptor getNamespace(@NotNull String name) { - // Is it a top-level namespace coming from the dependencies? - NamespaceDescriptor topLevelNamespaceFromConfiguration = configuration.getTopLevelNamespace(name); - if (topLevelNamespaceFromConfiguration != null) { - return topLevelNamespaceFromConfiguration; - } - // Should be null, we are delegating to EMPTY - return super.getNamespace(name); - } - - @NotNull - @Override - public Collection<DeclarationDescriptor> getAllDescriptors() { - List<DeclarationDescriptor> allDescriptors = Lists.newArrayList(); - configuration.addAllTopLevelNamespacesTo(allDescriptors); - return allDescriptors; - } - }); + scope.importScope(rootNs.getMemberScope()); // dummy builder is used because "root" is module descriptor, // namespaces added to module explicitly in diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TypeHierarchyResolver.java b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TypeHierarchyResolver.java index da814eeaa06d1..63a49dd678514 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TypeHierarchyResolver.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/resolve/TypeHierarchyResolver.java @@ -263,7 +263,7 @@ private NamespaceDescriptorImpl createNamespaceDescriptorPathIfNeeded(JetFile fi } @NotNull - private NamespaceDescriptorImpl createNamespaceDescriptorIfNeeded(@Nullable JetFile file, @NotNull NamespaceDescriptorParent owner, @NotNull String name, boolean root) { + public NamespaceDescriptorImpl createNamespaceDescriptorIfNeeded(@Nullable JetFile file, @NotNull NamespaceDescriptorParent owner, @NotNull String name, boolean root) { FqName fqName; NamespaceDescriptorImpl namespaceDescriptor; diff --git a/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java b/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java index a001856ead064..76209a93f713a 100644 --- a/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java +++ b/js/js.translator/src/org/jetbrains/k2js/analyze/AnalyzerFacadeForJS.java @@ -129,13 +129,5 @@ public void extendNamespaceScope(@NotNull BindingTrace trace, @NotNull Namespace @NotNull WritableScope namespaceMemberScope) { } - @Override - public NamespaceDescriptor getTopLevelNamespace(@NotNull String shortName) { - return null; - } - - @Override - public void addAllTopLevelNamespacesTo(@NotNull Collection<? super NamespaceDescriptor> topLevelNamespaces) { - } } }
c23c5d2494aafc4416a98e6768a1f3a3022cd011
elasticsearch
Added support for acknowledgement from other- nodes in open/close index api--The open/close index api now waits for an acknowledgement from all the other nodes before returning its response
a
https://github.com/elastic/elasticsearch
diff --git a/src/main/java/org/elasticsearch/action/admin/indices/close/CloseIndexRequest.java b/src/main/java/org/elasticsearch/action/admin/indices/close/CloseIndexRequest.java index ab524de7a37c8..aea253427b0aa 100644 --- a/src/main/java/org/elasticsearch/action/admin/indices/close/CloseIndexRequest.java +++ b/src/main/java/org/elasticsearch/action/admin/indices/close/CloseIndexRequest.java @@ -45,7 +45,7 @@ public class CloseIndexRequest extends MasterNodeOperationRequest<CloseIndexRequ } /** - * Constructs a new delete index request for the specified index. + * Constructs a new close index request for the specified index. */ public CloseIndexRequest(String... indices) { this.indices = indices; @@ -79,7 +79,7 @@ public CloseIndexRequest indices(String... indices) { } /** - * Timeout to wait for the index deletion to be acknowledged by current cluster nodes. Defaults + * Timeout to wait for the index closure to be acknowledged by current cluster nodes. Defaults * to <tt>10s</tt>. */ TimeValue timeout() { @@ -87,7 +87,7 @@ TimeValue timeout() { } /** - * Timeout to wait for the index deletion to be acknowledged by current cluster nodes. Defaults + * Timeout to wait for the index closure to be acknowledged by current cluster nodes. Defaults * to <tt>10s</tt>. */ public CloseIndexRequest timeout(TimeValue timeout) { @@ -96,7 +96,7 @@ public CloseIndexRequest timeout(TimeValue timeout) { } /** - * Timeout to wait for the index deletion to be acknowledged by current cluster nodes. Defaults + * Timeout to wait for the index closure to be acknowledged by current cluster nodes. Defaults * to <tt>10s</tt>. */ public CloseIndexRequest timeout(String timeout) { diff --git a/src/main/java/org/elasticsearch/action/admin/indices/open/OpenIndexRequest.java b/src/main/java/org/elasticsearch/action/admin/indices/open/OpenIndexRequest.java index ee79644359c38..dd9151b124f81 100644 --- a/src/main/java/org/elasticsearch/action/admin/indices/open/OpenIndexRequest.java +++ b/src/main/java/org/elasticsearch/action/admin/indices/open/OpenIndexRequest.java @@ -45,7 +45,7 @@ public class OpenIndexRequest extends MasterNodeOperationRequest<OpenIndexReques } /** - * Constructs a new delete index request for the specified index. + * Constructs a new open index request for the specified index. */ public OpenIndexRequest(String... indices) { this.indices = indices; @@ -79,7 +79,7 @@ public OpenIndexRequest indices(String... indices) { } /** - * Timeout to wait for the index deletion to be acknowledged by current cluster nodes. Defaults + * Timeout to wait for the index opening to be acknowledged by current cluster nodes. Defaults * to <tt>10s</tt>. */ TimeValue timeout() { @@ -87,7 +87,7 @@ TimeValue timeout() { } /** - * Timeout to wait for the index deletion to be acknowledged by current cluster nodes. Defaults + * Timeout to wait for the index opening to be acknowledged by current cluster nodes. Defaults * to <tt>10s</tt>. */ public OpenIndexRequest timeout(TimeValue timeout) { @@ -96,7 +96,7 @@ public OpenIndexRequest timeout(TimeValue timeout) { } /** - * Timeout to wait for the index deletion to be acknowledged by current cluster nodes. Defaults + * Timeout to wait for the index opening to be acknowledged by current cluster nodes. Defaults * to <tt>10s</tt>. */ public OpenIndexRequest timeout(String timeout) { diff --git a/src/main/java/org/elasticsearch/cluster/ClusterChangedEvent.java b/src/main/java/org/elasticsearch/cluster/ClusterChangedEvent.java index abf7a6af23f11..305b539e25b21 100644 --- a/src/main/java/org/elasticsearch/cluster/ClusterChangedEvent.java +++ b/src/main/java/org/elasticsearch/cluster/ClusterChangedEvent.java @@ -20,12 +20,14 @@ package org.elasticsearch.cluster; import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.cluster.node.DiscoveryNodes; import java.util.List; +import java.util.Map; /** * @@ -161,4 +163,22 @@ public boolean nodesAdded() { public boolean nodesChanged() { return nodesRemoved() || nodesAdded(); } -} + + public boolean indicesStateChanged() { + if (metaDataChanged()) { + ImmutableMap<String,IndexMetaData> indices = state.metaData().indices(); + ImmutableMap<String,IndexMetaData> previousIndices = previousState.metaData().indices(); + + for (Map.Entry<String, IndexMetaData> entry : indices.entrySet()) { + IndexMetaData indexMetaData = entry.getValue(); + IndexMetaData previousIndexMetaData = previousIndices.get(entry.getKey()); + if (previousIndexMetaData != null + && indexMetaData.state() != previousIndexMetaData.state()) { + return true; + } + } + } + + return false; + } +} \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/cluster/ClusterModule.java b/src/main/java/org/elasticsearch/cluster/ClusterModule.java index 2adf89e519692..5df5395f96cc8 100644 --- a/src/main/java/org/elasticsearch/cluster/ClusterModule.java +++ b/src/main/java/org/elasticsearch/cluster/ClusterModule.java @@ -77,5 +77,6 @@ protected void configure() { bind(NodeMappingRefreshAction.class).asEagerSingleton(); bind(MappingUpdatedAction.class).asEagerSingleton(); bind(NodeAliasesUpdatedAction.class).asEagerSingleton(); + bind(NodeIndicesStateUpdatedAction.class).asEagerSingleton(); } } \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/cluster/action/index/NodeIndicesStateUpdatedAction.java b/src/main/java/org/elasticsearch/cluster/action/index/NodeIndicesStateUpdatedAction.java new file mode 100644 index 0000000000000..ad9394fae53fe --- /dev/null +++ b/src/main/java/org/elasticsearch/cluster/action/index/NodeIndicesStateUpdatedAction.java @@ -0,0 +1,154 @@ +/* + * Licensed to ElasticSearch and Shay Banon under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. ElasticSearch licenses this + * file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package org.elasticsearch.cluster.action.index; + +import org.elasticsearch.ElasticSearchException; +import org.elasticsearch.cluster.ClusterService; +import org.elasticsearch.cluster.node.DiscoveryNodes; +import org.elasticsearch.common.component.AbstractComponent; +import org.elasticsearch.common.inject.Inject; +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.io.stream.StreamOutput; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.unit.TimeValue; +import org.elasticsearch.threadpool.ThreadPool; +import org.elasticsearch.transport.*; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +public class NodeIndicesStateUpdatedAction extends AbstractComponent { + + private final ThreadPool threadPool; + + private final TransportService transportService; + + private final ClusterService clusterService; + + private final List<Listener> listeners = new CopyOnWriteArrayList<Listener>(); + + @Inject + public NodeIndicesStateUpdatedAction(Settings settings, ThreadPool threadPool, TransportService transportService, ClusterService clusterService) { + super(settings); + this.threadPool = threadPool; + this.transportService = transportService; + this.clusterService = clusterService; + transportService.registerHandler(NodeIndexStateUpdatedTransportHandler.ACTION, new NodeIndexStateUpdatedTransportHandler()); + } + + public void add(final Listener listener, TimeValue timeout) { + listeners.add(listener); + threadPool.schedule(timeout, ThreadPool.Names.GENERIC, new Runnable() { + @Override + public void run() { + boolean removed = listeners.remove(listener); + if (removed) { + listener.onTimeout(); + } + } + }); + } + + public void remove(Listener listener) { + listeners.remove(listener); + } + + public void nodeIndexStateUpdated(final NodeIndexStateUpdatedResponse response) throws ElasticSearchException { + DiscoveryNodes nodes = clusterService.state().nodes(); + if (nodes.localNodeMaster()) { + threadPool.generic().execute(new Runnable() { + @Override + public void run() { + innerNodeIndexStateUpdated(response); + } + }); + } else { + transportService.sendRequest(clusterService.state().nodes().masterNode(), + NodeIndexStateUpdatedTransportHandler.ACTION, response, EmptyTransportResponseHandler.INSTANCE_SAME); + } + } + + private void innerNodeIndexStateUpdated(NodeIndexStateUpdatedResponse response) { + for (Listener listener : listeners) { + listener.onIndexStateUpdated(response); + } + } + + private class NodeIndexStateUpdatedTransportHandler extends BaseTransportRequestHandler<NodeIndexStateUpdatedResponse> { + + static final String ACTION = "cluster/nodeIndexStateUpdated"; + + @Override + public NodeIndexStateUpdatedResponse newInstance() { + return new NodeIndexStateUpdatedResponse(); + } + + @Override + public void messageReceived(NodeIndexStateUpdatedResponse response, TransportChannel channel) throws Exception { + innerNodeIndexStateUpdated(response); + channel.sendResponse(TransportResponse.Empty.INSTANCE); + } + + @Override + public String executor() { + return ThreadPool.Names.SAME; + } + } + + public static interface Listener { + void onIndexStateUpdated(NodeIndexStateUpdatedResponse response); + void onTimeout(); + } + + public static class NodeIndexStateUpdatedResponse extends TransportRequest { + private String nodeId; + private long version; + + NodeIndexStateUpdatedResponse() { + } + + public NodeIndexStateUpdatedResponse(String nodeId, long version) { + this.nodeId = nodeId; + this.version = version; + } + + public String nodeId() { + return nodeId; + } + + public long version() { + return version; + } + + @Override + public void writeTo(StreamOutput out) throws IOException { + super.writeTo(out); + out.writeString(nodeId); + out.writeLong(version); + } + + @Override + public void readFrom(StreamInput in) throws IOException { + super.readFrom(in); + nodeId = in.readString(); + version = in.readLong(); + } + } +} diff --git a/src/main/java/org/elasticsearch/cluster/metadata/MetaDataStateIndexService.java b/src/main/java/org/elasticsearch/cluster/metadata/MetaDataStateIndexService.java index 9c9272ec84237..4110b8890efc9 100644 --- a/src/main/java/org/elasticsearch/cluster/metadata/MetaDataStateIndexService.java +++ b/src/main/java/org/elasticsearch/cluster/metadata/MetaDataStateIndexService.java @@ -24,6 +24,7 @@ import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.TimeoutClusterStateUpdateTask; +import org.elasticsearch.cluster.action.index.NodeIndicesStateUpdatedAction; import org.elasticsearch.cluster.block.ClusterBlock; import org.elasticsearch.cluster.block.ClusterBlockLevel; import org.elasticsearch.cluster.block.ClusterBlocks; @@ -45,6 +46,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; /** * @@ -57,11 +60,14 @@ public class MetaDataStateIndexService extends AbstractComponent { private final AllocationService allocationService; + private final NodeIndicesStateUpdatedAction indicesStateUpdatedAction; + @Inject - public MetaDataStateIndexService(Settings settings, ClusterService clusterService, AllocationService allocationService) { + public MetaDataStateIndexService(Settings settings, ClusterService clusterService, AllocationService allocationService, NodeIndicesStateUpdatedAction indicesStateUpdatedAction) { super(settings); this.clusterService = clusterService; this.allocationService = allocationService; + this.indicesStateUpdatedAction = indicesStateUpdatedAction; } public void closeIndex(final Request request, final Listener listener) { @@ -127,12 +133,19 @@ public ClusterState execute(ClusterState currentState) { RoutingAllocation.Result routingResult = allocationService.reroute(ClusterState.builder().state(updatedState).routingTable(rtBuilder).build()); - return ClusterState.builder().state(updatedState).routingResult(routingResult).build(); + ClusterState newClusterState = ClusterState.builder().state(updatedState).routingResult(routingResult).build(); + + waitForOtherNodes(newClusterState, listener, request.timeout); + + return newClusterState; } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { - listener.onResponse(new Response(true)); + if (oldState == newState) { + // we didn't do anything, callback + listener.onResponse(new Response(true)); + } } }); } @@ -192,16 +205,32 @@ public ClusterState execute(ClusterState currentState) { RoutingAllocation.Result routingResult = allocationService.reroute(ClusterState.builder().state(updatedState).routingTable(rtBuilder).build()); - return ClusterState.builder().state(updatedState).routingResult(routingResult).build(); + ClusterState newClusterState = ClusterState.builder().state(updatedState).routingResult(routingResult).build(); + + waitForOtherNodes(newClusterState, listener, request.timeout); + + return newClusterState; + } @Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { - listener.onResponse(new Response(true)); + if (oldState == newState) { + // we didn't do anything, callback + listener.onResponse(new Response(true)); + } } }); } + private void waitForOtherNodes(ClusterState updatedState, Listener listener, TimeValue timeout) { + // wait for responses from other nodes if needed + int responseCount = updatedState.nodes().size(); + long version = updatedState.version() + 1; + logger.trace("waiting for [{}] notifications with version [{}]", responseCount, version); + indicesStateUpdatedAction.add(new CountDownListener(responseCount, listener, version), timeout); + } + public static interface Listener { void onResponse(Response response); @@ -242,4 +271,39 @@ public boolean acknowledged() { return acknowledged; } } + + private class CountDownListener implements NodeIndicesStateUpdatedAction.Listener { + + private final AtomicBoolean notified = new AtomicBoolean(); + private final AtomicInteger countDown; + private final Listener listener; + private final long version; + + public CountDownListener(int countDown, Listener listener, long version) { + this.countDown = new AtomicInteger(countDown); + this.listener = listener; + this.version = version; + } + + @Override + public void onIndexStateUpdated(NodeIndicesStateUpdatedAction.NodeIndexStateUpdatedResponse response) { + if (version <= response.version()) { + logger.trace("Received NodeIndexStateUpdatedResponse with version [{}] from [{}]", response.version(), response.nodeId()); + if (countDown.decrementAndGet() == 0) { + indicesStateUpdatedAction.remove(this); + if (notified.compareAndSet(false, true)) { + listener.onResponse(new Response(true)); + } + } + } + } + + @Override + public void onTimeout() { + indicesStateUpdatedAction.remove(this); + if (notified.compareAndSet(false, true)) { + listener.onResponse(new Response(false)); + } + } + } } diff --git a/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java b/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java index 11dd3f0a33f63..82654cdf389f7 100644 --- a/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java +++ b/src/main/java/org/elasticsearch/indices/cluster/IndicesClusterStateService.java @@ -86,6 +86,7 @@ public class IndicesClusterStateService extends AbstractLifecycleComponent<Indic private final NodeMappingCreatedAction nodeMappingCreatedAction; private final NodeMappingRefreshAction nodeMappingRefreshAction; private final NodeAliasesUpdatedAction nodeAliasesUpdatedAction; + private final NodeIndicesStateUpdatedAction nodeIndicesStateUpdatedAction; // a map of mappings type we have seen per index due to cluster state // we need this so we won't remove types automatically created as part of the indexing process @@ -101,7 +102,7 @@ public IndicesClusterStateService(Settings settings, IndicesService indicesServi ShardStateAction shardStateAction, NodeIndexCreatedAction nodeIndexCreatedAction, NodeIndexDeletedAction nodeIndexDeletedAction, NodeMappingCreatedAction nodeMappingCreatedAction, NodeMappingRefreshAction nodeMappingRefreshAction, - NodeAliasesUpdatedAction nodeAliasesUpdatedAction) { + NodeAliasesUpdatedAction nodeAliasesUpdatedAction, NodeIndicesStateUpdatedAction nodeIndicesStateUpdatedAction) { super(settings); this.indicesService = indicesService; this.clusterService = clusterService; @@ -113,6 +114,7 @@ public IndicesClusterStateService(Settings settings, IndicesService indicesServi this.nodeMappingCreatedAction = nodeMappingCreatedAction; this.nodeMappingRefreshAction = nodeMappingRefreshAction; this.nodeAliasesUpdatedAction = nodeAliasesUpdatedAction; + this.nodeIndicesStateUpdatedAction = nodeIndicesStateUpdatedAction; } @Override @@ -167,6 +169,7 @@ public void clusterChanged(final ClusterChangedEvent event) { applyCleanedIndices(event); applySettings(event); sendIndexLifecycleEvents(event); + notifyIndicesStateChanged(event); } } @@ -187,6 +190,13 @@ private void sendIndexLifecycleEvents(final ClusterChangedEvent event) { } } + private void notifyIndicesStateChanged(final ClusterChangedEvent event) { + //handles open/close index notifications + if (event.indicesStateChanged()) { + nodeIndicesStateUpdatedAction.nodeIndexStateUpdated(new NodeIndicesStateUpdatedAction.NodeIndexStateUpdatedResponse(event.state().nodes().localNodeId(), event.state().version())); + } + } + private void applyCleanedIndices(final ClusterChangedEvent event) { // handle closed indices, since they are not allocated on a node once they are closed // so applyDeletedIndices might not take them into account diff --git a/src/test/java/org/elasticsearch/test/integration/AbstractSharedClusterTest.java b/src/test/java/org/elasticsearch/test/integration/AbstractSharedClusterTest.java index 2f63ee648aa9e..9ac6738885b43 100644 --- a/src/test/java/org/elasticsearch/test/integration/AbstractSharedClusterTest.java +++ b/src/test/java/org/elasticsearch/test/integration/AbstractSharedClusterTest.java @@ -127,6 +127,10 @@ public static Client client() { return cluster().client(); } + public static Iterable<Client> clients() { + return cluster().clients(); + } + public ImmutableSettings.Builder randomSettingsBuilder() { // TODO RANDOMIZE return ImmutableSettings.builder(); diff --git a/src/test/java/org/elasticsearch/test/integration/indices/state/OpenCloseIndexTests.java b/src/test/java/org/elasticsearch/test/integration/indices/state/OpenCloseIndexTests.java index f2f5cd421b4d5..f5569aa7f7ba7 100644 --- a/src/test/java/org/elasticsearch/test/integration/indices/state/OpenCloseIndexTests.java +++ b/src/test/java/org/elasticsearch/test/integration/indices/state/OpenCloseIndexTests.java @@ -32,7 +32,6 @@ import org.elasticsearch.test.integration.AbstractSharedClusterTest; import org.junit.Test; -import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; @@ -273,6 +272,21 @@ public void testCloseOpenAliasMultipleIndices() { assertIndexIsOpened("test1", "test2"); } + @Test + public void testSimpleCloseOpenAcknowledged() { + createIndex("test1"); + ClusterHealthResponse healthResponse = client().admin().cluster().prepareHealth().setWaitForGreenStatus().execute().actionGet(); + assertThat(healthResponse.isTimedOut(), equalTo(false)); + + CloseIndexResponse closeIndexResponse = client().admin().indices().prepareClose("test1").execute().actionGet(); + assertThat(closeIndexResponse.isAcknowledged(), equalTo(true)); + assertIndexIsClosedOnAllNodes("test1"); + + OpenIndexResponse openIndexResponse = client().admin().indices().prepareOpen("test1").execute().actionGet(); + assertThat(openIndexResponse.isAcknowledged(), equalTo(true)); + assertIndexIsOpenedOnAllNodes("test1"); + } + private void assertIndexIsOpened(String... indices) { checkIndexState(IndexMetaData.State.OPEN, indices); } @@ -281,12 +295,33 @@ private void assertIndexIsClosed(String... indices) { checkIndexState(IndexMetaData.State.CLOSE, indices); } - private void checkIndexState(IndexMetaData.State state, String... indices) { + private void assertIndexIsOpenedOnAllNodes(String... indices) { + checkIndexStateOnAllNodes(IndexMetaData.State.OPEN, indices); + } + + private void assertIndexIsClosedOnAllNodes(String... indices) { + checkIndexStateOnAllNodes(IndexMetaData.State.CLOSE, indices); + } + + private void checkIndexStateOnAllNodes(IndexMetaData.State state, String... indices) { + //we explicitly check the cluster state on all nodes forcing the local execution + // we want to make sure that acknowledged true means that all the nodes already hold the updated cluster state + for (Client client : clients()) { + ClusterStateResponse clusterStateResponse = client.admin().cluster().prepareState().setLocal(true).execute().actionGet(); + checkIndexState(state, clusterStateResponse, indices); + } + } + + private void checkIndexState(IndexMetaData.State expectedState, String... indices) { ClusterStateResponse clusterStateResponse = client().admin().cluster().prepareState().execute().actionGet(); + checkIndexState(expectedState, clusterStateResponse, indices); + } + + private void checkIndexState(IndexMetaData.State expectedState, ClusterStateResponse clusterState, String... indices) { for (String index : indices) { - IndexMetaData indexMetaData = clusterStateResponse.getState().metaData().indices().get(index); + IndexMetaData indexMetaData = clusterState.getState().metaData().indices().get(index); assertThat(indexMetaData, notNullValue()); - assertThat(indexMetaData.getState(), equalTo(state)); + assertThat(indexMetaData.getState(), equalTo(expectedState)); } } } \ No newline at end of file