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
f57a8e904c824145a350c20fee1240503c7ca3b5
restlet-framework-java
Fixed potential NPE.--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet/src/org/restlet/Client.java b/modules/org.restlet/src/org/restlet/Client.java index 4c7a33a35a..2502fe4f87 100644 --- a/modules/org.restlet/src/org/restlet/Client.java +++ b/modules/org.restlet/src/org/restlet/Client.java @@ -99,7 +99,7 @@ public Client(Context context, List<Protocol> protocols, String helperClass) { this.helper = null; } - if (context != null) { + if (context != null && this.helper != null) { context.getAttributes().put("org.restlet.engine.helper", this.helper); } diff --git a/modules/org.restlet/src/org/restlet/Server.java b/modules/org.restlet/src/org/restlet/Server.java index dde2316ee5..007b75cb7d 100644 --- a/modules/org.restlet/src/org/restlet/Server.java +++ b/modules/org.restlet/src/org/restlet/Server.java @@ -136,7 +136,7 @@ public Server(Context context, List<Protocol> protocols, String address, this.helper = null; } - if (context != null) { + if (context != null && this.helper != null) { context.getAttributes().put("org.restlet.engine.helper", this.helper); }
e5cf1be77c4ef3acf89436789f96fff8c081964f
drools
BZ743283: Decision tables should support timer- column instead of deprecated duration attribute--
a
https://github.com/kiegroup/drools
diff --git a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java index e4ae8fc68f1..73cb78135c8 100644 --- a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java +++ b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/ActionType.java @@ -38,6 +38,8 @@ public enum Code { DESCRIPTION( "DESCRIPTION", "I" ), SALIENCE( "PRIORITY", "P", 1 ), DURATION( "DURATION", "D", 1 ), + TIMER( "TIMER", "T", 1 ), + CALENDARS( "CALENDARS", "E", 1 ), NOLOOP( "NO-LOOP", "U", 1 ), LOCKONACTIVE( "LOCK-ON-ACTIVE", "L", 1 ), AUTOFOCUS( "AUTO-FOCUS", "F", 1 ), diff --git a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java index 18e87a9dfd5..1b9cfa9d465 100644 --- a/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java +++ b/drools-decisiontables/src/main/java/org/drools/decisiontable/parser/DefaultRuleSheetListener.java @@ -211,6 +211,12 @@ private Package buildRuleSet() { getProperties().getSinglePropertyCell( code.getColHeader() ) ); } break; + case TIMER: + ruleset.setTimer( value ); + break; + case CALENDARS: + ruleset.setCalendars( value ); + break; case NOLOOP: ruleset.setNoLoop( RuleSheetParserUtil.isStringMeaningTrue( value ) ); break; @@ -628,6 +634,12 @@ private void nextDataCell(final int row, RuleSheetParserUtil.rc2name( row, column ) ); } break; + case TIMER: + this._currentRule.setTimer( value ); + break; + case CALENDARS: + this._currentRule.setCalendars( value ); + break; } } diff --git a/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java b/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java index 34afbbabd51..eed5edcee92 100644 --- a/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java +++ b/drools-decisiontables/src/test/java/org/drools/decisiontable/SpreadsheetCompilerUnitTest.java @@ -16,16 +16,16 @@ package org.drools.decisiontable; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import java.io.InputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.*; - import org.drools.decisiontable.parser.RuleMatrixSheetListener; +import org.junit.Test; /** * @@ -154,5 +154,61 @@ public void testDeclaresCSV() { assertTrue( drl.indexOf( "declare Smurf name : String end" ) > -1 ); } + @Test + public void testAttributesXLS() { + final SpreadsheetCompiler converter = new SpreadsheetCompiler(); + String drl = converter.compile( "Attributes.xls", + InputType.XLS ); + + assertNotNull( drl ); + + int rule1 = drl.indexOf( "rule \"N1\"" ); + assertFalse( rule1 == -1 ); + + assertTrue( drl.indexOf( "no-loop true", + rule1 ) > -1 ); + assertTrue( drl.indexOf( "duration 100", + rule1 ) > -1 ); + assertTrue( drl.indexOf( "salience 1", + rule1 ) > -1 ); + assertTrue( drl.indexOf( "ruleflow-group \"RFG1\"", + rule1 ) > -1 ); + assertTrue( drl.indexOf( "agenda-group \"AG1\"", + rule1 ) > -1 ); + assertTrue( drl.indexOf( "timer (T1)", + rule1 ) > -1 ); + assertTrue( drl.indexOf( "lock-on-active true", + rule1 ) > -1 ); + assertTrue( drl.indexOf( "activation-group \"g1\"", + rule1 ) > -1 ); + assertTrue( drl.indexOf( "auto-focus true", + rule1 ) > -1 ); + assertTrue( drl.indexOf( "calendars \"CAL1\"", + rule1 ) > -1 ); + + int rule2 = drl.indexOf( "rule \"N2\"" ); + assertFalse( rule2 == -1 ); + + assertTrue( drl.indexOf( "no-loop false", + rule2 ) > -1 ); + assertTrue( drl.indexOf( "duration 200", + rule2 ) > -1 ); + assertTrue( drl.indexOf( "salience 2", + rule2 ) > -1 ); + assertTrue( drl.indexOf( "ruleflow-group \"RFG2\"", + rule2 ) > -1 ); + assertTrue( drl.indexOf( "agenda-group \"AG2\"", + rule2 ) > -1 ); + assertTrue( drl.indexOf( "timer (T2)", + rule2 ) > -1 ); + assertTrue( drl.indexOf( "lock-on-active false", + rule2 ) > -1 ); + assertTrue( drl.indexOf( "activation-group \"g2\"", + rule2 ) > -1 ); + assertTrue( drl.indexOf( "auto-focus false", + rule2 ) > -1 ); + assertTrue( drl.indexOf( "calendars \"CAL2\"", + rule2 ) > -1 ); + } } diff --git a/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java b/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java index 13dcf1710da..cbfc6e9644a 100644 --- a/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java +++ b/drools-decisiontables/src/test/java/org/drools/decisiontable/parser/ActionTypeTest.java @@ -15,18 +15,117 @@ public class ActionTypeTest { @Test public void testChooseActionType() { + Map<Integer, ActionType> actionTypeMap = new HashMap<Integer, ActionType>(); ActionType.addNewActionType( actionTypeMap, "C", 0, 1 ); - ActionType type = (ActionType) actionTypeMap.get( new Integer(0) ); assertEquals( Code.CONDITION, type.getCode() ); - + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "CONDITION", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.CONDITION, type.getCode()); actionTypeMap = new HashMap<Integer, ActionType>(); ActionType.addNewActionType( actionTypeMap, "A", 0, 1 ); type = (ActionType) actionTypeMap.get( new Integer(0) ); assertEquals(Code.ACTION, type.getCode()); + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "ACTION", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.ACTION, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "N", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.NAME, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "NAME", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.NAME, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "I", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.DESCRIPTION, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "DESCRIPTION", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.DESCRIPTION, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "P", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.SALIENCE, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "PRIORITY", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.SALIENCE, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "D", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.DURATION, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "DURATION", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.DURATION, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "T", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.TIMER, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "TIMER", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.TIMER, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "E", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.CALENDARS, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "CALENDARS", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.CALENDARS, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "U", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.NOLOOP, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "NO-LOOP", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.NOLOOP, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "L", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.LOCKONACTIVE, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "LOCK-ON-ACTIVE", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.LOCKONACTIVE, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "F", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.AUTOFOCUS, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "AUTO-FOCUS", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.AUTOFOCUS, type.getCode()); + actionTypeMap = new HashMap<Integer, ActionType>(); ActionType.addNewActionType( actionTypeMap, "X", 0, 1 ); type = (ActionType) actionTypeMap.get( new Integer(0) ); @@ -36,16 +135,37 @@ public void testChooseActionType() { ActionType.addNewActionType( actionTypeMap, "ACTIVATION-GROUP", 0, 1 ); type = (ActionType) actionTypeMap.get( new Integer(0) ); assertEquals(Code.ACTIVATIONGROUP, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "G", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.AGENDAGROUP, type.getCode()); actionTypeMap = new HashMap<Integer, ActionType>(); - ActionType.addNewActionType( actionTypeMap, "NO-LOOP", 0, 1 ); + ActionType.addNewActionType( actionTypeMap, "AGENDA-GROUP", 0, 1 ); type = (ActionType) actionTypeMap.get( new Integer(0) ); - assertEquals(Code.NOLOOP, type.getCode()); + assertEquals(Code.AGENDAGROUP, type.getCode()); + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "R", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.RULEFLOWGROUP, type.getCode()); + actionTypeMap = new HashMap<Integer, ActionType>(); ActionType.addNewActionType( actionTypeMap, "RULEFLOW-GROUP", 0, 1 ); type = (ActionType) actionTypeMap.get( new Integer(0) ); assertEquals(Code.RULEFLOWGROUP, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "@", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.METADATA, type.getCode()); + + actionTypeMap = new HashMap<Integer, ActionType>(); + ActionType.addNewActionType( actionTypeMap, "METADATA", 0, 1 ); + type = (ActionType) actionTypeMap.get( new Integer(0) ); + assertEquals(Code.METADATA, type.getCode()); + } } diff --git a/drools-decisiontables/src/test/resources/org/drools/decisiontable/Attributes.xls b/drools-decisiontables/src/test/resources/org/drools/decisiontable/Attributes.xls new file mode 100644 index 00000000000..3159e4ffeb6 Binary files /dev/null and b/drools-decisiontables/src/test/resources/org/drools/decisiontable/Attributes.xls differ diff --git a/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java b/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java index 9d7dc79663a..b46e25c7c45 100644 --- a/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java +++ b/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java @@ -53,6 +53,14 @@ protected String asStringLiteral( String value ){ return '"' + value.replaceAll( "\"", Matcher.quoteReplacement( "\\\"" ) ) + '"'; } + protected String asTimerLiteral( String value ){ + // Keep the brackets if they come in the right places. + if( value.startsWith( "(" ) && value.endsWith( ")" ) && value.length() >= 2 ){ + value = value.substring( 1, value.length() - 1 ); + } + return "(" + value+ ")"; + } + public void setSalience( final Integer value ){ this._attr2value.put( "salience", Integer.toString( value ) ); } @@ -65,6 +73,14 @@ public void setDuration(final Long value) { this._attr2value.put( "duration", Long.toString( value ) ); } + public void setTimer(final String value) { + this._attr2value.put( "timer", asTimerLiteral( value ) ); + } + + public void setCalendars(final String value) { + this._attr2value.put( "calendars", asStringLiteral( value ) ); + } + public void setActivationGroup(final String value) { this._attr2value.put( "activation-group", asStringLiteral( value ) ); }
44d520ccdb14fce22413efe7e76daa8b1c3d6442
Delta Spike
upgrade tomee and openejb to released versions
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/cdictrl/impl-openejb/pom.xml b/deltaspike/cdictrl/impl-openejb/pom.xml index 09f83f190..599eb7289 100644 --- a/deltaspike/cdictrl/impl-openejb/pom.xml +++ b/deltaspike/cdictrl/impl-openejb/pom.xml @@ -33,7 +33,7 @@ <name>Apache DeltaSpike CDI OpenEJB-ContainerControl</name> <properties> - <openejb.version>4.5.1-SNAPSHOT</openejb.version> + <openejb.version>4.5.0</openejb.version> </properties> <dependencies> diff --git a/deltaspike/parent/pom.xml b/deltaspike/parent/pom.xml index 83d6a40ce..18c625680 100644 --- a/deltaspike/parent/pom.xml +++ b/deltaspike/parent/pom.xml @@ -53,7 +53,7 @@ <!-- testing stuff --> <junit.version>4.10</junit.version> <arquillian.version>1.0.2.Final</arquillian.version> - <tomee.version>1.5.1-SNAPSHOT</tomee.version> + <tomee.version>1.5.0</tomee.version> <!-- JSF-2.0 implementations--> <myfaces2.version>2.0.14</myfaces2.version>
9eb049791037ecb65da18b562ff57804fbd6e942
ReactiveX-RxJava
Performance refactoring: OperatorSubscribeFunction--- migrated Func1 to OperatorSubscribeFunction for internal operator implementations-- do not wrap with AtomicObserver when it's a trusted operator--https://github.com/Netflix/RxJava/issues/104-
p
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/observables/Observable.java b/rxjava-core/src/main/java/rx/observables/Observable.java index adcef9f5a9..79ad9fa84d 100644 --- a/rxjava-core/src/main/java/rx/observables/Observable.java +++ b/rxjava-core/src/main/java/rx/observables/Observable.java @@ -46,6 +46,7 @@ import rx.observables.operations.OperationToObservableList; import rx.observables.operations.OperationToObservableSortedList; import rx.observables.operations.OperationZip; +import rx.observables.operations.OperatorSubscribeFunction; import rx.util.AtomicObservableSubscription; import rx.util.AtomicObserver; import rx.util.functions.Action0; @@ -74,7 +75,7 @@ public class Observable<T> { private final Func1<Observer<T>, Subscription> onSubscribe; - public Observable(Func1<Observer<T>, Subscription> onSubscribe) { + protected Observable(Func1<Observer<T>, Subscription> onSubscribe) { this.onSubscribe = onSubscribe; } @@ -104,16 +105,23 @@ public Observable(Func1<Observer<T>, Subscription> onSubscribe) { * to stop receiving notifications before the provider has finished sending them */ public Subscription subscribe(Observer<T> observer) { - /* - * Wrap the observer and subscription in Atomic* wrappers to: - * - * - ensure correct behavior of onNext, onCompleted and onError. - * - allow the Observer to have access to the subscription in asynchronous execution for checking if unsubscribed occurred without onComplete/onError. - * - handle both synchronous and asynchronous subscribe() execution flows - */ - final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); - final Observer<T> atomicObserver = new AtomicObserver<T>(observer, subscription); - return subscription.wrap(onSubscribe.call(atomicObserver)); + if (onSubscribe instanceof OperatorSubscribeFunction) { + /* + * This means it's a 'trusted' operator so we won't wrap it. + */ + return onSubscribe.call(observer); + } else { + /* + * Wrap the observer and subscription in Atomic* wrappers to: + * + * - ensure correct behavior of onNext, onCompleted and onError. + * - allow the Observer to have access to the subscription in asynchronous execution for checking if unsubscribed occurred without onComplete/onError. + * - handle both synchronous and asynchronous subscribe() execution flows + */ + final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); + final Observer<T> atomicObserver = new AtomicObserver<T>(observer, subscription); + return subscription.wrap(onSubscribe.call(atomicObserver)); + } }; @SuppressWarnings({ "rawtypes", "unchecked" }) diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationCombineLatest.java b/rxjava-core/src/main/java/rx/observables/operations/OperationCombineLatest.java index c1444e7e9b..d689a07bc0 100644 --- a/rxjava-core/src/main/java/rx/observables/operations/OperationCombineLatest.java +++ b/rxjava-core/src/main/java/rx/observables/operations/OperationCombineLatest.java @@ -103,7 +103,7 @@ public void onNext(Object args) { * * @param <R> */ - private static class Aggregator<R> implements Func1<Observer<R>, Subscription> { + private static class Aggregator<R> implements OperatorSubscribeFunction<R> { private final FuncN<R> combineLatestFunction; private Observer<R> Observer; diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationFilter.java b/rxjava-core/src/main/java/rx/observables/operations/OperationFilter.java index b26ef84b24..119635cc2d 100644 --- a/rxjava-core/src/main/java/rx/observables/operations/OperationFilter.java +++ b/rxjava-core/src/main/java/rx/observables/operations/OperationFilter.java @@ -24,6 +24,7 @@ import rx.observables.Observable; import rx.observables.Observer; import rx.observables.Subscription; +import rx.util.AtomicObservableSubscription; import rx.util.functions.Func1; public final class OperationFilter<T> { @@ -32,10 +33,11 @@ public static <T> Func1<Observer<T>, Subscription> filter(Observable<T> that, Fu return new Filter<T>(that, predicate); } - private static class Filter<T> implements Func1<Observer<T>, Subscription> { + private static class Filter<T> implements OperatorSubscribeFunction<T> { private final Observable<T> that; private final Func1<T, Boolean> predicate; + private final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); public Filter(Observable<T> that, Func1<T, Boolean> predicate) { this.that = that; @@ -43,7 +45,7 @@ public Filter(Observable<T> that, Func1<T, Boolean> predicate) { } public Subscription call(final Observer<T> observer) { - return that.subscribe(new Observer<T>() { + return subscription.wrap(that.subscribe(new Observer<T>() { public void onNext(T value) { try { if ((boolean) predicate.call(value)) { @@ -51,7 +53,8 @@ public void onNext(T value) { } } catch (Exception ex) { observer.onError(ex); - // TODO is there a way to tell 'that' to unsubscribe if we have an error? + // this will work if the sequence is asynchronous, it will have no effect on a synchronous observable + subscription.unsubscribe(); } } @@ -62,7 +65,7 @@ public void onError(Exception ex) { public void onCompleted() { observer.onCompleted(); } - }); + })); } } diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationLast.java b/rxjava-core/src/main/java/rx/observables/operations/OperationLast.java index 4bdd125f1d..465ee7b391 100644 --- a/rxjava-core/src/main/java/rx/observables/operations/OperationLast.java +++ b/rxjava-core/src/main/java/rx/observables/operations/OperationLast.java @@ -40,7 +40,7 @@ public static <T> Func1<Observer<T>, Subscription> last(Observable<T> observable return new Last<T>(observable); } - private static class Last<T> implements Func1<Observer<T>, Subscription> { + private static class Last<T> implements OperatorSubscribeFunction<T> { private final AtomicReference<T> lastValue = new AtomicReference<T>(); private final Observable<T> that; diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationMap.java b/rxjava-core/src/main/java/rx/observables/operations/OperationMap.java index c1a689814c..0f19468b9a 100644 --- a/rxjava-core/src/main/java/rx/observables/operations/OperationMap.java +++ b/rxjava-core/src/main/java/rx/observables/operations/OperationMap.java @@ -79,7 +79,7 @@ public static <T, R> Func1<Observer<R>, Subscription> mapMany(Observable<T> sequ * @param <R> * the type of the output sequence. */ - private static class MapObservable<T, R> implements Func1<Observer<R>, Subscription> { + private static class MapObservable<T, R> implements OperatorSubscribeFunction<R> { public MapObservable(Observable<T> sequence, Func1<T, R> func) { this.sequence = sequence; this.func = func; diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationMaterialize.java b/rxjava-core/src/main/java/rx/observables/operations/OperationMaterialize.java index 8c81d46ba5..f941c31edc 100644 --- a/rxjava-core/src/main/java/rx/observables/operations/OperationMaterialize.java +++ b/rxjava-core/src/main/java/rx/observables/operations/OperationMaterialize.java @@ -49,7 +49,7 @@ public static <T> Func1<Observer<Notification<T>>, Subscription> materialize(fin return new MaterializeObservable<T>(sequence); } - private static class MaterializeObservable<T> implements Func1<Observer<Notification<T>>, Subscription> { + private static class MaterializeObservable<T> implements OperatorSubscribeFunction<Notification<T>> { private final Observable<T> sequence; diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationMerge.java b/rxjava-core/src/main/java/rx/observables/operations/OperationMerge.java index 21d3791950..10f701abb2 100644 --- a/rxjava-core/src/main/java/rx/observables/operations/OperationMerge.java +++ b/rxjava-core/src/main/java/rx/observables/operations/OperationMerge.java @@ -46,7 +46,7 @@ public final class OperationMerge { */ public static <T> Func1<Observer<T>, Subscription> merge(final Observable<Observable<T>> o) { // wrap in a Func so that if a chain is built up, then asynchronously subscribed to twice we will have 2 instances of Take<T> rather than 1 handing both, which is not thread-safe. - return new Func1<Observer<T>, Subscription>() { + return new OperatorSubscribeFunction<T>() { @Override public Subscription call(Observer<T> observer) { @@ -56,7 +56,7 @@ public Subscription call(Observer<T> observer) { } public static <T> Func1<Observer<T>, Subscription> merge(final Observable<T>... sequences) { - return merge(Observable.create(new Func1<Observer<Observable<T>>, Subscription>() { + return merge(Observable.create(new OperatorSubscribeFunction<Observable<T>>() { private volatile boolean unsubscribed = false; @Override @@ -85,7 +85,7 @@ public void unsubscribe() { } public static <T> Func1<Observer<T>, Subscription> merge(final List<Observable<T>> sequences) { - return merge(Observable.create(new Func1<Observer<Observable<T>>, Subscription>() { + return merge(Observable.create(new OperatorSubscribeFunction<Observable<T>>() { private volatile boolean unsubscribed = false; @@ -126,7 +126,7 @@ public void unsubscribe() { * * @param <T> */ - private static final class MergeObservable<T> implements Func1<Observer<T>, Subscription> { + private static final class MergeObservable<T> implements OperatorSubscribeFunction<T> { private final Observable<Observable<T>> sequences; private final MergeSubscription ourSubscription = new MergeSubscription(); private AtomicBoolean stopped = new AtomicBoolean(false); diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationMergeDelayError.java b/rxjava-core/src/main/java/rx/observables/operations/OperationMergeDelayError.java index cc7d15c80a..11d0ddd662 100644 --- a/rxjava-core/src/main/java/rx/observables/operations/OperationMergeDelayError.java +++ b/rxjava-core/src/main/java/rx/observables/operations/OperationMergeDelayError.java @@ -58,7 +58,7 @@ public final class OperationMergeDelayError { */ public static <T> Func1<Observer<T>, Subscription> mergeDelayError(final Observable<Observable<T>> sequences) { // wrap in a Func so that if a chain is built up, then asynchronously subscribed to twice we will have 2 instances of Take<T> rather than 1 handing both, which is not thread-safe. - return new Func1<Observer<T>, Subscription>() { + return new OperatorSubscribeFunction<T>() { @Override public Subscription call(Observer<T> observer) { @@ -68,7 +68,7 @@ public Subscription call(Observer<T> observer) { } public static <T> Func1<Observer<T>, Subscription> mergeDelayError(final Observable<T>... sequences) { - return mergeDelayError(Observable.create(new Func1<Observer<Observable<T>>, Subscription>() { + return mergeDelayError(Observable.create(new OperatorSubscribeFunction<Observable<T>>() { private volatile boolean unsubscribed = false; @Override @@ -97,7 +97,7 @@ public void unsubscribe() { } public static <T> Func1<Observer<T>, Subscription> mergeDelayError(final List<Observable<T>> sequences) { - return mergeDelayError(Observable.create(new Func1<Observer<Observable<T>>, Subscription>() { + return mergeDelayError(Observable.create(new OperatorSubscribeFunction<Observable<T>>() { private volatile boolean unsubscribed = false; @@ -138,7 +138,7 @@ public void unsubscribe() { * * @param <T> */ - private static final class MergeDelayErrorObservable<T> implements Func1<Observer<T>, Subscription> { + private static final class MergeDelayErrorObservable<T> implements OperatorSubscribeFunction<T> { private final Observable<Observable<T>> sequences; private final MergeSubscription ourSubscription = new MergeSubscription(); private AtomicBoolean stopped = new AtomicBoolean(false); @@ -848,7 +848,6 @@ private static class CaptureObserver implements Observer<String> { @Override public void onCompleted() { - // TODO Auto-generated method stub } @@ -859,7 +858,6 @@ public void onError(Exception e) { @Override public void onNext(String args) { - // TODO Auto-generated method stub } diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorResumeNextViaFunction.java b/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorResumeNextViaFunction.java index 06d6bbdf05..d041b9b0b7 100644 --- a/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorResumeNextViaFunction.java +++ b/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorResumeNextViaFunction.java @@ -38,7 +38,7 @@ public static <T> Func1<Observer<T>, Subscription> onErrorResumeNextViaFunction( return new OnErrorResumeNextViaFunction<T>(originalSequence, resumeFunction); } - private static class OnErrorResumeNextViaFunction<T> implements Func1<Observer<T>, Subscription> { + private static class OnErrorResumeNextViaFunction<T> implements OperatorSubscribeFunction<T> { private final Func1<Exception, Observable<T>> resumeFunction; private final Observable<T> originalSequence; diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorResumeNextViaObservable.java b/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorResumeNextViaObservable.java index c7da6bdee2..33fe9ee227 100644 --- a/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorResumeNextViaObservable.java +++ b/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorResumeNextViaObservable.java @@ -36,7 +36,7 @@ public static <T> Func1<Observer<T>, Subscription> onErrorResumeNextViaObservabl return new OnErrorResumeNextViaObservable<T>(originalSequence, resumeSequence); } - private static class OnErrorResumeNextViaObservable<T> implements Func1<Observer<T>, Subscription> { + private static class OnErrorResumeNextViaObservable<T> implements OperatorSubscribeFunction<T> { private final Observable<T> resumeSequence; private final Observable<T> originalSequence; diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorReturn.java b/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorReturn.java index 7f76433c10..8b8a988c3b 100644 --- a/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorReturn.java +++ b/rxjava-core/src/main/java/rx/observables/operations/OperationOnErrorReturn.java @@ -41,7 +41,7 @@ public static <T> Func1<Observer<T>, Subscription> onErrorReturn(Observable<T> o return new OnErrorReturn<T>(originalSequence, resumeFunction); } - private static class OnErrorReturn<T> implements Func1<Observer<T>, Subscription> { + private static class OnErrorReturn<T> implements OperatorSubscribeFunction<T> { private final Func1<Exception, T> resumeFunction; private final Observable<T> originalSequence; diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationScan.java b/rxjava-core/src/main/java/rx/observables/operations/OperationScan.java index e7c09b0f83..7752bb2549 100644 --- a/rxjava-core/src/main/java/rx/observables/operations/OperationScan.java +++ b/rxjava-core/src/main/java/rx/observables/operations/OperationScan.java @@ -25,6 +25,7 @@ import rx.observables.Observable; import rx.observables.Observer; import rx.observables.Subscription; +import rx.util.AtomicObservableSubscription; import rx.util.functions.Func1; import rx.util.functions.Func2; @@ -61,10 +62,11 @@ public static <T> Func1<Observer<T>, Subscription> scan(Observable<T> sequence, return new Accumulator<T>(sequence, null, accumulator); } - private static class Accumulator<T> implements Func1<Observer<T>, Subscription> { + private static class Accumulator<T> implements OperatorSubscribeFunction<T> { private final Observable<T> sequence; private final T initialValue; private Func2<T, T, T> accumlatorFunction; + private final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); private Accumulator(Observable<T> sequence, T initialValue, Func2<T, T, T> accumulator) { this.sequence = sequence; @@ -74,7 +76,7 @@ private Accumulator(Observable<T> sequence, T initialValue, Func2<T, T, T> accum public Subscription call(final Observer<T> observer) { - return sequence.subscribe(new Observer<T>() { + return subscription.wrap(sequence.subscribe(new Observer<T>() { private T acc = initialValue; private boolean hasSentInitialValue = false; @@ -108,7 +110,8 @@ public synchronized void onNext(T value) { observer.onNext(acc); } catch (Exception ex) { observer.onError(ex); - // TODO is there a correct way to unsubscribe from the sequence? + // this will work if the sequence is asynchronous, it will have no effect on a synchronous observable + subscription.unsubscribe(); } } @@ -124,7 +127,7 @@ public synchronized void onCompleted() { } observer.onCompleted(); } - }); + })); } } diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationSkip.java b/rxjava-core/src/main/java/rx/observables/operations/OperationSkip.java index 35c470af1e..15d4e76cf0 100644 --- a/rxjava-core/src/main/java/rx/observables/operations/OperationSkip.java +++ b/rxjava-core/src/main/java/rx/observables/operations/OperationSkip.java @@ -62,7 +62,7 @@ public Subscription call(Observer<T> observer) { * * @param <T> */ - private static class Skip<T> implements Func1<Observer<T>, Subscription> { + private static class Skip<T> implements OperatorSubscribeFunction<T> { private final int num; private final Observable<T> items; diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationSynchronize.java b/rxjava-core/src/main/java/rx/observables/operations/OperationSynchronize.java index 6258c7703f..b6d3ad36c3 100644 --- a/rxjava-core/src/main/java/rx/observables/operations/OperationSynchronize.java +++ b/rxjava-core/src/main/java/rx/observables/operations/OperationSynchronize.java @@ -58,7 +58,7 @@ public static <T> Func1<Observer<T>, Subscription> synchronize(Observable<T> obs return new Synchronize<T>(observable); } - private static class Synchronize<T> implements Func1<Observer<T>, Subscription> { + private static class Synchronize<T> implements OperatorSubscribeFunction<T> { public Synchronize(Observable<T> innerObservable) { this.innerObservable = innerObservable; diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationTake.java b/rxjava-core/src/main/java/rx/observables/operations/OperationTake.java index 676887d8fb..7d6bed7b71 100644 --- a/rxjava-core/src/main/java/rx/observables/operations/OperationTake.java +++ b/rxjava-core/src/main/java/rx/observables/operations/OperationTake.java @@ -26,6 +26,7 @@ import rx.observables.Observable; import rx.observables.Observer; import rx.observables.Subscription; +import rx.util.AtomicObservableSubscription; import rx.util.functions.Func1; /** @@ -44,7 +45,7 @@ public final class OperationTake { */ public static <T> Func1<Observer<T>, Subscription> take(final Observable<T> items, final int num) { // wrap in a Watchbable so that if a chain is built up, then asynchronously subscribed to twice we will have 2 instances of Take<T> rather than 1 handing both, which is not thread-safe. - return new Func1<Observer<T>, Subscription>() { + return new OperatorSubscribeFunction<T>() { @Override public Subscription call(Observer<T> observer) { @@ -65,9 +66,10 @@ public Subscription call(Observer<T> observer) { * * @param <T> */ - private static class Take<T> implements Func1<Observer<T>, Subscription> { + private static class Take<T> implements OperatorSubscribeFunction<T> { private final int num; private final Observable<T> items; + private final AtomicObservableSubscription subscription = new AtomicObservableSubscription(); Take(final Observable<T> items, final int num) { this.num = num; @@ -75,7 +77,7 @@ private static class Take<T> implements Func1<Observer<T>, Subscription> { } public Subscription call(Observer<T> observer) { - return items.subscribe(new ItemObserver(observer)); + return subscription.wrap(items.subscribe(new ItemObserver(observer))); } /** @@ -105,8 +107,8 @@ public void onNext(T args) { if (counter.getAndIncrement() < num) { observer.onNext(args); } else { - observer.onCompleted(); - // TODO do we need to unsubscribe here? + // this will work if the sequence is asynchronous, it will have no effect on a synchronous observable + subscription.unsubscribe(); } } @@ -168,8 +170,7 @@ public void testUnsubscribeAfterTake() { verify(aObserver, times(1)).onNext("one"); verify(aObserver, never()).onNext("two"); verify(aObserver, never()).onNext("three"); - // TODO commented this out for now as it's broken and I'm questioning whether it needs to be - // verify(s, times(1)).unsubscribe(); + verify(s, times(1)).unsubscribe(); } private static class TestObservable extends Observable<String> { diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableIterable.java b/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableIterable.java index 0c58e0411c..802a25bac3 100644 --- a/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableIterable.java +++ b/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableIterable.java @@ -40,7 +40,7 @@ public static <T> Func1<Observer<T>, Subscription> toObservableIterable(Iterable return new ToObservableIterable<T>(list); } - private static class ToObservableIterable<T> implements Func1<Observer<T>, Subscription> { + private static class ToObservableIterable<T> implements OperatorSubscribeFunction<T> { public ToObservableIterable(Iterable<T> list) { this.iterable = list; } diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableList.java b/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableList.java index 4b4ef30e44..3c5673b860 100644 --- a/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableList.java +++ b/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableList.java @@ -37,7 +37,7 @@ public static <T> Func1<Observer<List<T>>, Subscription> toObservableList(Observ return new ToObservableList<T>(that); } - private static class ToObservableList<T> implements Func1<Observer<List<T>>, Subscription> { + private static class ToObservableList<T> implements OperatorSubscribeFunction<List<T>> { private final Observable<T> that; final ConcurrentLinkedQueue<T> list = new ConcurrentLinkedQueue<T>(); diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableSortedList.java b/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableSortedList.java index 7f5c99112d..de17b17345 100644 --- a/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableSortedList.java +++ b/rxjava-core/src/main/java/rx/observables/operations/OperationToObservableSortedList.java @@ -64,7 +64,7 @@ public static <T> Func1<Observer<List<T>>, Subscription> toSortedList(Observable return new ToObservableSortedList<T>(sequence, sortFunction); } - private static class ToObservableSortedList<T> implements Func1<Observer<List<T>>, Subscription> { + private static class ToObservableSortedList<T> implements OperatorSubscribeFunction<List<T>> { private final Observable<T> that; private final ConcurrentLinkedQueue<T> list = new ConcurrentLinkedQueue<T>(); diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperationZip.java b/rxjava-core/src/main/java/rx/observables/operations/OperationZip.java index 0b4fa26fba..43e816afe3 100644 --- a/rxjava-core/src/main/java/rx/observables/operations/OperationZip.java +++ b/rxjava-core/src/main/java/rx/observables/operations/OperationZip.java @@ -112,7 +112,7 @@ public void onNext(T args) { * @param <R> */ @ThreadSafe - private static class Aggregator<R> implements Func1<Observer<R>, Subscription> { + private static class Aggregator<R> implements OperatorSubscribeFunction<R> { private volatile AtomicObserverSingleThreaded<R> observer; private final FuncN<R> zipFunction; diff --git a/rxjava-core/src/main/java/rx/observables/operations/OperatorSubscribeFunction.java b/rxjava-core/src/main/java/rx/observables/operations/OperatorSubscribeFunction.java new file mode 100644 index 0000000000..c755dff760 --- /dev/null +++ b/rxjava-core/src/main/java/rx/observables/operations/OperatorSubscribeFunction.java @@ -0,0 +1,25 @@ +package rx.observables.operations; + +import rx.observables.Observable; +import rx.observables.Observer; +import rx.observables.Subscription; +import rx.util.AtomicObserver; +import rx.util.functions.Func1; + +/** + * A "marker" interface used for internal operators implementing the "subscribe" function and turned into Observables using {@link Observable#create(Func1)}. + * <p> + * This marker is used by it to treat these implementations as "trusted". + * <p> + * NOTE: If you use this interface you are declaring that your implementation: + * <ul> + * <li>is thread-safe</li> + * <li>doesn't need additional wrapping by {@link AtomicObserver}</li> + * <li>obeys the contract of onNext, onError, onComplete</li> + * </ul> + * + * @param <T> + */ +public interface OperatorSubscribeFunction<T> extends Func1<Observer<T>, Subscription> { + +} diff --git a/rxjava-core/src/main/java/rx/util/functions/Functions.java b/rxjava-core/src/main/java/rx/util/functions/Functions.java index 518283c87a..6b9237cdf1 100644 --- a/rxjava-core/src/main/java/rx/util/functions/Functions.java +++ b/rxjava-core/src/main/java/rx/util/functions/Functions.java @@ -91,12 +91,6 @@ public static FuncN from(final Object function) { } else { /* not an Rx Function so try language adaptors */ - /* - * TODO the following code needs to be evaluated for performance - * - * The c.isInstance and keySet() functions may be areas of concern with as often as this will be executed - */ - // check for language adaptor for (final Class c : languageAdaptors.keySet()) { if (c.isInstance(function)) {
c43bb2308d62c558eac5708338b5a666c3fbfa66
Valadoc
libvaladoc: @throws: Check for unthrown exceptions
a
https://github.com/GNOME/vala/
diff --git a/src/libvaladoc/taglets/tagletthrows.vala b/src/libvaladoc/taglets/tagletthrows.vala index 547fbc7ca6..986e797c9b 100644 --- a/src/libvaladoc/taglets/tagletthrows.vala +++ b/src/libvaladoc/taglets/tagletthrows.vala @@ -43,6 +43,20 @@ public class Valadoc.Taglets.Throws : InlineContent, Taglet, Block { reporter.simple_error ("%s does not exist", error_domain_name); } + + Gee.List<Api.Node> exceptions = container.get_children_by_types ({Api.NodeType.ERROR_DOMAIN, Api.NodeType.CLASS}, false); + bool report_warning = true; + foreach (Api.Node exception in exceptions) { + if (exception == error_domain || exception is Api.Class) { + report_warning = false; + break; + } + } + if (report_warning) { + reporter.simple_warning ("%s does not exist in exception list", error_domain_name); + } + + base.check (api_root, container, file_path, reporter, settings); }
1e963ac59cfb9250c735d13ef5b9c9f8bb1a549c
Delta Spike
add jbosas-managed-7 profile in ds-data
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/modules/data/impl/pom.xml b/deltaspike/modules/data/impl/pom.xml index bf063648c..27537182b 100755 --- a/deltaspike/modules/data/impl/pom.xml +++ b/deltaspike/modules/data/impl/pom.xml @@ -152,6 +152,19 @@ </testResources> </build> </profile> + <profile> + <id>jbossas-managed-7</id> + <build> + <testResources> + <testResource> + <directory>src/test/resources</directory> + </testResource> + <testResource> + <directory>src/test/resources-jbossas7</directory> + </testResource> + </testResources> + </build> + </profile> <profile> <id>glassfish-remote-3.1</id> <build>
1cfea5ddbdda59ea7b6194aab353b6baf519a8a5
Valadoc
libvaladoc: Api.Class: Add is_compact
a
https://github.com/GNOME/vala/
diff --git a/src/driver/0.10.x/treebuilder.vala b/src/driver/0.10.x/treebuilder.vala index 01f22f1687..6420cb7542 100644 --- a/src/driver/0.10.x/treebuilder.vala +++ b/src/driver/0.10.x/treebuilder.vala @@ -212,6 +212,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { "ErrorBase", "NoReturn", "NoThrow", + "Compact", "Assert", "Flags" }; diff --git a/src/driver/0.12.x/treebuilder.vala b/src/driver/0.12.x/treebuilder.vala index f67d642794..bf559ae302 100644 --- a/src/driver/0.12.x/treebuilder.vala +++ b/src/driver/0.12.x/treebuilder.vala @@ -212,6 +212,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { "ErrorBase", "NoReturn", "NoThrow", + "Compact", "Assert", "Flags" }; diff --git a/src/driver/0.14.x/treebuilder.vala b/src/driver/0.14.x/treebuilder.vala index 795aa97977..d9cdfa6eb5 100644 --- a/src/driver/0.14.x/treebuilder.vala +++ b/src/driver/0.14.x/treebuilder.vala @@ -208,6 +208,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { "ErrorBase", "NoReturn", "NoThrow", + "Compact", "Assert", "Flags" }; diff --git a/src/driver/0.16.x/treebuilder.vala b/src/driver/0.16.x/treebuilder.vala index 8bf06f310e..9629d854d3 100644 --- a/src/driver/0.16.x/treebuilder.vala +++ b/src/driver/0.16.x/treebuilder.vala @@ -216,6 +216,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { "ErrorBase", "NoReturn", "NoThrow", + "Compact", "Assert", "Flags" }; diff --git a/src/driver/0.18.x/treebuilder.vala b/src/driver/0.18.x/treebuilder.vala index 37f44bd9d1..b2538910c9 100644 --- a/src/driver/0.18.x/treebuilder.vala +++ b/src/driver/0.18.x/treebuilder.vala @@ -220,6 +220,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { "ErrorBase", "NoReturn", "NoThrow", + "Compact", "Assert", "Flags" }; diff --git a/src/libvaladoc/api/class.vala b/src/libvaladoc/api/class.vala index 0c5a7a5c1e..8176b6d0f9 100644 --- a/src/libvaladoc/api/class.vala +++ b/src/libvaladoc/api/class.vala @@ -250,6 +250,12 @@ public class Valadoc.Api.Class : TypeSymbol { get; } + public bool is_compact { + get { + return base_type == null && get_attribute ("Compact") != null; + } + } + /** * {@inheritDoc} */
55e73275ec32b059968a12b20190262ce5db1209
Delta Spike
upgrade owb.version to 1.1.7 which is the latest released version
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/parent/pom.xml b/deltaspike/parent/pom.xml index 843f81001..9c1842fef 100644 --- a/deltaspike/parent/pom.xml +++ b/deltaspike/parent/pom.xml @@ -47,7 +47,7 @@ <inceptionYear>2011</inceptionYear> <properties> - <owb.version>1.1.6</owb.version> + <owb.version>1.1.7</owb.version> <weld.version>1.1.10.Final</weld.version> <!-- testing stuff -->
8eb76715a1a4a7cabc56a17c0d44bc6bb9d2ebcf
ReactiveX-RxJava
Add Single.doAfterTerminate()--
a
https://github.com/ReactiveX/RxJava
diff --git a/src/main/java/rx/Single.java b/src/main/java/rx/Single.java index b577f9a812..3880da9b0c 100644 --- a/src/main/java/rx/Single.java +++ b/src/main/java/rx/Single.java @@ -36,6 +36,7 @@ import rx.internal.operators.OperatorDelay; import rx.internal.operators.OperatorDoOnEach; import rx.internal.operators.OperatorDoOnUnsubscribe; +import rx.internal.operators.OperatorFinally; import rx.internal.operators.OperatorMap; import rx.internal.operators.OperatorObserveOn; import rx.internal.operators.OperatorOnErrorReturn; @@ -2020,4 +2021,25 @@ public void call(SingleSubscriber<? super T> singleSubscriber) { public final Single<T> doOnUnsubscribe(final Action0 action) { return lift(new OperatorDoOnUnsubscribe<T>(action)); } + + /** + * Registers an {@link Action0} to be called when this {@link Single} invokes either + * {@link SingleSubscriber#onSuccess(Object)} onSuccess} or {@link SingleSubscriber#onError onError}. + * <p> + * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/finallyDo.png" alt=""> + * <dl> + * <dt><b>Scheduler:</b></dt> + * <dd>{@code doAfterTerminate} does not operate by default on a particular {@link Scheduler}.</dd> + * </dl> + * + * @param action + * an {@link Action0} to be invoked when the source {@link Single} finishes. + * @return a {@link Single} that emits the same item or error as the source {@link Single}, then invokes the + * {@link Action0} + * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> + */ + @Experimental + public final Single<T> doAfterTerminate(Action0 action) { + return lift(new OperatorFinally<T>(action)); + } } diff --git a/src/test/java/rx/SingleTest.java b/src/test/java/rx/SingleTest.java index 0fa8750709..17e3367835 100644 --- a/src/test/java/rx/SingleTest.java +++ b/src/test/java/rx/SingleTest.java @@ -51,7 +51,6 @@ import rx.schedulers.Schedulers; import rx.subscriptions.Subscriptions; - public class SingleTest { @Test @@ -891,4 +890,55 @@ public void call(SingleSubscriber<? super Object> singleSubscriber) { testSubscriber.assertNoValues(); testSubscriber.assertNoTerminalEvent(); } + + @Test + public void doAfterTerminateActionShouldBeInvokedAfterOnSuccess() { + Action0 action = mock(Action0.class); + + TestSubscriber<String> testSubscriber = new TestSubscriber<String>(); + + Single + .just("value") + .doAfterTerminate(action) + .subscribe(testSubscriber); + + testSubscriber.assertValue("value"); + testSubscriber.assertNoErrors(); + + verify(action).call(); + } + + @Test + public void doAfterTerminateActionShouldBeInvokedAfterOnError() { + Action0 action = mock(Action0.class); + + TestSubscriber<Object> testSubscriber = new TestSubscriber<Object>(); + + Throwable error = new IllegalStateException(); + + Single + .error(error) + .doAfterTerminate(action) + .subscribe(testSubscriber); + + testSubscriber.assertNoValues(); + testSubscriber.assertError(error); + + verify(action).call(); + } + + @Test + public void doAfterTerminateActionShouldNotBeInvokedUntilSubscriberSubscribes() { + Action0 action = mock(Action0.class); + + Single + .just("value") + .doAfterTerminate(action); + + Single + .error(new IllegalStateException()) + .doAfterTerminate(action); + + verifyZeroInteractions(action); + } }
aecde5a15d035beb421ef31c4a005e273b2912a0
intellij-community
just one more DnDEnabler little fix :)--
c
https://github.com/JetBrains/intellij-community
diff --git a/source/com/intellij/ide/dnd/DnDEnabler.java b/source/com/intellij/ide/dnd/DnDEnabler.java index 68ee93a99a03d..c68cbb1276084 100644 --- a/source/com/intellij/ide/dnd/DnDEnabler.java +++ b/source/com/intellij/ide/dnd/DnDEnabler.java @@ -148,10 +148,6 @@ public void eventDispatched(AWTEvent event) { if (myDnDSource.getComponent().isFocusable()) { myDnDSource.getComponent().requestFocus(); } - - if (myOriginalDragGestureRecognizer != null) { - dispatchMouseEvent(myOriginalDragGestureRecognizer, e); - } } else { myDnDSource.processMouseEvent(e); @@ -164,6 +160,10 @@ public void eventDispatched(AWTEvent event) { } } } + + if (myOriginalDragGestureRecognizer != null) { + dispatchMouseEvent(myOriginalDragGestureRecognizer, e); + } } } }
6aa31e87bc18b613d66eef751f5481d161ee321d
orientdb
Unneeded index flush was removed--
p
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/metadata/OMetadataDefault.java b/core/src/main/java/com/orientechnologies/orient/core/metadata/OMetadataDefault.java index 0d09ad52126..a75938889fe 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/metadata/OMetadataDefault.java +++ b/core/src/main/java/com/orientechnologies/orient/core/metadata/OMetadataDefault.java @@ -150,12 +150,6 @@ public OSecurityShared call() { security = instance; instance.load(); } - - // if (instance.getAllRoles().isEmpty()) { - // OLogManager.instance().error(this, "No security has been installed, create default users and roles"); - // security.repair(); - // } - return instance; } }), database); @@ -198,14 +192,10 @@ public void reload() { * Closes internal objects */ public void close() { - if (indexManager != null) - indexManager.flush(); if (schema != null) schema.close(); if (security != null) security.close(); - // if (functionLibrary != null) - // functionLibrary.close(); } protected ODatabaseRecord getDatabase() { 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 80bc4dc4439..e8715e6d73d 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 @@ -15,15 +15,8 @@ */ package com.orientechnologies.orient.core.sql; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Set; import com.orientechnologies.common.util.OPair; import com.orientechnologies.orient.core.command.OCommandRequest; @@ -155,9 +148,15 @@ public Object execute(final Map<Object, Object> iArgs) { parameters = new OCommandParameters(iArgs); + Map<Object, Object> queryArgs = new HashMap<Object, Object>(); + for (int i = parameterCounter; i < parameters.size(); i++) { + if (parameters.getByName(i) != null) + queryArgs.put(i - parameterCounter, parameters.getByName(i)); + } + query.setUseCache(false); query.setContext(context); - getDatabase().query(query, iArgs); + getDatabase().query(query, queryArgs); return recordCount; } 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 ecd04665490..45b58c51ad0 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 @@ -155,7 +155,8 @@ protected void onAfterRequest() throws IOException { if (connection != null) { if (connection.database != null) - connection.database.getLevel1Cache().clear(); + if (!connection.database.isClosed()) + connection.database.getLevel1Cache().clear(); connection.data.lastCommandExecutionTime = System.currentTimeMillis() - connection.data.lastCommandReceived; connection.data.totalCommandExecutionTime += connection.data.lastCommandExecutionTime; diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLUpdateTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLUpdateTest.java index 6039ab4ea47..9db222d74a4 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLUpdateTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLUpdateTest.java @@ -15,12 +15,7 @@ */ package com.orientechnologies.orient.test.database.auto; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import org.testng.Assert; import org.testng.annotations.Parameters; @@ -252,25 +247,6 @@ public void updateWithWildcardsOnSetAndWhere() { database.close(); } - @Test - public void updateWithNamedParameters(){ - database.open("admin", "admin"); - ODocument doc = new ODocument("Person"); - doc.field("name", "Caf"); - doc.field("city", "Torino"); - doc.field("gender", "fmale"); - doc.save(); - OCommandSQL updatecommand = new OCommandSQL("update Person set gender = :gender , city = :city where name = :name"); - Map<String,Object> params = new HashMap<String, Object>(); - params.put("gender", "f"); - params.put("city", "TOR"); - params.put("name", "Caf"); - database.command(updatecommand).execute(params); - checkUpdatedDoc(database, "Caf", "TOR", "f"); - - database.close(); - } - public void updateIncrement() { database.open("admin", "admin"); diff --git a/tests/src/test/resources/orientdb-server-config.xml b/tests/src/test/resources/orientdb-server-config.xml index 29c97a68ff2..dd10ae68e0f 100644 --- a/tests/src/test/resources/orientdb-server-config.xml +++ b/tests/src/test/resources/orientdb-server-config.xml @@ -25,16 +25,22 @@ </handlers> <network> <protocols> - <protocol implementation="com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary" name="binary"/> - <protocol implementation="com.orientechnologies.orient.server.network.protocol.http.ONetworkProtocolHttpDb" name="http"/> + <protocol + implementation="com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary" + name="binary"/> + <protocol implementation="com.orientechnologies.orient.server.network.protocol.http.ONetworkProtocolHttpDb" + name="http"/> </protocols> <listeners> <listener protocol="binary" port-range="2424-2430" ip-address="0.0.0.0"/> <listener protocol="http" port-range="2480-2490" ip-address="0.0.0.0"> <commands> - <command implementation="com.orientechnologies.orient.server.network.protocol.http.command.get.OServerCommandGetStaticContent" pattern="GET|www GET|studio/ GET| GET|*.htm GET|*.html GET|*.xml GET|*.jpeg GET|*.jpg GET|*.png GET|*.gif GET|*.js GET|*.css GET|*.swf GET|*.ico GET|*.txt GET|*.otf GET|*.pjs GET|*.svg"> + <command + implementation="com.orientechnologies.orient.server.network.protocol.http.command.get.OServerCommandGetStaticContent" + pattern="GET|www GET|studio/ GET| GET|*.htm GET|*.html GET|*.xml GET|*.jpeg GET|*.jpg GET|*.png GET|*.gif GET|*.js GET|*.css GET|*.swf GET|*.ico GET|*.txt GET|*.otf GET|*.pjs GET|*.svg"> <parameters> - <entry value="Cache-Control: no-cache, no-store, max-age=0, must-revalidate\r\nPragma: no-cache" name="http.cache:*.htm *.html"/> + <entry value="Cache-Control: no-cache, no-store, max-age=0, must-revalidate\r\nPragma: no-cache" + name="http.cache:*.htm *.html"/> <entry value="Cache-Control: max-age=120" name="http.cache:default"/> </parameters> </command> @@ -52,7 +58,11 @@ <user resources="connect,server.listDatabases" password="guest" name="guest"/> </users> <properties> - <entry value="info" name="log.console.level"/> - <entry value="fine" name="log.file.level"/> + <entry name="cache.level2.enabled" value="false"/> + <entry name="cache.level2.size" value="0"/> + <entry name="cache.level1.enabled" value="false"/> + <entry name="cache.level1.size" value="0"/> + <entry name="log.console.level" value="info"/> + <entry name="log.file.level" value="fine"/> </properties> </orient-server>
e47e90e46c274e8853d151689977d214e018f0d8
brianfrankcooper$ycsb
Elasticsearch 5: Use auto-IDs and implements scan This commit refactors the indexing of documents in the Elasticsearch 5 binding to use auto-generated IDs, instead indexing the key field as a dedicated field rather than using it as the ID. This enables us to implement scan functionality which we add in this commit as well.
p
https://github.com/brianfrankcooper/ycsb
diff --git a/elasticsearch5/src/main/java/com/yahoo/ycsb/db/elasticsearch5/ElasticsearchClient.java b/elasticsearch5/src/main/java/com/yahoo/ycsb/db/elasticsearch5/ElasticsearchClient.java index 386ba7c805..2986f88c27 100644 --- a/elasticsearch5/src/main/java/com/yahoo/ycsb/db/elasticsearch5/ElasticsearchClient.java +++ b/elasticsearch5/src/main/java/com/yahoo/ycsb/db/elasticsearch5/ElasticsearchClient.java @@ -25,15 +25,18 @@ import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.delete.DeleteResponse; -import org.elasticsearch.action.get.GetResponse; +import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.Requests; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.node.Node; +import org.elasticsearch.index.query.RangeQueryBuilder; +import org.elasticsearch.index.query.TermQueryBuilder; import org.elasticsearch.rest.RestStatus; +import org.elasticsearch.search.SearchHit; +import org.elasticsearch.search.SearchHitField; import org.elasticsearch.transport.client.PreBuiltTransportClient; import java.net.InetAddress; @@ -124,7 +127,7 @@ public void init() throws DBException { .exists(Requests.indicesExistsRequest(indexKey)).actionGet() .isExists(); if (exists && newdb) { - client.admin().indices().prepareDelete(indexKey).execute().actionGet(); + client.admin().indices().prepareDelete(indexKey).get(); } if (!exists || newdb) { client.admin().indices().create( @@ -138,8 +141,8 @@ public void init() throws DBException { client.admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet(); } - private int parseIntegerProperty(Properties properties, String key, int defaultValue) { - String value = properties.getProperty(key); + private int parseIntegerProperty(final Properties properties, final String key, final int defaultValue) { + final String value = properties.getProperty(key); return value == null ? defaultValue : Integer.parseInt(value); } @@ -154,82 +157,96 @@ public void cleanup() throws DBException { @Override public Status insert(String table, String key, Map<String, ByteIterator> values) { try { - final XContentBuilder doc = jsonBuilder().startObject(); + final XContentBuilder doc = jsonBuilder(); - for (Entry<String, String> entry : StringByteIterator.getStringMap(values).entrySet()) { + doc.startObject(); + for (final Entry<String, String> entry : StringByteIterator.getStringMap(values).entrySet()) { doc.field(entry.getKey(), entry.getValue()); } + doc.field("key", key); doc.endObject(); - client.prepareIndex(indexKey, table, key).setSource(doc).execute().actionGet(); + client.prepareIndex(indexKey, table).setSource(doc).execute().actionGet(); return Status.OK; - } catch (Exception e) { + } catch (final Exception e) { e.printStackTrace(); return Status.ERROR; } } @Override - public Status delete(String table, String key) { + public Status delete(final String table, final String key) { try { - DeleteResponse response = client.prepareDelete(indexKey, table, key).execute().actionGet(); - if (response.status().equals(RestStatus.NOT_FOUND)) { + final SearchResponse searchResponse = search(key); + if (searchResponse.getHits().totalHits == 0) { + return Status.NOT_FOUND; + } + + final String id = searchResponse.getHits().getAt(0).getId(); + + final DeleteResponse deleteResponse = client.prepareDelete(indexKey, table, id).execute().actionGet(); + if (deleteResponse.status().equals(RestStatus.NOT_FOUND)) { return Status.NOT_FOUND; } else { return Status.OK; } - } catch (Exception e) { + } catch (final Exception e) { e.printStackTrace(); return Status.ERROR; } } @Override - public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) { + public Status read( + final String table, + final String key, + final Set<String> fields, + final Map<String, ByteIterator> result) { try { - final GetResponse response = client.prepareGet(indexKey, table, key).execute().actionGet(); + final SearchResponse searchResponse = search(key); + if (searchResponse.getHits().totalHits == 0) { + return Status.NOT_FOUND; + } - if (response.isExists()) { - if (fields != null) { - for (String field : fields) { - result.put(field, new StringByteIterator( - (String) response.getSource().get(field))); - } - } else { - for (String field : response.getSource().keySet()) { - result.put(field, new StringByteIterator( - (String) response.getSource().get(field))); - } + final SearchHit hit = searchResponse.getHits().getAt(0); + if (fields != null) { + for (String field : fields) { + result.put(field, new StringByteIterator( + (String) hit.getField(field).getValue())); } - return Status.OK; } else { - return Status.NOT_FOUND; + for (final Map.Entry<String, SearchHitField> e : hit.getFields().entrySet()) { + result.put(e.getKey(), new StringByteIterator((String) e.getValue().getValue())); + } } - } catch (Exception e) { + return Status.OK; + + } catch (final Exception e) { e.printStackTrace(); return Status.ERROR; } } @Override - public Status update(String table, String key, Map<String, ByteIterator> values) { + public Status update(final String table, final String key, final Map<String, ByteIterator> values) { try { - final GetResponse response = client.prepareGet(indexKey, table, key).execute().actionGet(); + final SearchResponse response = search(key); + if (response.getHits().totalHits == 0) { + return Status.NOT_FOUND; + } - if (response.isExists()) { - for (Entry<String, String> entry : StringByteIterator.getStringMap(values).entrySet()) { - response.getSource().put(entry.getKey(), entry.getValue()); - } + final SearchHit hit = response.getHits().getAt(0); + for (final Entry<String, String> entry : StringByteIterator.getStringMap(values).entrySet()) { + hit.getSource().put(entry.getKey(), entry.getValue()); + } - client.prepareIndex(indexKey, table, key).setSource(response.getSource()).execute().actionGet(); + client.prepareIndex(indexKey, table, key).setSource(hit.getSource()).get(); - return Status.OK; - } else { - return Status.NOT_FOUND; - } - } catch (Exception e) { + return Status.OK; + + } catch (final Exception e) { e.printStackTrace(); return Status.ERROR; } @@ -237,11 +254,40 @@ public Status update(String table, String key, Map<String, ByteIterator> values) @Override public Status scan( - String table, - String startkey, - int recordcount, - Set<String> fields, - Vector<HashMap<String, ByteIterator>> result) { - return Status.NOT_IMPLEMENTED; + final String table, + final String startkey, + final int recordcount, + final Set<String> fields, + final Vector<HashMap<String, ByteIterator>> result) { + try { + final RangeQueryBuilder query = new RangeQueryBuilder("key").gte(startkey); + final SearchResponse response = client.prepareSearch(indexKey).setQuery(query).setSize(recordcount).get(); + + for (final SearchHit hit : response.getHits()) { + final HashMap<String, ByteIterator> entry; + if (fields != null) { + entry = new HashMap<>(fields.size()); + for (final String field : fields) { + entry.put(field, new StringByteIterator((String) hit.getSource().get(field))); + } + } else { + entry = new HashMap<>(hit.getFields().size()); + for (final Map.Entry<String, SearchHitField> field : hit.getFields().entrySet()) { + entry.put(field.getKey(), new StringByteIterator((String) field.getValue().getValue())); + } + } + result.add(entry); + } + return Status.OK; + } catch (final Exception e) { + e.printStackTrace(); + return Status.ERROR; + } } + + + private SearchResponse search(final String key) { + return client.prepareSearch(indexKey).setQuery(new TermQueryBuilder("key", key)).get(); + } + }
1f6e2f3e113c8162aa40e6c8a09ac3917c6d3ecf
Mylyn Reviews
Removed feature for versions
p
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/.project b/versions/org.eclipse.mylyn.versions.tasks-feature/.project deleted file mode 100644 index dfb62cc5..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks-feature/.project +++ /dev/null @@ -1,17 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.mylyn.versions-feature</name> - <comment></comment> - <projects> - </projects> - <buildSpec> - <buildCommand> - <name>org.eclipse.pde.FeatureBuilder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.pde.FeatureNature</nature> - </natures> -</projectDescription> diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.jdt.core.prefs b/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index bbaca6d6..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,357 +0,0 @@ -#Wed Mar 02 16:00:06 PST 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.codeComplete.argumentPrefixes= -org.eclipse.jdt.core.codeComplete.argumentSuffixes= -org.eclipse.jdt.core.codeComplete.fieldPrefixes= -org.eclipse.jdt.core.codeComplete.fieldSuffixes= -org.eclipse.jdt.core.codeComplete.localPrefixes= -org.eclipse.jdt.core.codeComplete.localSuffixes= -org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= -org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.5 -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.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -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.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -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.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning -org.eclipse.jdt.core.compiler.problem.nullReference=error -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -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.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=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -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.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.5 -org.eclipse.jdt.core.compiler.taskCaseSensitive=enabled -org.eclipse.jdt.core.compiler.taskPriorities=NORMAL,HIGH,NORMAL -org.eclipse.jdt.core.compiler.taskTags=TODO,FIXME,XXX -org.eclipse.jdt.core.formatter.align_type_members_on_columns=false -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 -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=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_assignment=0 -org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 -org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=48 -org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 -org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 -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=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=80 -org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 -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=1 -org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 -org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 -org.eclipse.jdt.core.formatter.blank_lines_before_method=1 -org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 -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=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line -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=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.comment.clear_blank_lines=false -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=true -org.eclipse.jdt.core.formatter.comment.format_block_comments=false -org.eclipse.jdt.core.formatter.comment.format_comments=true -org.eclipse.jdt.core.formatter.comment.format_header=false -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=false -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=insert -org.eclipse.jdt.core.formatter.comment.line_length=120 -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=true -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=false -org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert -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_member=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=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=do not 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=do not 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=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=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not 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=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not 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=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not 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=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not 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=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not 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=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not 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=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=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=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=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=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=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=120 -org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=true -org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=true -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=1 -org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true -org.eclipse.jdt.core.formatter.tabulation.char=tab -org.eclipse.jdt.core.formatter.tabulation.size=4 -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/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.jdt.ui.prefs b/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index f6c0a161..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,63 +0,0 @@ -#Wed Mar 02 16:00:06 PST 2011 -cleanup_settings_version=2 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -formatter_profile=_Mylyn based on Eclipse -formatter_settings_version=12 -internal.default.compliance=default -org.eclipse.jdt.ui.exception.name=e -org.eclipse.jdt.ui.gettersetter.use.is=true -org.eclipse.jdt.ui.javadoc=false -org.eclipse.jdt.ui.keywordthis=false -org.eclipse.jdt.ui.overrideannotation=true -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">/**\r\n * @return the ${bare_field_name}\r\n */</template><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">/**\r\n * @param ${param} the ${bare_field_name} to set\r\n */</template><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">/**\r\n * ${tags}\r\n */</template><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">/**\r\n * \r\n */</template><template autoinsert\="false" context\="typecomment_context" deleted\="false" description\="Comment for created types" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.typecomment" name\="typecomment">/**\r\n * @author ${user}\r\n */</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">/**\r\n * \r\n */</template><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">/**\r\n * ${tags}\r\n */</template><template autoinsert\="false" context\="overridecomment_context" deleted\="false" description\="Comment for overriding methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.overridecomment" name\="overridecomment"/><template autoinsert\="false" context\="newtype_context" deleted\="false" description\="Newly created files" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.newtype" name\="newtype">/*******************************************************************************\r\n * Copyright (c) ${year} Tasktop Technologies and others.\r\n * All rights reserved. This program and the accompanying materials\r\n * are made available under the terms of the Eclipse Public License v1.0\r\n * which accompanies this distribution, and is available at\r\n * http\://www.eclipse.org/legal/epl-v10.html\r\n *\r\n * Contributors\:\r\n * Tasktop Technologies - initial API and implementation\r\n *******************************************************************************/\r\n\r\n${package_declaration}\r\n\r\n${typecomment}\r\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">\r\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">\r\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">\r\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">\r\n</template><template autoinsert\="false" 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\r\n${exception_var}.printStackTrace();</template><template autoinsert\="false" context\="methodbody_context" deleted\="false" description\="Code in created method stubs" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.methodbody" name\="methodbody">// ignore\r\n${body_statement}</template><template autoinsert\="false" 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}\r\n// ignore</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><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">/**\r\n * ${tags}\r\n * ${see_to_target}\r\n */</template><template autoinsert\="true" context\="gettercomment_context" deleted\="false" description\="Comment for getter function" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.gettercomment" name\="gettercomment">/**\r\n * @return the ${bare_field_name}\r\n */</template><template autoinsert\="true" context\="settercomment_context" deleted\="false" description\="Comment for setter function" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.settercomment" name\="settercomment">/**\r\n * @param ${param} the ${bare_field_name} to set\r\n */</template><template autoinsert\="true" context\="constructorcomment_context" deleted\="false" description\="Comment for created constructors" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.constructorcomment" name\="constructorcomment">/**\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="filecomment_context" deleted\="false" description\="Comment for created JavaScript files" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.filecomment" name\="filecomment">/**\r\n * \r\n */</template><template autoinsert\="true" context\="typecomment_context" deleted\="false" description\="Comment for created types" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.typecomment" name\="typecomment">/**\r\n * @author ${user}\r\n *\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="fieldcomment_context" deleted\="false" description\="Comment for vars" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.fieldcomment" name\="fieldcomment">/**\r\n * \r\n */</template><template autoinsert\="true" context\="methodcomment_context" deleted\="false" description\="Comment for non-overriding function" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.methodcomment" name\="methodcomment">/**\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="overridecomment_context" deleted\="false" description\="Comment for overriding functions" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.overridecomment" name\="overridecomment">/* (non-Jsdoc)\r\n * ${see_to_overridden}\r\n */</template><template autoinsert\="true" context\="delegatecomment_context" deleted\="false" description\="Comment for delegate functions" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.delegatecomment" name\="delegatecomment">/**\r\n * ${tags}\r\n * ${see_to_target}\r\n */</template><template autoinsert\="true" context\="newtype_context" deleted\="false" description\="Newly created files" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.newtype" name\="newtype">${filecomment}\r\n${package_declaration}\r\n\r\n${typecomment}\r\n${type_declaration}</template><template autoinsert\="true" context\="classbody_context" deleted\="false" description\="Code in new class type bodies" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.classbody" name\="classbody">\r\n</template><template autoinsert\="true" context\="interfacebody_context" deleted\="false" description\="Code in new interface type bodies" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.interfacebody" name\="interfacebody">\r\n</template><template autoinsert\="true" context\="enumbody_context" deleted\="false" description\="Code in new enum type bodies" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.enumbody" name\="enumbody">\r\n</template><template autoinsert\="true" context\="annotationbody_context" deleted\="false" description\="Code in new annotation type bodies" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.annotationbody" name\="annotationbody">\r\n</template><template autoinsert\="true" context\="catchblock_context" deleted\="false" description\="Code in new catch blocks" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.catchblock" name\="catchblock">// ${todo} Auto-generated catch block\r\n${exception_var}.printStackTrace();</template><template autoinsert\="true" context\="methodbody_context" deleted\="false" description\="Code in created function stubs" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.methodbody" name\="methodbody">// ${todo} Auto-generated function stub\r\n${body_statement}</template><template autoinsert\="true" context\="constructorbody_context" deleted\="false" description\="Code in created constructor stubs" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.constructorbody" name\="constructorbody">${body_statement}\r\n// ${todo} Auto-generated constructor stub</template><template autoinsert\="true" context\="getterbody_context" deleted\="false" description\="Code in created getters" enabled\="true" id\="org.eclipse.wst.jsdt.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.wst.jsdt.ui.text.codetemplates.setterbody" name\="setterbody">${field} \= ${param};</template></templates> -sp_cleanup.add_default_serial_version_id=true -sp_cleanup.add_generated_serial_version_id=false -sp_cleanup.add_missing_annotations=true -sp_cleanup.add_missing_deprecated_annotations=true -sp_cleanup.add_missing_methods=false -sp_cleanup.add_missing_nls_tags=false -sp_cleanup.add_missing_override_annotations=true -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=false -sp_cleanup.always_use_this_for_non_static_field_access=false -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_to_enhanced_for_loop=true -sp_cleanup.correct_indentation=true -sp_cleanup.format_source_code=true -sp_cleanup.format_source_code_changes_only=false -sp_cleanup.make_local_variable_final=false -sp_cleanup.make_parameters_final=false -sp_cleanup.make_private_fields_final=true -sp_cleanup.make_variable_declarations_final=true -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=true -sp_cleanup.on_save_use_additional_actions=true -sp_cleanup.organize_imports=true -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=true -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=true -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=true -sp_cleanup.remove_unused_imports=false -sp_cleanup.remove_unused_local_variables=false -sp_cleanup.remove_unused_private_fields=true -sp_cleanup.remove_unused_private_members=false -sp_cleanup.remove_unused_private_methods=true -sp_cleanup.remove_unused_private_types=true -sp_cleanup.sort_members=false -sp_cleanup.sort_members_all=false -sp_cleanup.use_blocks=true -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_parentheses_in_expressions=false -sp_cleanup.use_this_for_non_static_field_access=false -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true -sp_cleanup.use_this_for_non_static_method_access=false -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.mylyn.tasks.ui.prefs b/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.mylyn.tasks.ui.prefs deleted file mode 100644 index 47ada179..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.mylyn.tasks.ui.prefs +++ /dev/null @@ -1,4 +0,0 @@ -#Thu Dec 20 14:12:59 PST 2007 -eclipse.preferences.version=1 -project.repository.kind=bugzilla -project.repository.url=https\://bugs.eclipse.org/bugs diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/about.html b/versions/org.eclipse.mylyn.versions.tasks-feature/about.html deleted file mode 100644 index d774b07c..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks-feature/about.html +++ /dev/null @@ -1,27 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> -<html> -<head> -<title>About</title> -<meta http-equiv=Content-Type content="text/html; charset=ISO-8859-1"> -</head> -<body lang="EN-US"> -<h2>About This Content</h2> - -<p>June 25, 2008</p> -<h3>License</h3> - -<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise -indicated below, the Content is provided to you under the terms and conditions of the -Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available -at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. -For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> - -<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is -being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may -apply to your use of any object code in the Content. Check the Redistributor's license that was -provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise -indicated below, the terms and conditions of the EPL still apply to any source code in the Content -and such source code may be obtained at <a href="/">http://www.eclipse.org</a>.</p> - -</body> -</html> \ No newline at end of file diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/build.properties b/versions/org.eclipse.mylyn.versions.tasks-feature/build.properties deleted file mode 100644 index 1d717bf0..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks-feature/build.properties +++ /dev/null @@ -1,16 +0,0 @@ -############################################################################### -# Copyright (c) 2009, 2010 Tasktop Technologies 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: -# Tasktop Technologies - initial API and implementation -############################################################################### -bin.includes = feature.properties,\ - feature.xml,\ - about.html,\ - epl-v10.html,\ - license.html -src.includes = about.html diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/epl-v10.html b/versions/org.eclipse.mylyn.versions.tasks-feature/epl-v10.html deleted file mode 100644 index ed4b1966..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks-feature/epl-v10.html +++ /dev/null @@ -1,328 +0,0 @@ -<html xmlns:o="urn:schemas-microsoft-com:office:office" -xmlns:w="urn:schemas-microsoft-com:office:word" -xmlns="http://www.w3.org/TR/REC-html40"> - -<head> -<meta http-equiv=Content-Type content="text/html; charset=windows-1252"> -<meta name=ProgId content=Word.Document> -<meta name=Generator content="Microsoft Word 9"> -<meta name=Originator content="Microsoft Word 9"> -<link rel=File-List -href="./Eclipse%20EPL%202003_11_10%20Final_files/filelist.xml"> -<title>Eclipse Public License - Version 1.0</title> -<!--[if gte mso 9]><xml> - <o:DocumentProperties> - <o:Revision>2</o:Revision> - <o:TotalTime>3</o:TotalTime> - <o:Created>2004-03-05T23:03:00Z</o:Created> - <o:LastSaved>2004-03-05T23:03:00Z</o:LastSaved> - <o:Pages>4</o:Pages> - <o:Words>1626</o:Words> - <o:Characters>9270</o:Characters> - <o:Lines>77</o:Lines> - <o:Paragraphs>18</o:Paragraphs> - <o:CharactersWithSpaces>11384</o:CharactersWithSpaces> - <o:Version>9.4402</o:Version> - </o:DocumentProperties> -</xml><![endif]--><!--[if gte mso 9]><xml> - <w:WordDocument> - <w:TrackRevisions/> - </w:WordDocument> -</xml><![endif]--> -<style> -<!-- - /* Font Definitions */ -@font-face - {font-family:Tahoma; - panose-1:2 11 6 4 3 5 4 4 2 4; - mso-font-charset:0; - mso-generic-font-family:swiss; - mso-font-pitch:variable; - mso-font-signature:553679495 -2147483648 8 0 66047 0;} - /* Style Definitions */ -p.MsoNormal, li.MsoNormal, div.MsoNormal - {mso-style-parent:""; - margin:0in; - margin-bottom:.0001pt; - mso-pagination:widow-orphan; - font-size:12.0pt; - font-family:"Times New Roman"; - mso-fareast-font-family:"Times New Roman";} -p - {margin-right:0in; - mso-margin-top-alt:auto; - mso-margin-bottom-alt:auto; - margin-left:0in; - mso-pagination:widow-orphan; - font-size:12.0pt; - font-family:"Times New Roman"; - mso-fareast-font-family:"Times New Roman";} -p.BalloonText, li.BalloonText, div.BalloonText - {mso-style-name:"Balloon Text"; - margin:0in; - margin-bottom:.0001pt; - mso-pagination:widow-orphan; - font-size:8.0pt; - font-family:Tahoma; - mso-fareast-font-family:"Times New Roman";} -@page Section1 - {size:8.5in 11.0in; - margin:1.0in 1.25in 1.0in 1.25in; - mso-header-margin:.5in; - mso-footer-margin:.5in; - mso-paper-source:0;} -div.Section1 - {page:Section1;} ---> -</style> -</head> - -<body lang=EN-US style='tab-interval:.5in'> - -<div class=Section1> - -<p align=center style='text-align:center'><b>Eclipse Public License - v 1.0</b> -</p> - -<p><span style='font-size:10.0pt'>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.</span> </p> - -<p><b><span style='font-size:10.0pt'>1. DEFINITIONS</span></b> </p> - -<p><span style='font-size:10.0pt'>&quot;Contribution&quot; means:</span> </p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) -in the case of the initial Contributor, the initial code and documentation -distributed under this Agreement, and<br clear=left> -b) in the case of each subsequent Contributor:</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i) -changes to the Program, and</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii) -additions to the Program;</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>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. </span></p> - -<p><span style='font-size:10.0pt'>&quot;Contributor&quot; means any person or -entity that distributes the Program.</span> </p> - -<p><span style='font-size:10.0pt'>&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. </span></p> - -<p><span style='font-size:10.0pt'>&quot;Program&quot; means the Contributions -distributed in accordance with this Agreement.</span> </p> - -<p><span style='font-size:10.0pt'>&quot;Recipient&quot; means anyone who -receives the Program under this Agreement, including all Contributors.</span> </p> - -<p><b><span style='font-size:10.0pt'>2. GRANT OF RIGHTS</span></b> </p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) -Subject to the terms of this Agreement, each Contributor hereby grants Recipient -a non-exclusive, worldwide, royalty-free copyright license to<span -style='color:red'> </span>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.</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) -Subject to the terms of this Agreement, each Contributor hereby grants -Recipient a non-exclusive, worldwide,<span style='color:green'> </span>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. </span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>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.</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>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. </span></p> - -<p><b><span style='font-size:10.0pt'>3. REQUIREMENTS</span></b> </p> - -<p><span style='font-size:10.0pt'>A Contributor may choose to distribute the -Program in object code form under its own license agreement, provided that:</span> -</p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) -it complies with the terms and conditions of this Agreement; and</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) -its license agreement:</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>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; </span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii) -effectively excludes on behalf of all Contributors all liability for damages, -including direct, indirect, special, incidental and consequential damages, such -as lost profits; </span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iii) -states that any provisions which differ from this Agreement are offered by that -Contributor alone and not by any other party; and</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>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.<span style='color:blue'> </span></span></p> - -<p><span style='font-size:10.0pt'>When the Program is made available in source -code form:</span> </p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) -it must be made available under this Agreement; and </span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) a -copy of this Agreement must be included with each copy of the Program. </span></p> - -<p><span style='font-size:10.0pt'>Contributors may not remove or alter any -copyright notices contained within the Program. </span></p> - -<p><span style='font-size:10.0pt'>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. </span></p> - -<p><b><span style='font-size:10.0pt'>4. COMMERCIAL DISTRIBUTION</span></b> </p> - -<p><span style='font-size:10.0pt'>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.</span> </p> - -<p><span style='font-size:10.0pt'>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.</span> </p> - -<p><b><span style='font-size:10.0pt'>5. NO WARRANTY</span></b> </p> - -<p><span style='font-size:10.0pt'>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. </span></p> - -<p><b><span style='font-size:10.0pt'>6. DISCLAIMER OF LIABILITY</span></b> </p> - -<p><span style='font-size:10.0pt'>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.</span> </p> - -<p><b><span style='font-size:10.0pt'>7. GENERAL</span></b> </p> - -<p><span style='font-size:10.0pt'>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.</span> </p> - -<p><span style='font-size:10.0pt'>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. </span></p> - -<p><span style='font-size:10.0pt'>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. </span></p> - -<p><span style='font-size:10.0pt'>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.</span> </p> - -<p><span style='font-size:10.0pt'>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.</span> </p> - -<p class=MsoNormal><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> - -</div> - -</body> - -</html> \ No newline at end of file diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/feature.properties b/versions/org.eclipse.mylyn.versions.tasks-feature/feature.properties deleted file mode 100644 index f6531426..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks-feature/feature.properties +++ /dev/null @@ -1,138 +0,0 @@ -############################################################################### -# Copyright (c) 2011 Tasktop Technologies 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: -# Tasktop Technologies - initial API and implementation -############################################################################### -featureName=Mylyn Versions Task Bridge (Incubation) -description=Provides a framework for accessing team providers. -providerName=Eclipse Mylyn -copyright=Copyright (c) 2011 Tasktop Technologies and others. All rights reserved. - -license=\ -Eclipse Foundation Software User Agreement\n\ -April 14, 2010\n\ -\n\ -Usage Of Content\n\ -\n\ -THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR\n\ -OTHER MATERIALS FOR OPEN SOURCE PROJECTS (COLLECTIVELY "CONTENT").\n\ -USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS\n\ -AGREEMENT AND/OR THE TERMS AND CONDITIONS OF LICENSE AGREEMENTS OR\n\ -NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU\n\ -AGREE THAT YOUR USE OF THE CONTENT IS GOVERNED BY THIS AGREEMENT\n\ -AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS\n\ -OR NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE\n\ -TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND CONDITIONS\n\ -OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED\n\ -BELOW, THEN YOU MAY NOT USE THE CONTENT.\n\ -\n\ -Applicable Licenses\n\ -\n\ -Unless otherwise indicated, all Content made available by the\n\ -Eclipse Foundation is provided to you under the terms and conditions of\n\ -the Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is\n\ -provided with this Content and is also available at http://www.eclipse.org/legal/epl-v10.html.\n\ -For purposes of the EPL, "Program" will mean the Content.\n\ -\n\ -Content includes, but is not limited to, source code, object code,\n\ -documentation and other files maintained in the Eclipse Foundation source code\n\ -repository ("Repository") in software modules ("Modules") and made available\n\ -as downloadable archives ("Downloads").\n\ -\n\ - - Content may be structured and packaged into modules to facilitate delivering,\n\ - extending, and upgrading the Content. Typical modules may include plug-ins ("Plug-ins"),\n\ - plug-in fragments ("Fragments"), and features ("Features").\n\ - - Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java(TM) ARchive)\n\ - in a directory named "plugins".\n\ - - A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material.\n\ - Each Feature may be packaged as a sub-directory in a directory named "features".\n\ - Within a Feature, files named "feature.xml" may contain a list of the names and version\n\ - numbers of the Plug-ins and/or Fragments associated with that Feature.\n\ - - Features may also include other Features ("Included Features"). Within a Feature, files\n\ - named "feature.xml" may contain a list of the names and version numbers of Included Features.\n\ -\n\ -The terms and conditions governing Plug-ins and Fragments should be\n\ -contained in files named "about.html" ("Abouts"). The terms and\n\ -conditions governing Features and Included Features should be contained\n\ -in files named "license.html" ("Feature Licenses"). Abouts and Feature\n\ -Licenses may be located in any directory of a Download or Module\n\ -including, but not limited to the following locations:\n\ -\n\ - - The top-level (root) directory\n\ - - Plug-in and Fragment directories\n\ - - Inside Plug-ins and Fragments packaged as JARs\n\ - - Sub-directories of the directory named "src" of certain Plug-ins\n\ - - Feature directories\n\ -\n\ -Note: if a Feature made available by the Eclipse Foundation is installed using the\n\ -Provisioning Technology (as defined below), you must agree to a license ("Feature \n\ -Update License") during the installation process. If the Feature contains\n\ -Included Features, the Feature Update License should either provide you\n\ -with the terms and conditions governing the Included Features or inform\n\ -you where you can locate them. Feature Update Licenses may be found in\n\ -the "license" property of files named "feature.properties" found within a Feature.\n\ -Such Abouts, Feature Licenses, and Feature Update Licenses contain the\n\ -terms and conditions (or references to such terms and conditions) that\n\ -govern your use of the associated Content in that directory.\n\ -\n\ -THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER\n\ -TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS.\n\ -SOME OF THESE OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):\n\ -\n\ - - Common Public License Version 1.0 (available at http://www.eclipse.org/legal/cpl-v10.html)\n\ - - Apache Software License 1.1 (available at http://www.apache.org/licenses/LICENSE)\n\ - - Apache Software License 2.0 (available at http://www.apache.org/licenses/LICENSE-2.0)\n\ - - Metro Link Public License 1.00 (available at http://www.opengroup.org/openmotif/supporters/metrolink/license.html)\n\ - - Mozilla Public License Version 1.1 (available at http://www.mozilla.org/MPL/MPL-1.1.html)\n\ -\n\ -IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR\n\ -TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License\n\ -is provided, please contact the Eclipse Foundation to determine what terms and conditions\n\ -govern that particular Content.\n\ -\n\ -\n\Use of Provisioning Technology\n\ -\n\ -The Eclipse Foundation makes available provisioning software, examples of which include,\n\ -but are not limited to, p2 and the Eclipse Update Manager ("Provisioning Technology") for\n\ -the purpose of allowing users to install software, documentation, information and/or\n\ -other materials (collectively "Installable Software"). This capability is provided with\n\ -the intent of allowing such users to install, extend and update Eclipse-based products.\n\ -Information about packaging Installable Software is available at\n\ -http://eclipse.org/equinox/p2/repository_packaging.html ("Specification").\n\ -\n\ -You may use Provisioning Technology to allow other parties to install Installable Software.\n\ -You shall be responsible for enabling the applicable license agreements relating to the\n\ -Installable Software to be presented to, and accepted by, the users of the Provisioning Technology\n\ -in accordance with the Specification. By using Provisioning Technology in such a manner and\n\ -making it available in accordance with the Specification, you further acknowledge your\n\ -agreement to, and the acquisition of all necessary rights to permit the following:\n\ -\n\ - 1. A series of actions may occur ("Provisioning Process") in which a user may execute\n\ - the Provisioning Technology on a machine ("Target Machine") with the intent of installing,\n\ - extending or updating the functionality of an Eclipse-based product.\n\ - 2. During the Provisioning Process, the Provisioning Technology may cause third party\n\ - Installable Software or a portion thereof to be accessed and copied to the Target Machine.\n\ - 3. Pursuant to the Specification, you will provide to the user the terms and conditions that\n\ - govern the use of the Installable Software ("Installable Software Agreement") and such\n\ - Installable Software Agreement shall be accessed from the Target Machine in accordance\n\ - with the Specification. Such Installable Software Agreement must inform the user of the\n\ - terms and conditions that govern the Installable Software and must solicit acceptance by\n\ - the end user in the manner prescribed in such Installable Software Agreement. Upon such\n\ - indication of agreement by the user, the provisioning Technology will complete installation\n\ - of the Installable Software.\n\ -\n\ -Cryptography\n\ -\n\ -Content may contain encryption software. The country in which you are\n\ -currently may have restrictions on the import, possession, and use,\n\ -and/or re-export to another country, of encryption software. BEFORE\n\ -using any encryption software, please check the country's laws,\n\ -regulations and policies concerning the import, possession, or use, and\n\ -re-export of encryption software, to see if this is permitted.\n\ -\n\ -Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both.\n diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/feature.xml b/versions/org.eclipse.mylyn.versions.tasks-feature/feature.xml deleted file mode 100644 index c39a0b02..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks-feature/feature.xml +++ /dev/null @@ -1,48 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Copyright (c) 2010 Tasktop Technologies 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: - Tasktop Technologies - initial API and implementation - --> -<feature - id="org.eclipse.mylyn.versions.tasks-feature" - label="%featureName" - version="0.7.0.qualifier" - provider-name="%providerName" - plugin="org.eclipse.mylyn"> - - <description url="http://eclipse.org/mylyn"> - %description - </description> - - <copyright> - %copyright - </copyright> - - <license url="license.html"> - %license - </license> - - <requires> - </requires> - - <plugin - id="org.eclipse.mylyn.versions.tasks.core" - download-size="0" - install-size="0" - version="0.0.0" - unpack="false"/> - - <plugin - id="org.eclipse.mylyn.versions.tasks.ui" - download-size="0" - install-size="0" - version="0.0.0" - unpack="false"/> - -</feature> diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/license.html b/versions/org.eclipse.mylyn.versions.tasks-feature/license.html deleted file mode 100644 index c184ca36..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks-feature/license.html +++ /dev/null @@ -1,107 +0,0 @@ -<?xml version="1.0" encoding="ISO-8859-1" ?> -<!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"> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> -<title>Eclipse Foundation Software User Agreement</title> -</head> - -<body lang="EN-US"> -<h2>Eclipse Foundation Software User Agreement</h2> -<p>April 14, 2010</p> - -<h3>Usage Of Content</h3> - -<p>THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR OTHER MATERIALS FOR OPEN SOURCE PROJECTS - (COLLECTIVELY &quot;CONTENT&quot;). USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS AGREEMENT AND/OR THE TERMS AND - CONDITIONS OF LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU AGREE THAT YOUR USE - OF THE CONTENT IS GOVERNED BY THIS AGREEMENT AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR - NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND - CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW, THEN YOU MAY NOT USE THE CONTENT.</p> - -<h3>Applicable Licenses</h3> - -<p>Unless otherwise indicated, all Content made available by the Eclipse Foundation is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 - (&quot;EPL&quot;). A copy of the EPL is provided with this Content and is also available at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. - For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> - -<p>Content includes, but is not limited to, source code, object code, documentation and other files maintained in the Eclipse Foundation source code - repository (&quot;Repository&quot;) in software modules (&quot;Modules&quot;) and made available as downloadable archives (&quot;Downloads&quot;).</p> - -<ul> - <li>Content may be structured and packaged into modules to facilitate delivering, extending, and upgrading the Content. Typical modules may include plug-ins (&quot;Plug-ins&quot;), plug-in fragments (&quot;Fragments&quot;), and features (&quot;Features&quot;).</li> - <li>Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java&trade; ARchive) in a directory named &quot;plugins&quot;.</li> - <li>A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material. Each Feature may be packaged as a sub-directory in a directory named &quot;features&quot;. Within a Feature, files named &quot;feature.xml&quot; may contain a list of the names and version numbers of the Plug-ins - and/or Fragments associated with that Feature.</li> - <li>Features may also include other Features (&quot;Included Features&quot;). Within a Feature, files named &quot;feature.xml&quot; may contain a list of the names and version numbers of Included Features.</li> -</ul> - -<p>The terms and conditions governing Plug-ins and Fragments should be contained in files named &quot;about.html&quot; (&quot;Abouts&quot;). The terms and conditions governing Features and -Included Features should be contained in files named &quot;license.html&quot; (&quot;Feature Licenses&quot;). Abouts and Feature Licenses may be located in any directory of a Download or Module -including, but not limited to the following locations:</p> - -<ul> - <li>The top-level (root) directory</li> - <li>Plug-in and Fragment directories</li> - <li>Inside Plug-ins and Fragments packaged as JARs</li> - <li>Sub-directories of the directory named &quot;src&quot; of certain Plug-ins</li> - <li>Feature directories</li> -</ul> - -<p>Note: if a Feature made available by the Eclipse Foundation is installed using the Provisioning Technology (as defined below), you must agree to a license (&quot;Feature Update License&quot;) during the -installation process. If the Feature contains Included Features, the Feature Update License should either provide you with the terms and conditions governing the Included Features or -inform you where you can locate them. Feature Update Licenses may be found in the &quot;license&quot; property of files named &quot;feature.properties&quot; found within a Feature. -Such Abouts, Feature Licenses, and Feature Update Licenses contain the terms and conditions (or references to such terms and conditions) that govern your use of the associated Content in -that directory.</p> - -<p>THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS. SOME OF THESE -OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):</p> - -<ul> - <li>Common Public License Version 1.0 (available at <a href="http://www.eclipse.org/legal/cpl-v10.html">http://www.eclipse.org/legal/cpl-v10.html</a>)</li> - <li>Apache Software License 1.1 (available at <a href="http://www.apache.org/licenses/LICENSE">http://www.apache.org/licenses/LICENSE</a>)</li> - <li>Apache Software License 2.0 (available at <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>)</li> - <li>Metro Link Public License 1.00 (available at <a href="http://www.opengroup.org/openmotif/supporters/metrolink/license.html">http://www.opengroup.org/openmotif/supporters/metrolink/license.html</a>)</li> - <li>Mozilla Public License Version 1.1 (available at <a href="http://www.mozilla.org/MPL/MPL-1.1.html">http://www.mozilla.org/MPL/MPL-1.1.html</a>)</li> -</ul> - -<p>IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License is provided, please -contact the Eclipse Foundation to determine what terms and conditions govern that particular Content.</p> - - -<h3>Use of Provisioning Technology</h3> - -<p>The Eclipse Foundation makes available provisioning software, examples of which include, but are not limited to, p2 and the Eclipse - Update Manager (&quot;Provisioning Technology&quot;) for the purpose of allowing users to install software, documentation, information and/or - other materials (collectively &quot;Installable Software&quot;). This capability is provided with the intent of allowing such users to - install, extend and update Eclipse-based products. Information about packaging Installable Software is available at <a - href="http://eclipse.org/equinox/p2/repository_packaging.html">http://eclipse.org/equinox/p2/repository_packaging.html</a> - (&quot;Specification&quot;).</p> - -<p>You may use Provisioning Technology to allow other parties to install Installable Software. You shall be responsible for enabling the - applicable license agreements relating to the Installable Software to be presented to, and accepted by, the users of the Provisioning Technology - in accordance with the Specification. By using Provisioning Technology in such a manner and making it available in accordance with the - Specification, you further acknowledge your agreement to, and the acquisition of all necessary rights to permit the following:</p> - -<ol> - <li>A series of actions may occur (&quot;Provisioning Process&quot;) in which a user may execute the Provisioning Technology - on a machine (&quot;Target Machine&quot;) with the intent of installing, extending or updating the functionality of an Eclipse-based - product.</li> - <li>During the Provisioning Process, the Provisioning Technology may cause third party Installable Software or a portion thereof to be - accessed and copied to the Target Machine.</li> - <li>Pursuant to the Specification, you will provide to the user the terms and conditions that govern the use of the Installable - Software (&quot;Installable Software Agreement&quot;) and such Installable Software Agreement shall be accessed from the Target - Machine in accordance with the Specification. Such Installable Software Agreement must inform the user of the terms and conditions that govern - the Installable Software and must solicit acceptance by the end user in the manner prescribed in such Installable Software Agreement. Upon such - indication of agreement by the user, the provisioning Technology will complete installation of the Installable Software.</li> -</ol> - -<h3>Cryptography</h3> - -<p>Content may contain encryption software. The country in which you are currently may have restrictions on the import, possession, and use, and/or re-export to - another country, of encryption software. BEFORE using any encryption software, please check the country's laws, regulations and policies concerning the import, - possession, or use, and re-export of encryption software, to see if this is permitted.</p> - -<p><small>Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both.</small></p> -</body> -</html> diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/pom.xml b/versions/org.eclipse.mylyn.versions.tasks-feature/pom.xml deleted file mode 100644 index 482366db..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks-feature/pom.xml +++ /dev/null @@ -1,14 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - <modelVersion>4.0.0</modelVersion> - <parent> - <artifactId>mylyn-versions-tasks-parent</artifactId> - <groupId>org.eclipse.mylyn.versions</groupId> - <version>0.7.0-SNAPSHOT</version> - </parent> - <groupId>org.eclipse.mylyn.versions</groupId> - <artifactId>org.eclipse.mylyn.versions.tasks-feature</artifactId> - <version>0.7.0-SNAPSHOT</version> - <packaging>eclipse-feature</packaging> -</project> diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.project b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.project deleted file mode 100644 index c9fcc520..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.project +++ /dev/null @@ -1,17 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.mylyn.versions.sdk-feature</name> - <comment></comment> - <projects> - </projects> - <buildSpec> - <buildCommand> - <name>org.eclipse.pde.FeatureBuilder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.pde.FeatureNature</nature> - </natures> -</projectDescription> diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.settings/org.eclipse.jdt.core.prefs b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index bbaca6d6..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,357 +0,0 @@ -#Wed Mar 02 16:00:06 PST 2011 -eclipse.preferences.version=1 -org.eclipse.jdt.core.codeComplete.argumentPrefixes= -org.eclipse.jdt.core.codeComplete.argumentSuffixes= -org.eclipse.jdt.core.codeComplete.fieldPrefixes= -org.eclipse.jdt.core.codeComplete.fieldSuffixes= -org.eclipse.jdt.core.codeComplete.localPrefixes= -org.eclipse.jdt.core.codeComplete.localSuffixes= -org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= -org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.5 -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.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -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.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -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.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning -org.eclipse.jdt.core.compiler.problem.nullReference=error -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -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.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=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -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.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.5 -org.eclipse.jdt.core.compiler.taskCaseSensitive=enabled -org.eclipse.jdt.core.compiler.taskPriorities=NORMAL,HIGH,NORMAL -org.eclipse.jdt.core.compiler.taskTags=TODO,FIXME,XXX -org.eclipse.jdt.core.formatter.align_type_members_on_columns=false -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 -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=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 -org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_assignment=0 -org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 -org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 -org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=48 -org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 -org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 -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=16 -org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=80 -org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 -org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 -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=1 -org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 -org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 -org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 -org.eclipse.jdt.core.formatter.blank_lines_before_method=1 -org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 -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=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line -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=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line -org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line -org.eclipse.jdt.core.formatter.comment.clear_blank_lines=false -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false -org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=true -org.eclipse.jdt.core.formatter.comment.format_block_comments=false -org.eclipse.jdt.core.formatter.comment.format_comments=true -org.eclipse.jdt.core.formatter.comment.format_header=false -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=false -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=insert -org.eclipse.jdt.core.formatter.comment.line_length=120 -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=true -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=false -org.eclipse.jdt.core.formatter.indentation.size=4 -org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert -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_member=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=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=do not 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=do not 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=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=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not 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=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not 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=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not 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=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not 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=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not 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=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert -org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not 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=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=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=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=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=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert -org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=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=120 -org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=true -org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=true -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=1 -org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true -org.eclipse.jdt.core.formatter.tabulation.char=tab -org.eclipse.jdt.core.formatter.tabulation.size=4 -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/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.settings/org.eclipse.jdt.ui.prefs b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index ae5a0874..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,63 +0,0 @@ -#Wed Mar 02 16:00:03 PST 2011 -cleanup_settings_version=2 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -formatter_profile=_Mylyn based on Eclipse -formatter_settings_version=12 -internal.default.compliance=default -org.eclipse.jdt.ui.exception.name=e -org.eclipse.jdt.ui.gettersetter.use.is=true -org.eclipse.jdt.ui.javadoc=false -org.eclipse.jdt.ui.keywordthis=false -org.eclipse.jdt.ui.overrideannotation=true -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">/**\r\n * @return the ${bare_field_name}\r\n */</template><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">/**\r\n * @param ${param} the ${bare_field_name} to set\r\n */</template><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">/**\r\n * ${tags}\r\n */</template><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">/**\r\n * \r\n */</template><template autoinsert\="false" context\="typecomment_context" deleted\="false" description\="Comment for created types" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.typecomment" name\="typecomment">/**\r\n * @author ${user}\r\n */</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">/**\r\n * \r\n */</template><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">/**\r\n * ${tags}\r\n */</template><template autoinsert\="false" context\="overridecomment_context" deleted\="false" description\="Comment for overriding methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.overridecomment" name\="overridecomment"/><template autoinsert\="false" context\="newtype_context" deleted\="false" description\="Newly created files" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.newtype" name\="newtype">/*******************************************************************************\r\n * Copyright (c) ${year} Tasktop Technologies and others.\r\n * All rights reserved. This program and the accompanying materials\r\n * are made available under the terms of the Eclipse Public License v1.0\r\n * which accompanies this distribution, and is available at\r\n * http\://www.eclipse.org/legal/epl-v10.html\r\n *\r\n * Contributors\:\r\n * Tasktop Technologies - initial API and implementation\r\n *******************************************************************************/\r\n\r\n${package_declaration}\r\n\r\n${typecomment}\r\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">\r\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">\r\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">\r\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">\r\n</template><template autoinsert\="false" 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\r\n${exception_var}.printStackTrace();</template><template autoinsert\="false" context\="methodbody_context" deleted\="false" description\="Code in created method stubs" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.methodbody" name\="methodbody">// ignore\r\n${body_statement}</template><template autoinsert\="false" 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}\r\n// ignore</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><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">/**\r\n * ${tags}\r\n * ${see_to_target}\r\n */</template><template autoinsert\="true" context\="gettercomment_context" deleted\="false" description\="Comment for getter function" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.gettercomment" name\="gettercomment">/**\r\n * @return the ${bare_field_name}\r\n */</template><template autoinsert\="true" context\="settercomment_context" deleted\="false" description\="Comment for setter function" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.settercomment" name\="settercomment">/**\r\n * @param ${param} the ${bare_field_name} to set\r\n */</template><template autoinsert\="true" context\="constructorcomment_context" deleted\="false" description\="Comment for created constructors" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.constructorcomment" name\="constructorcomment">/**\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="filecomment_context" deleted\="false" description\="Comment for created JavaScript files" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.filecomment" name\="filecomment">/**\r\n * \r\n */</template><template autoinsert\="true" context\="typecomment_context" deleted\="false" description\="Comment for created types" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.typecomment" name\="typecomment">/**\r\n * @author ${user}\r\n *\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="fieldcomment_context" deleted\="false" description\="Comment for vars" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.fieldcomment" name\="fieldcomment">/**\r\n * \r\n */</template><template autoinsert\="true" context\="methodcomment_context" deleted\="false" description\="Comment for non-overriding function" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.methodcomment" name\="methodcomment">/**\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="overridecomment_context" deleted\="false" description\="Comment for overriding functions" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.overridecomment" name\="overridecomment">/* (non-Jsdoc)\r\n * ${see_to_overridden}\r\n */</template><template autoinsert\="true" context\="delegatecomment_context" deleted\="false" description\="Comment for delegate functions" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.delegatecomment" name\="delegatecomment">/**\r\n * ${tags}\r\n * ${see_to_target}\r\n */</template><template autoinsert\="true" context\="newtype_context" deleted\="false" description\="Newly created files" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.newtype" name\="newtype">${filecomment}\r\n${package_declaration}\r\n\r\n${typecomment}\r\n${type_declaration}</template><template autoinsert\="true" context\="classbody_context" deleted\="false" description\="Code in new class type bodies" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.classbody" name\="classbody">\r\n</template><template autoinsert\="true" context\="interfacebody_context" deleted\="false" description\="Code in new interface type bodies" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.interfacebody" name\="interfacebody">\r\n</template><template autoinsert\="true" context\="enumbody_context" deleted\="false" description\="Code in new enum type bodies" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.enumbody" name\="enumbody">\r\n</template><template autoinsert\="true" context\="annotationbody_context" deleted\="false" description\="Code in new annotation type bodies" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.annotationbody" name\="annotationbody">\r\n</template><template autoinsert\="true" context\="catchblock_context" deleted\="false" description\="Code in new catch blocks" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.catchblock" name\="catchblock">// ${todo} Auto-generated catch block\r\n${exception_var}.printStackTrace();</template><template autoinsert\="true" context\="methodbody_context" deleted\="false" description\="Code in created function stubs" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.methodbody" name\="methodbody">// ${todo} Auto-generated function stub\r\n${body_statement}</template><template autoinsert\="true" context\="constructorbody_context" deleted\="false" description\="Code in created constructor stubs" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.constructorbody" name\="constructorbody">${body_statement}\r\n// ${todo} Auto-generated constructor stub</template><template autoinsert\="true" context\="getterbody_context" deleted\="false" description\="Code in created getters" enabled\="true" id\="org.eclipse.wst.jsdt.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.wst.jsdt.ui.text.codetemplates.setterbody" name\="setterbody">${field} \= ${param};</template></templates> -sp_cleanup.add_default_serial_version_id=true -sp_cleanup.add_generated_serial_version_id=false -sp_cleanup.add_missing_annotations=true -sp_cleanup.add_missing_deprecated_annotations=true -sp_cleanup.add_missing_methods=false -sp_cleanup.add_missing_nls_tags=false -sp_cleanup.add_missing_override_annotations=true -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=false -sp_cleanup.always_use_this_for_non_static_field_access=false -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_to_enhanced_for_loop=true -sp_cleanup.correct_indentation=true -sp_cleanup.format_source_code=true -sp_cleanup.format_source_code_changes_only=false -sp_cleanup.make_local_variable_final=false -sp_cleanup.make_parameters_final=false -sp_cleanup.make_private_fields_final=true -sp_cleanup.make_variable_declarations_final=true -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=true -sp_cleanup.on_save_use_additional_actions=true -sp_cleanup.organize_imports=true -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=true -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=true -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=true -sp_cleanup.remove_unused_imports=false -sp_cleanup.remove_unused_local_variables=false -sp_cleanup.remove_unused_private_fields=true -sp_cleanup.remove_unused_private_members=false -sp_cleanup.remove_unused_private_methods=true -sp_cleanup.remove_unused_private_types=true -sp_cleanup.sort_members=false -sp_cleanup.sort_members_all=false -sp_cleanup.use_blocks=true -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_parentheses_in_expressions=false -sp_cleanup.use_this_for_non_static_field_access=false -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true -sp_cleanup.use_this_for_non_static_method_access=false -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.settings/org.eclipse.mylyn.tasks.ui.prefs b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.settings/org.eclipse.mylyn.tasks.ui.prefs deleted file mode 100644 index 47ada179..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.settings/org.eclipse.mylyn.tasks.ui.prefs +++ /dev/null @@ -1,4 +0,0 @@ -#Thu Dec 20 14:12:59 PST 2007 -eclipse.preferences.version=1 -project.repository.kind=bugzilla -project.repository.url=https\://bugs.eclipse.org/bugs diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/about.html b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/about.html deleted file mode 100644 index d774b07c..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/about.html +++ /dev/null @@ -1,27 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> -<html> -<head> -<title>About</title> -<meta http-equiv=Content-Type content="text/html; charset=ISO-8859-1"> -</head> -<body lang="EN-US"> -<h2>About This Content</h2> - -<p>June 25, 2008</p> -<h3>License</h3> - -<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise -indicated below, the Content is provided to you under the terms and conditions of the -Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available -at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. -For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> - -<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is -being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may -apply to your use of any object code in the Content. Check the Redistributor's license that was -provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise -indicated below, the terms and conditions of the EPL still apply to any source code in the Content -and such source code may be obtained at <a href="/">http://www.eclipse.org</a>.</p> - -</body> -</html> \ No newline at end of file diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/build.properties b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/build.properties deleted file mode 100644 index 1d717bf0..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/build.properties +++ /dev/null @@ -1,16 +0,0 @@ -############################################################################### -# Copyright (c) 2009, 2010 Tasktop Technologies 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: -# Tasktop Technologies - initial API and implementation -############################################################################### -bin.includes = feature.properties,\ - feature.xml,\ - about.html,\ - epl-v10.html,\ - license.html -src.includes = about.html diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/epl-v10.html b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/epl-v10.html deleted file mode 100644 index ed4b1966..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/epl-v10.html +++ /dev/null @@ -1,328 +0,0 @@ -<html xmlns:o="urn:schemas-microsoft-com:office:office" -xmlns:w="urn:schemas-microsoft-com:office:word" -xmlns="http://www.w3.org/TR/REC-html40"> - -<head> -<meta http-equiv=Content-Type content="text/html; charset=windows-1252"> -<meta name=ProgId content=Word.Document> -<meta name=Generator content="Microsoft Word 9"> -<meta name=Originator content="Microsoft Word 9"> -<link rel=File-List -href="./Eclipse%20EPL%202003_11_10%20Final_files/filelist.xml"> -<title>Eclipse Public License - Version 1.0</title> -<!--[if gte mso 9]><xml> - <o:DocumentProperties> - <o:Revision>2</o:Revision> - <o:TotalTime>3</o:TotalTime> - <o:Created>2004-03-05T23:03:00Z</o:Created> - <o:LastSaved>2004-03-05T23:03:00Z</o:LastSaved> - <o:Pages>4</o:Pages> - <o:Words>1626</o:Words> - <o:Characters>9270</o:Characters> - <o:Lines>77</o:Lines> - <o:Paragraphs>18</o:Paragraphs> - <o:CharactersWithSpaces>11384</o:CharactersWithSpaces> - <o:Version>9.4402</o:Version> - </o:DocumentProperties> -</xml><![endif]--><!--[if gte mso 9]><xml> - <w:WordDocument> - <w:TrackRevisions/> - </w:WordDocument> -</xml><![endif]--> -<style> -<!-- - /* Font Definitions */ -@font-face - {font-family:Tahoma; - panose-1:2 11 6 4 3 5 4 4 2 4; - mso-font-charset:0; - mso-generic-font-family:swiss; - mso-font-pitch:variable; - mso-font-signature:553679495 -2147483648 8 0 66047 0;} - /* Style Definitions */ -p.MsoNormal, li.MsoNormal, div.MsoNormal - {mso-style-parent:""; - margin:0in; - margin-bottom:.0001pt; - mso-pagination:widow-orphan; - font-size:12.0pt; - font-family:"Times New Roman"; - mso-fareast-font-family:"Times New Roman";} -p - {margin-right:0in; - mso-margin-top-alt:auto; - mso-margin-bottom-alt:auto; - margin-left:0in; - mso-pagination:widow-orphan; - font-size:12.0pt; - font-family:"Times New Roman"; - mso-fareast-font-family:"Times New Roman";} -p.BalloonText, li.BalloonText, div.BalloonText - {mso-style-name:"Balloon Text"; - margin:0in; - margin-bottom:.0001pt; - mso-pagination:widow-orphan; - font-size:8.0pt; - font-family:Tahoma; - mso-fareast-font-family:"Times New Roman";} -@page Section1 - {size:8.5in 11.0in; - margin:1.0in 1.25in 1.0in 1.25in; - mso-header-margin:.5in; - mso-footer-margin:.5in; - mso-paper-source:0;} -div.Section1 - {page:Section1;} ---> -</style> -</head> - -<body lang=EN-US style='tab-interval:.5in'> - -<div class=Section1> - -<p align=center style='text-align:center'><b>Eclipse Public License - v 1.0</b> -</p> - -<p><span style='font-size:10.0pt'>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.</span> </p> - -<p><b><span style='font-size:10.0pt'>1. DEFINITIONS</span></b> </p> - -<p><span style='font-size:10.0pt'>&quot;Contribution&quot; means:</span> </p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) -in the case of the initial Contributor, the initial code and documentation -distributed under this Agreement, and<br clear=left> -b) in the case of each subsequent Contributor:</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i) -changes to the Program, and</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii) -additions to the Program;</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>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. </span></p> - -<p><span style='font-size:10.0pt'>&quot;Contributor&quot; means any person or -entity that distributes the Program.</span> </p> - -<p><span style='font-size:10.0pt'>&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. </span></p> - -<p><span style='font-size:10.0pt'>&quot;Program&quot; means the Contributions -distributed in accordance with this Agreement.</span> </p> - -<p><span style='font-size:10.0pt'>&quot;Recipient&quot; means anyone who -receives the Program under this Agreement, including all Contributors.</span> </p> - -<p><b><span style='font-size:10.0pt'>2. GRANT OF RIGHTS</span></b> </p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) -Subject to the terms of this Agreement, each Contributor hereby grants Recipient -a non-exclusive, worldwide, royalty-free copyright license to<span -style='color:red'> </span>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.</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) -Subject to the terms of this Agreement, each Contributor hereby grants -Recipient a non-exclusive, worldwide,<span style='color:green'> </span>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. </span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>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.</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>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. </span></p> - -<p><b><span style='font-size:10.0pt'>3. REQUIREMENTS</span></b> </p> - -<p><span style='font-size:10.0pt'>A Contributor may choose to distribute the -Program in object code form under its own license agreement, provided that:</span> -</p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) -it complies with the terms and conditions of this Agreement; and</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) -its license agreement:</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>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; </span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii) -effectively excludes on behalf of all Contributors all liability for damages, -including direct, indirect, special, incidental and consequential damages, such -as lost profits; </span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iii) -states that any provisions which differ from this Agreement are offered by that -Contributor alone and not by any other party; and</span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>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.<span style='color:blue'> </span></span></p> - -<p><span style='font-size:10.0pt'>When the Program is made available in source -code form:</span> </p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) -it must be made available under this Agreement; and </span></p> - -<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) a -copy of this Agreement must be included with each copy of the Program. </span></p> - -<p><span style='font-size:10.0pt'>Contributors may not remove or alter any -copyright notices contained within the Program. </span></p> - -<p><span style='font-size:10.0pt'>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. </span></p> - -<p><b><span style='font-size:10.0pt'>4. COMMERCIAL DISTRIBUTION</span></b> </p> - -<p><span style='font-size:10.0pt'>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.</span> </p> - -<p><span style='font-size:10.0pt'>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.</span> </p> - -<p><b><span style='font-size:10.0pt'>5. NO WARRANTY</span></b> </p> - -<p><span style='font-size:10.0pt'>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. </span></p> - -<p><b><span style='font-size:10.0pt'>6. DISCLAIMER OF LIABILITY</span></b> </p> - -<p><span style='font-size:10.0pt'>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.</span> </p> - -<p><b><span style='font-size:10.0pt'>7. GENERAL</span></b> </p> - -<p><span style='font-size:10.0pt'>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.</span> </p> - -<p><span style='font-size:10.0pt'>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. </span></p> - -<p><span style='font-size:10.0pt'>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. </span></p> - -<p><span style='font-size:10.0pt'>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.</span> </p> - -<p><span style='font-size:10.0pt'>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.</span> </p> - -<p class=MsoNormal><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> - -</div> - -</body> - -</html> \ No newline at end of file diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/feature.properties b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/feature.properties deleted file mode 100644 index dc762267..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/feature.properties +++ /dev/null @@ -1,138 +0,0 @@ -############################################################################### -# Copyright (c) 2011 Tasktop Technologies 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: -# Tasktop Technologies - initial API and implementation -############################################################################### -featureName=Mylyn Versions SDK (Incubation) -description=Plug-in development support and sources for version integrations. -providerName=Eclipse Mylyn -copyright=Copyright (c) 2010, 2011 Tasktop Technologies and others. All rights reserved. - -license=\ -Eclipse Foundation Software User Agreement\n\ -April 14, 2010\n\ -\n\ -Usage Of Content\n\ -\n\ -THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR\n\ -OTHER MATERIALS FOR OPEN SOURCE PROJECTS (COLLECTIVELY "CONTENT").\n\ -USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS\n\ -AGREEMENT AND/OR THE TERMS AND CONDITIONS OF LICENSE AGREEMENTS OR\n\ -NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU\n\ -AGREE THAT YOUR USE OF THE CONTENT IS GOVERNED BY THIS AGREEMENT\n\ -AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS\n\ -OR NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE\n\ -TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND CONDITIONS\n\ -OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED\n\ -BELOW, THEN YOU MAY NOT USE THE CONTENT.\n\ -\n\ -Applicable Licenses\n\ -\n\ -Unless otherwise indicated, all Content made available by the\n\ -Eclipse Foundation is provided to you under the terms and conditions of\n\ -the Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is\n\ -provided with this Content and is also available at http://www.eclipse.org/legal/epl-v10.html.\n\ -For purposes of the EPL, "Program" will mean the Content.\n\ -\n\ -Content includes, but is not limited to, source code, object code,\n\ -documentation and other files maintained in the Eclipse Foundation source code\n\ -repository ("Repository") in software modules ("Modules") and made available\n\ -as downloadable archives ("Downloads").\n\ -\n\ - - Content may be structured and packaged into modules to facilitate delivering,\n\ - extending, and upgrading the Content. Typical modules may include plug-ins ("Plug-ins"),\n\ - plug-in fragments ("Fragments"), and features ("Features").\n\ - - Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java(TM) ARchive)\n\ - in a directory named "plugins".\n\ - - A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material.\n\ - Each Feature may be packaged as a sub-directory in a directory named "features".\n\ - Within a Feature, files named "feature.xml" may contain a list of the names and version\n\ - numbers of the Plug-ins and/or Fragments associated with that Feature.\n\ - - Features may also include other Features ("Included Features"). Within a Feature, files\n\ - named "feature.xml" may contain a list of the names and version numbers of Included Features.\n\ -\n\ -The terms and conditions governing Plug-ins and Fragments should be\n\ -contained in files named "about.html" ("Abouts"). The terms and\n\ -conditions governing Features and Included Features should be contained\n\ -in files named "license.html" ("Feature Licenses"). Abouts and Feature\n\ -Licenses may be located in any directory of a Download or Module\n\ -including, but not limited to the following locations:\n\ -\n\ - - The top-level (root) directory\n\ - - Plug-in and Fragment directories\n\ - - Inside Plug-ins and Fragments packaged as JARs\n\ - - Sub-directories of the directory named "src" of certain Plug-ins\n\ - - Feature directories\n\ -\n\ -Note: if a Feature made available by the Eclipse Foundation is installed using the\n\ -Provisioning Technology (as defined below), you must agree to a license ("Feature \n\ -Update License") during the installation process. If the Feature contains\n\ -Included Features, the Feature Update License should either provide you\n\ -with the terms and conditions governing the Included Features or inform\n\ -you where you can locate them. Feature Update Licenses may be found in\n\ -the "license" property of files named "feature.properties" found within a Feature.\n\ -Such Abouts, Feature Licenses, and Feature Update Licenses contain the\n\ -terms and conditions (or references to such terms and conditions) that\n\ -govern your use of the associated Content in that directory.\n\ -\n\ -THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER\n\ -TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS.\n\ -SOME OF THESE OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):\n\ -\n\ - - Common Public License Version 1.0 (available at http://www.eclipse.org/legal/cpl-v10.html)\n\ - - Apache Software License 1.1 (available at http://www.apache.org/licenses/LICENSE)\n\ - - Apache Software License 2.0 (available at http://www.apache.org/licenses/LICENSE-2.0)\n\ - - Metro Link Public License 1.00 (available at http://www.opengroup.org/openmotif/supporters/metrolink/license.html)\n\ - - Mozilla Public License Version 1.1 (available at http://www.mozilla.org/MPL/MPL-1.1.html)\n\ -\n\ -IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR\n\ -TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License\n\ -is provided, please contact the Eclipse Foundation to determine what terms and conditions\n\ -govern that particular Content.\n\ -\n\ -\n\Use of Provisioning Technology\n\ -\n\ -The Eclipse Foundation makes available provisioning software, examples of which include,\n\ -but are not limited to, p2 and the Eclipse Update Manager ("Provisioning Technology") for\n\ -the purpose of allowing users to install software, documentation, information and/or\n\ -other materials (collectively "Installable Software"). This capability is provided with\n\ -the intent of allowing such users to install, extend and update Eclipse-based products.\n\ -Information about packaging Installable Software is available at\n\ -http://eclipse.org/equinox/p2/repository_packaging.html ("Specification").\n\ -\n\ -You may use Provisioning Technology to allow other parties to install Installable Software.\n\ -You shall be responsible for enabling the applicable license agreements relating to the\n\ -Installable Software to be presented to, and accepted by, the users of the Provisioning Technology\n\ -in accordance with the Specification. By using Provisioning Technology in such a manner and\n\ -making it available in accordance with the Specification, you further acknowledge your\n\ -agreement to, and the acquisition of all necessary rights to permit the following:\n\ -\n\ - 1. A series of actions may occur ("Provisioning Process") in which a user may execute\n\ - the Provisioning Technology on a machine ("Target Machine") with the intent of installing,\n\ - extending or updating the functionality of an Eclipse-based product.\n\ - 2. During the Provisioning Process, the Provisioning Technology may cause third party\n\ - Installable Software or a portion thereof to be accessed and copied to the Target Machine.\n\ - 3. Pursuant to the Specification, you will provide to the user the terms and conditions that\n\ - govern the use of the Installable Software ("Installable Software Agreement") and such\n\ - Installable Software Agreement shall be accessed from the Target Machine in accordance\n\ - with the Specification. Such Installable Software Agreement must inform the user of the\n\ - terms and conditions that govern the Installable Software and must solicit acceptance by\n\ - the end user in the manner prescribed in such Installable Software Agreement. Upon such\n\ - indication of agreement by the user, the provisioning Technology will complete installation\n\ - of the Installable Software.\n\ -\n\ -Cryptography\n\ -\n\ -Content may contain encryption software. The country in which you are\n\ -currently may have restrictions on the import, possession, and use,\n\ -and/or re-export to another country, of encryption software. BEFORE\n\ -using any encryption software, please check the country's laws,\n\ -regulations and policies concerning the import, possession, or use, and\n\ -re-export of encryption software, to see if this is permitted.\n\ -\n\ -Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both.\n diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/feature.xml b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/feature.xml deleted file mode 100644 index ebfac00f..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/feature.xml +++ /dev/null @@ -1,50 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - Copyright (c) 2011 Tasktop Technologies 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: - Tasktop Technologies - initial API and implementation - --> -<feature - id="org.eclipse.mylyn.versions.tasks-sdk" - label="%featureName" - version="0.7.0.qualifier" - provider-name="%providerName" - plugin="org.eclipse.mylyn"> - - <description url="http://eclipse.org/mylyn"> - %description - </description> - - <copyright> - %copyright - </copyright> - - <license url="license.html"> - %license - </license> - - <includes - id="org.eclipse.mylyn.versions.tasks-feature" - version="0.0.0"/> - - <plugin - id="org.eclipse.mylyn.versions.tasks.core.source" - download-size="0" - install-size="0" - version="0.0.0" - unpack="false"/> - - <plugin - id="org.eclipse.mylyn.versions.tasks.ui.source" - download-size="0" - install-size="0" - version="0.0.0" - unpack="false"/> - - -</feature> diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/license.html b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/license.html deleted file mode 100644 index c184ca36..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/license.html +++ /dev/null @@ -1,107 +0,0 @@ -<?xml version="1.0" encoding="ISO-8859-1" ?> -<!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"> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> -<title>Eclipse Foundation Software User Agreement</title> -</head> - -<body lang="EN-US"> -<h2>Eclipse Foundation Software User Agreement</h2> -<p>April 14, 2010</p> - -<h3>Usage Of Content</h3> - -<p>THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR OTHER MATERIALS FOR OPEN SOURCE PROJECTS - (COLLECTIVELY &quot;CONTENT&quot;). USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS AGREEMENT AND/OR THE TERMS AND - CONDITIONS OF LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU AGREE THAT YOUR USE - OF THE CONTENT IS GOVERNED BY THIS AGREEMENT AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR - NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND - CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW, THEN YOU MAY NOT USE THE CONTENT.</p> - -<h3>Applicable Licenses</h3> - -<p>Unless otherwise indicated, all Content made available by the Eclipse Foundation is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 - (&quot;EPL&quot;). A copy of the EPL is provided with this Content and is also available at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. - For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> - -<p>Content includes, but is not limited to, source code, object code, documentation and other files maintained in the Eclipse Foundation source code - repository (&quot;Repository&quot;) in software modules (&quot;Modules&quot;) and made available as downloadable archives (&quot;Downloads&quot;).</p> - -<ul> - <li>Content may be structured and packaged into modules to facilitate delivering, extending, and upgrading the Content. Typical modules may include plug-ins (&quot;Plug-ins&quot;), plug-in fragments (&quot;Fragments&quot;), and features (&quot;Features&quot;).</li> - <li>Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java&trade; ARchive) in a directory named &quot;plugins&quot;.</li> - <li>A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material. Each Feature may be packaged as a sub-directory in a directory named &quot;features&quot;. Within a Feature, files named &quot;feature.xml&quot; may contain a list of the names and version numbers of the Plug-ins - and/or Fragments associated with that Feature.</li> - <li>Features may also include other Features (&quot;Included Features&quot;). Within a Feature, files named &quot;feature.xml&quot; may contain a list of the names and version numbers of Included Features.</li> -</ul> - -<p>The terms and conditions governing Plug-ins and Fragments should be contained in files named &quot;about.html&quot; (&quot;Abouts&quot;). The terms and conditions governing Features and -Included Features should be contained in files named &quot;license.html&quot; (&quot;Feature Licenses&quot;). Abouts and Feature Licenses may be located in any directory of a Download or Module -including, but not limited to the following locations:</p> - -<ul> - <li>The top-level (root) directory</li> - <li>Plug-in and Fragment directories</li> - <li>Inside Plug-ins and Fragments packaged as JARs</li> - <li>Sub-directories of the directory named &quot;src&quot; of certain Plug-ins</li> - <li>Feature directories</li> -</ul> - -<p>Note: if a Feature made available by the Eclipse Foundation is installed using the Provisioning Technology (as defined below), you must agree to a license (&quot;Feature Update License&quot;) during the -installation process. If the Feature contains Included Features, the Feature Update License should either provide you with the terms and conditions governing the Included Features or -inform you where you can locate them. Feature Update Licenses may be found in the &quot;license&quot; property of files named &quot;feature.properties&quot; found within a Feature. -Such Abouts, Feature Licenses, and Feature Update Licenses contain the terms and conditions (or references to such terms and conditions) that govern your use of the associated Content in -that directory.</p> - -<p>THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS. SOME OF THESE -OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):</p> - -<ul> - <li>Common Public License Version 1.0 (available at <a href="http://www.eclipse.org/legal/cpl-v10.html">http://www.eclipse.org/legal/cpl-v10.html</a>)</li> - <li>Apache Software License 1.1 (available at <a href="http://www.apache.org/licenses/LICENSE">http://www.apache.org/licenses/LICENSE</a>)</li> - <li>Apache Software License 2.0 (available at <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>)</li> - <li>Metro Link Public License 1.00 (available at <a href="http://www.opengroup.org/openmotif/supporters/metrolink/license.html">http://www.opengroup.org/openmotif/supporters/metrolink/license.html</a>)</li> - <li>Mozilla Public License Version 1.1 (available at <a href="http://www.mozilla.org/MPL/MPL-1.1.html">http://www.mozilla.org/MPL/MPL-1.1.html</a>)</li> -</ul> - -<p>IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License is provided, please -contact the Eclipse Foundation to determine what terms and conditions govern that particular Content.</p> - - -<h3>Use of Provisioning Technology</h3> - -<p>The Eclipse Foundation makes available provisioning software, examples of which include, but are not limited to, p2 and the Eclipse - Update Manager (&quot;Provisioning Technology&quot;) for the purpose of allowing users to install software, documentation, information and/or - other materials (collectively &quot;Installable Software&quot;). This capability is provided with the intent of allowing such users to - install, extend and update Eclipse-based products. Information about packaging Installable Software is available at <a - href="http://eclipse.org/equinox/p2/repository_packaging.html">http://eclipse.org/equinox/p2/repository_packaging.html</a> - (&quot;Specification&quot;).</p> - -<p>You may use Provisioning Technology to allow other parties to install Installable Software. You shall be responsible for enabling the - applicable license agreements relating to the Installable Software to be presented to, and accepted by, the users of the Provisioning Technology - in accordance with the Specification. By using Provisioning Technology in such a manner and making it available in accordance with the - Specification, you further acknowledge your agreement to, and the acquisition of all necessary rights to permit the following:</p> - -<ol> - <li>A series of actions may occur (&quot;Provisioning Process&quot;) in which a user may execute the Provisioning Technology - on a machine (&quot;Target Machine&quot;) with the intent of installing, extending or updating the functionality of an Eclipse-based - product.</li> - <li>During the Provisioning Process, the Provisioning Technology may cause third party Installable Software or a portion thereof to be - accessed and copied to the Target Machine.</li> - <li>Pursuant to the Specification, you will provide to the user the terms and conditions that govern the use of the Installable - Software (&quot;Installable Software Agreement&quot;) and such Installable Software Agreement shall be accessed from the Target - Machine in accordance with the Specification. Such Installable Software Agreement must inform the user of the terms and conditions that govern - the Installable Software and must solicit acceptance by the end user in the manner prescribed in such Installable Software Agreement. Upon such - indication of agreement by the user, the provisioning Technology will complete installation of the Installable Software.</li> -</ol> - -<h3>Cryptography</h3> - -<p>Content may contain encryption software. The country in which you are currently may have restrictions on the import, possession, and use, and/or re-export to - another country, of encryption software. BEFORE using any encryption software, please check the country's laws, regulations and policies concerning the import, - possession, or use, and re-export of encryption software, to see if this is permitted.</p> - -<p><small>Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both.</small></p> -</body> -</html> diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/pom.xml b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/pom.xml deleted file mode 100644 index 3955be7d..00000000 --- a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/pom.xml +++ /dev/null @@ -1,14 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> - <modelVersion>4.0.0</modelVersion> - <parent> - <artifactId>mylyn-versions-tasks-parent</artifactId> - <groupId>org.eclipse.mylyn.versions</groupId> - <version>0.7.0-SNAPSHOT</version> - </parent> - <groupId>org.eclipse.mylyn.versions</groupId> - <artifactId>org.eclipse.mylyn.versions.tasks-sdk</artifactId> - <version>0.7.0-SNAPSHOT</version> - <packaging>eclipse-feature</packaging> -</project>
0950c46beda335819928585f1262dfe1dca78a0b
ReactiveX-RxJava
Trying to extend the Scheduler interface according- to the comments at -19.--
a
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/Scheduler.java b/rxjava-core/src/main/java/rx/Scheduler.java index 74fe274b3a..e1e7c1e806 100644 --- a/rxjava-core/src/main/java/rx/Scheduler.java +++ b/rxjava-core/src/main/java/rx/Scheduler.java @@ -19,12 +19,31 @@ import rx.util.functions.Action0; import rx.util.functions.Func0; +import rx.util.functions.Func1; +import rx.util.functions.Func2; /** * Represents an object that schedules units of work. */ public interface Scheduler { + /** + * Schedules a cancelable action to be executed. + * + * @param state State to pass into the action. + * @param action Action to schedule. + * @return a subscription to be able to unsubscribe from action. + */ + <T> Subscription schedule(T state, Func2<Scheduler, T, Subscription> action); + + /** + * Schedules a cancelable action to be executed. + * + * @param action Action to schedule. + * @return a subscription to be able to unsubscribe from action. + */ + Subscription schedule(Func1<Scheduler, Subscription> action); + /** * Schedules a cancelable action to be executed. * @@ -43,6 +62,27 @@ public interface Scheduler { */ Subscription schedule(Action0 action); + /** + * Schedules a cancelable action to be executed in dueTime. + * + * @param state State to pass into the action. + * @param action Action to schedule. + * @param dueTime Time the action is due for executing. + * @param unit Time unit of the due time. + * @return a subscription to be able to unsubscribe from action. + */ + <T> Subscription schedule(T state, Func2<Scheduler, T, Subscription> action, long dueTime, TimeUnit unit); + + /** + * Schedules a cancelable action to be executed in dueTime. + * + * @param action Action to schedule. + * @param dueTime Time the action is due for executing. + * @param unit Time unit of the due time. + * @return a subscription to be able to unsubscribe from action. + */ + Subscription schedule(Func1<Scheduler, Subscription> action, long dueTime, TimeUnit unit); + /** * Schedules an action to be executed in dueTime. * diff --git a/rxjava-core/src/main/java/rx/concurrency/AbstractScheduler.java b/rxjava-core/src/main/java/rx/concurrency/AbstractScheduler.java index e6fc87ebdb..d15e8e184a 100644 --- a/rxjava-core/src/main/java/rx/concurrency/AbstractScheduler.java +++ b/rxjava-core/src/main/java/rx/concurrency/AbstractScheduler.java @@ -22,6 +22,8 @@ import rx.subscriptions.Subscriptions; import rx.util.functions.Action0; import rx.util.functions.Func0; +import rx.util.functions.Func1; +import rx.util.functions.Func2; /* package */abstract class AbstractScheduler implements Scheduler { @@ -30,11 +32,51 @@ public Subscription schedule(Action0 action) { return schedule(asFunc0(action)); } + @Override + public Subscription schedule(final Func1<Scheduler, Subscription> action) { + return schedule(new Func0<Subscription>() { + @Override + public Subscription call() { + return action.call(AbstractScheduler.this); + } + }); + } + + @Override + public <T> Subscription schedule(final T state, final Func2<Scheduler, T, Subscription> action) { + return schedule(new Func0<Subscription>() { + @Override + public Subscription call() { + return action.call(AbstractScheduler.this, state); + } + }); + } + @Override public Subscription schedule(Action0 action, long dueTime, TimeUnit unit) { return schedule(asFunc0(action), dueTime, unit); } + @Override + public Subscription schedule(final Func1<Scheduler, Subscription> action, long dueTime, TimeUnit unit) { + return schedule(new Func0<Subscription>() { + @Override + public Subscription call() { + return action.call(AbstractScheduler.this); + } + }, dueTime, unit); + } + + @Override + public <T> Subscription schedule(final T state, final Func2<Scheduler, T, Subscription> action, long dueTime, TimeUnit unit) { + return schedule(new Func0<Subscription>() { + @Override + public Subscription call() { + return action.call(AbstractScheduler.this, state); + } + }, dueTime, unit); + } + @Override public long now() { return System.nanoTime(); diff --git a/rxjava-core/src/main/java/rx/operators/Tester.java b/rxjava-core/src/main/java/rx/operators/Tester.java index bc04242846..11b2c8a798 100644 --- a/rxjava-core/src/main/java/rx/operators/Tester.java +++ b/rxjava-core/src/main/java/rx/operators/Tester.java @@ -19,6 +19,7 @@ import rx.util.functions.Action0; import rx.util.functions.Func0; import rx.util.functions.Func1; +import rx.util.functions.Func2; /** * Common utility functions for testing operator implementations. @@ -289,6 +290,16 @@ public Subscription schedule(Func0<Subscription> action) { return underlying.schedule(action); } + @Override + public Subscription schedule(Func1<Scheduler, Subscription> action) { + return underlying.schedule(action); + } + + @Override + public <T> Subscription schedule(T state, Func2<Scheduler, T, Subscription> action) { + return underlying.schedule(state, action); + } + @Override public Subscription schedule(Action0 action, long dueTime, TimeUnit unit) { return underlying.schedule(action, dueTime, unit); @@ -299,6 +310,16 @@ public Subscription schedule(Func0<Subscription> action, long dueTime, TimeUnit return underlying.schedule(action, dueTime, unit); } + @Override + public Subscription schedule(Func1<Scheduler, Subscription> action, long dueTime, TimeUnit unit) { + return underlying.schedule(action, dueTime, unit); + } + + @Override + public <T> Subscription schedule(T state, Func2<Scheduler, T, Subscription> action, long dueTime, TimeUnit unit) { + return underlying.schedule(state, action, dueTime, unit); + } + @Override public long now() { return underlying.now();
5f00dc61b87eb4af734446d3a7b1c8928cf57e5d
camel
CAMEL-1933: Overhaul of JMX. Added managed send- to.Prepared for camel/route context runtime configuration to be managed.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@808777 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/Route.java b/camel-core/src/main/java/org/apache/camel/Route.java index 0539773fda209..c7bdc8d77f1a8 100644 --- a/camel-core/src/main/java/org/apache/camel/Route.java +++ b/camel-core/src/main/java/org/apache/camel/Route.java @@ -19,6 +19,8 @@ import java.util.List; import java.util.Map; +import org.apache.camel.spi.RouteContext; + public interface Route { String ID_PROPERTY = "id"; @@ -44,6 +46,13 @@ public interface Route { */ Map<String, Object> getProperties(); + /** + * Gets the route context + * + * @return the route context + */ + RouteContext getRouteContext(); + /** * This property map is used to associate information about * the route. Gets all the services for this routes 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 9f5db318fad28..f7763ca816839 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 @@ -591,7 +591,7 @@ public ServiceStatus getRouteStatus(String key) { } public void startRoute(RouteDefinition route) throws Exception { - Collection<Route> routes = new ArrayList<Route>(); + List<Route> routes = new ArrayList<Route>(); List<RouteContext> routeContexts = route.addRoutes(this, routes); RouteService routeService = new RouteService(this, route, routeContexts, routes); startRouteService(routeService); diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultRoute.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultRoute.java index e41d4caadc171..f89e34eed2ea0 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultRoute.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultRoute.java @@ -24,6 +24,7 @@ import org.apache.camel.Endpoint; import org.apache.camel.Route; import org.apache.camel.Service; +import org.apache.camel.spi.RouteContext; /** * A <a href="http://camel.apache.org/routes.html">Route</a> @@ -37,13 +38,15 @@ public abstract class DefaultRoute extends ServiceSupport implements Route { private final Endpoint endpoint; private final Map<String, Object> properties = new HashMap<String, Object>(); private final List<Service> services = new ArrayList<Service>(); + private final RouteContext routeContext; - public DefaultRoute(Endpoint endpoint) { + public DefaultRoute(RouteContext routeContext, Endpoint endpoint) { + this.routeContext = routeContext; this.endpoint = endpoint; } - public DefaultRoute(Endpoint endpoint, Service... services) { - this(endpoint); + public DefaultRoute(RouteContext routeContext, Endpoint endpoint, Service... services) { + this(routeContext, endpoint); for (Service service : services) { addService(service); } @@ -62,6 +65,10 @@ public Endpoint getEndpoint() { return endpoint; } + public RouteContext getRouteContext() { + return routeContext; + } + public Map<String, Object> getProperties() { return properties; } diff --git a/camel-core/src/main/java/org/apache/camel/impl/DefaultRouteContext.java b/camel-core/src/main/java/org/apache/camel/impl/DefaultRouteContext.java index 84e3aedaa8005..7c25394510b85 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/DefaultRouteContext.java +++ b/camel-core/src/main/java/org/apache/camel/impl/DefaultRouteContext.java @@ -145,7 +145,7 @@ public void commit() { wrapper.setProcessor(unitOfWorkProcessor); // and create the route that wraps the UoW - Route edcr = new EventDrivenConsumerRoute(getEndpoint(), wrapper); + Route edcr = new EventDrivenConsumerRoute(this, getEndpoint(), wrapper); edcr.getProperties().put(Route.ID_PROPERTY, route.idOrCreate(getCamelContext().getNodeIdFactory())); edcr.getProperties().put(Route.PARENT_PROPERTY, Integer.toHexString(route.hashCode())); if (route.getGroup() != null) { diff --git a/camel-core/src/main/java/org/apache/camel/impl/EventDrivenConsumerRoute.java b/camel-core/src/main/java/org/apache/camel/impl/EventDrivenConsumerRoute.java index cf491137a8f6c..1f4807d2a01c0 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/EventDrivenConsumerRoute.java +++ b/camel-core/src/main/java/org/apache/camel/impl/EventDrivenConsumerRoute.java @@ -23,6 +23,7 @@ import org.apache.camel.Navigate; import org.apache.camel.Processor; import org.apache.camel.Service; +import org.apache.camel.spi.RouteContext; import org.apache.camel.management.InstrumentationProcessor; /** @@ -34,8 +35,8 @@ public class EventDrivenConsumerRoute extends DefaultRoute { private final Processor processor; - public EventDrivenConsumerRoute(Endpoint endpoint, Processor processor) { - super(endpoint); + public EventDrivenConsumerRoute(RouteContext routeContext, Endpoint endpoint, Processor processor) { + super(routeContext, endpoint); this.processor = processor; } diff --git a/camel-core/src/main/java/org/apache/camel/impl/RouteService.java b/camel-core/src/main/java/org/apache/camel/impl/RouteService.java index abdbf3f6789cd..a7820d308f241 100644 --- a/camel-core/src/main/java/org/apache/camel/impl/RouteService.java +++ b/camel-core/src/main/java/org/apache/camel/impl/RouteService.java @@ -45,10 +45,10 @@ public class RouteService extends ServiceSupport { private final DefaultCamelContext camelContext; private final RouteDefinition routeDefinition; private final List<RouteContext> routeContexts; - private final Collection<Route> routes; + private final List<Route> routes; private final String id; - public RouteService(DefaultCamelContext camelContext, RouteDefinition routeDefinition, List<RouteContext> routeContexts, Collection<Route> routes) { + public RouteService(DefaultCamelContext camelContext, RouteDefinition routeDefinition, List<RouteContext> routeContexts, List<Route> routes) { this.camelContext = camelContext; this.routeDefinition = routeDefinition; this.routeContexts = routeContexts; diff --git a/camel-core/src/main/java/org/apache/camel/management/DefaultManagedLifecycleStrategy.java b/camel-core/src/main/java/org/apache/camel/management/DefaultManagedLifecycleStrategy.java index 0894a1a811864..083fec9cfb2d4 100644 --- a/camel-core/src/main/java/org/apache/camel/management/DefaultManagedLifecycleStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/management/DefaultManagedLifecycleStrategy.java @@ -43,6 +43,7 @@ import org.apache.camel.management.mbean.ManagedProcessor; import org.apache.camel.management.mbean.ManagedProducer; import org.apache.camel.management.mbean.ManagedRoute; +import org.apache.camel.management.mbean.ManagedSendProcessor; import org.apache.camel.management.mbean.ManagedThrottler; import org.apache.camel.model.AOPDefinition; import org.apache.camel.model.InterceptDefinition; @@ -51,6 +52,7 @@ import org.apache.camel.model.ProcessorDefinition; import org.apache.camel.model.RouteDefinition; import org.apache.camel.processor.Delayer; +import org.apache.camel.processor.SendProcessor; import org.apache.camel.processor.Throttler; import org.apache.camel.spi.BrowsableEndpoint; import org.apache.camel.spi.ClassResolver; @@ -316,10 +318,10 @@ private Object createManagedObjectForProcessor(CamelContext context, Processor p return new ManagedDelayer(context, (Delayer) processor, definition); } else if (processor instanceof Throttler) { return new ManagedThrottler(context, (Throttler) processor, definition); + } else if (processor instanceof SendProcessor) { + return new ManagedSendProcessor(context, (SendProcessor) processor, definition); } - // TODO Add more specialized support for processors such as SendTo, WireTap etc. - // fallback to a generic processor return new ManagedProcessor(context, processor, definition); } diff --git a/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedSendProcessor.java b/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedSendProcessor.java new file mode 100644 index 0000000000000..739ef4d8f7f18 --- /dev/null +++ b/camel-core/src/main/java/org/apache/camel/management/mbean/ManagedSendProcessor.java @@ -0,0 +1,64 @@ +/** + * 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.management.mbean; + +import org.apache.camel.CamelContext; +import org.apache.camel.Endpoint; +import org.apache.camel.model.ProcessorDefinition; +import org.apache.camel.processor.SendProcessor; +import org.springframework.jmx.export.annotation.ManagedAttribute; +import org.springframework.jmx.export.annotation.ManagedOperation; +import org.springframework.jmx.export.annotation.ManagedResource; + +/** + * @version $Revision$ + */ +@ManagedResource(description = "Managed SendProcessor") +public class ManagedSendProcessor extends ManagedProcessor { + + private SendProcessor processor; + + public ManagedSendProcessor(CamelContext context, SendProcessor processor, ProcessorDefinition definition) { + super(context, processor, definition); + this.processor = processor; + } + + public SendProcessor getProcessor() { + return processor; + } + + @ManagedAttribute(description = "Destination as Endpoint Uri") + public String getDestination() { + return processor.getDestination().getEndpointUri(); + } + + @ManagedAttribute(description = "Message Exchange Pattern") + public String getMessageExchangePattern() { + if (processor.getPattern() != null) { + return processor.getPattern().name(); + } else { + return null; + } + } + + @ManagedOperation(description = "Change Destination Endpoint Uri") + public void changeDestination(String uri) throws Exception { + Endpoint endpoint = getContext().getEndpoint(uri); + processor.setDestination(endpoint); + } + +} diff --git a/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java b/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java index 8a9491d4d84e1..20c587b5d0f77 100644 --- a/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/processor/SendProcessor.java @@ -56,6 +56,11 @@ public String toString() { return "sendTo(" + destination + (pattern != null ? " " + pattern : "") + ")"; } + public synchronized void setDestination(Endpoint destination) { + this.destination = destination; + this.init = false; + } + public String getTraceLabel() { return destination.getEndpointUri(); } @@ -97,6 +102,10 @@ public Endpoint getDestination() { return destination; } + public ExchangePattern getPattern() { + return pattern; + } + protected Exchange configureExchange(Exchange exchange, ExchangePattern pattern) { if (pattern != null) { exchange.setPattern(pattern); diff --git a/camel-core/src/test/java/org/apache/camel/management/ManagedSendProcessorTest.java b/camel-core/src/test/java/org/apache/camel/management/ManagedSendProcessorTest.java new file mode 100644 index 0000000000000..306efa9b9d191 --- /dev/null +++ b/camel-core/src/test/java/org/apache/camel/management/ManagedSendProcessorTest.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.management; + +import javax.management.MBeanServer; +import javax.management.ObjectName; + +import org.apache.camel.CamelContext; +import org.apache.camel.ContextTestSupport; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; + +/** + * @version $Revision$ + */ +public class ManagedSendProcessorTest extends ContextTestSupport { + + @Override + protected CamelContext createCamelContext() throws Exception { + CamelContext context = super.createCamelContext(); + DefaultManagementNamingStrategy naming = (DefaultManagementNamingStrategy) context.getManagementStrategy().getManagementNamingStrategy(); + naming.setHostName("localhost"); + naming.setDomainName("org.apache.camel"); + return context; + } + + @SuppressWarnings("unchecked") + public void testManageSendProcessor() throws Exception { + MockEndpoint result = getMockEndpoint("mock:result"); + result.expectedMessageCount(1); + MockEndpoint foo = getMockEndpoint("mock:foo"); + foo.expectedMessageCount(0); + + template.sendBody("direct:start", "Hello World"); + + assertMockEndpointsSatisfied(); + + // get the stats for the route + MBeanServer mbeanServer = context.getManagementStrategy().getManagementAgent().getMBeanServer(); + + // get the object name for the delayer + ObjectName on = ObjectName.getInstance("org.apache.camel:context=localhost/camel-1,type=processors,name=\"mysend\""); + + // send it somewhere else + mbeanServer.invoke(on, "changeDestination", new Object[]{"direct:foo"}, new String[]{"java.lang.String"}); + + // prepare mocks + result.reset(); + result.expectedMessageCount(0); + foo.reset(); + foo.expectedMessageCount(1); + + // send in another message that should be sent to mock:foo + template.sendBody("direct:start", "Bye World"); + + assertMockEndpointsSatisfied(); + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + @Override + public void configure() throws Exception { + from("direct:start") + .to("mock:result").id("mysend"); + + from("direct:foo").to("mock:foo"); + } + }; + } + +}
8467928cf0639c9783a5f03168af547ffe8a23c8
camel
CAMEL-4023 Properties to Cxf ClientProxyFactory- can be set on endpoint uri or CxfEndpoint bean.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1128561 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/camel
diff --git a/components/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfComponent.java b/components/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfComponent.java index 5133229a23c88..f7bfe4b9b5713 100644 --- a/components/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfComponent.java +++ b/components/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfComponent.java @@ -88,6 +88,8 @@ protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> properties = IntrospectionSupport.extractProperties(parameters, "properties."); if (properties != null) { result.setProperties(properties); + // set the properties of MTOM + result.setMtomEnabled(Boolean.valueOf((String)properties.get(Message.MTOM_ENABLED))); } return result; diff --git a/components/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfEndpoint.java b/components/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfEndpoint.java index 10f70ea88739c..d66ae60c8076a 100644 --- a/components/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfEndpoint.java +++ b/components/camel-cxf/src/main/java/org/apache/camel/component/cxf/CxfEndpoint.java @@ -188,12 +188,12 @@ protected void setupServerFactoryBean(ServerFactoryBean sfb, Class<?> cls) { } // any optional properties - if (properties != null) { + if (getProperties() != null) { if (sfb.getProperties() != null) { // add to existing properties - sfb.getProperties().putAll(properties); + sfb.getProperties().putAll(getProperties()); } else { - sfb.setProperties(properties); + sfb.setProperties(getProperties()); } LOG.debug("ServerFactoryBean: {} added properties: {}", sfb, properties); } @@ -299,6 +299,17 @@ protected void setupClientFactoryBean(ClientProxyFactoryBean factoryBean, Class< factoryBean.getServiceFactory().setWrapped(getWrappedStyle()); } + // set the properties on CxfProxyFactoryBean + if (getProperties() != null) { + if (factoryBean.getProperties() != null) { + // add to existing properties + factoryBean.getProperties().putAll(getProperties()); + } else { + factoryBean.setProperties(getProperties()); + } + LOG.debug("ClientProxyFactoryBean: {} added properties: {}", factoryBean, properties); + } + factoryBean.setBus(getBus()); } diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfJavaOnlyPayloadModeTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfJavaOnlyPayloadModeTest.java index 7fce8263687f6..cf69d4ee9b6b4 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfJavaOnlyPayloadModeTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfJavaOnlyPayloadModeTest.java @@ -36,7 +36,8 @@ public class CxfJavaOnlyPayloadModeTest extends CamelTestSupport { + "?wsdlURL=classpath:person.wsdl" + "&serviceName={http://camel.apache.org/wsdl-first}PersonService" + "&portName={http://camel.apache.org/wsdl-first}soap" - + "&dataFormat=PAYLOAD"; + + "&dataFormat=PAYLOAD" + + "&properties.exceptionMessageCauseEnabled=true&properties.faultStackTraceEnabled=true"; @Test public void testCxfJavaOnly() throws Exception { diff --git a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/mtom/CxfMtomConsumerTest.java b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/mtom/CxfMtomConsumerTest.java index 71c0d77041751..275412bfb2883 100644 --- a/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/mtom/CxfMtomConsumerTest.java +++ b/components/camel-cxf/src/test/java/org/apache/camel/component/cxf/mtom/CxfMtomConsumerTest.java @@ -40,7 +40,7 @@ public class CxfMtomConsumerTest extends CamelTestSupport { protected static final String MTOM_ENDPOINT_ADDRESS = "http://localhost:9091/jaxws-mtom/hello"; protected static final String MTOM_ENDPOINT_URI = "cxf://" + MTOM_ENDPOINT_ADDRESS - + "?serviceClass=org.apache.camel.component.cxf.HelloImpl"; + + "?serviceClass=org.apache.camel.cxf.mtom_feature.Hello"; private final QName serviceName = new QName("http://apache.org/camel/cxf/mtom_feature", "HelloService"); @@ -83,12 +83,12 @@ private Hello getPort() { return service.getHelloPort(); } - private Image getImage(String name) throws Exception { + protected Image getImage(String name) throws Exception { return ImageIO.read(getClass().getResource(name)); } @Test - public void testInvokingServiceFromCXFClient() throws Exception { + public void testInvokingService() throws Exception { if (Boolean.getBoolean("java.awt.headless") || System.getProperty("os.name").startsWith("Mac OS") && System.getProperty("user.name").equals("cruise")) {
37a3414cd78d97ecbf2aa012579eda615054ba86
Mylyn Reviews
322734: Re-Added comment comment part
p
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java index 94a62a2d..b690ed5c 100644 --- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java +++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java @@ -64,7 +64,6 @@ public Set<String> getBlockingIds(ITask task) { public Set<String> getBlockingPaths(ITask task) { Set<String> blockedPaths = new HashSet<String>(); blockedPaths.add(AbstractTaskEditorPage.PATH_ATTRIBUTES); - blockedPaths.add(AbstractTaskEditorPage.PATH_COMMENTS); blockedPaths.add(AbstractTaskEditorPage.PATH_ATTACHMENTS); blockedPaths.add(AbstractTaskEditorPage.PATH_PLANNING);
5ae1c8a24284d1bbc96c8410c81600a5e1a7a9f5
spring-framework
Clean up spring-webmvc-portlet tests warnings--Clean up compiler warnings in the tests of spring-webmvc-portlet. This-commit adds type parameters to all the types (mostly `List` and `Map`).--After this commit the only warnings in spring-web left are the-subclasses of `MyCommandProvidingFormController`.-
p
https://github.com/spring-projects/spring-framework
diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/context/BeanThatListens.java b/spring-webmvc-portlet/src/test/java/org/springframework/context/BeanThatListens.java index ab40da4b8969..d6f4b6ab9121 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/context/BeanThatListens.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/context/BeanThatListens.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ * @author Thomas Risberg * @author Juergen Hoeller */ -public class BeanThatListens implements ApplicationListener { +public class BeanThatListens implements ApplicationListener<ApplicationEvent> { private BeanThatBroadcasts beanThatBroadcasts; @@ -36,7 +36,7 @@ public BeanThatListens() { public BeanThatListens(BeanThatBroadcasts beanThatBroadcasts) { this.beanThatBroadcasts = beanThatBroadcasts; - Map beans = beanThatBroadcasts.applicationContext.getBeansOfType(BeanThatListens.class); + Map<String, BeanThatListens> beans = beanThatBroadcasts.applicationContext.getBeansOfType(BeanThatListens.class); if (!beans.isEmpty()) { throw new IllegalStateException("Shouldn't have found any BeanThatListens instances"); } diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/context/TestListener.java b/spring-webmvc-portlet/src/test/java/org/springframework/context/TestListener.java index 739222190fa9..7762131ab418 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/context/TestListener.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/context/TestListener.java @@ -1,3 +1,19 @@ +/* + * Copyright 2002-2014 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.context; import org.springframework.context.ApplicationEvent; @@ -9,7 +25,7 @@ * @author Rod Johnson * @since January 21, 2001 */ -public class TestListener implements ApplicationListener { +public class TestListener implements ApplicationListener<ApplicationEvent> { private int eventCount; diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletRequest.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletRequest.java index 2cbefb79c1a2..08278d07d521 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletRequest.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -271,8 +271,8 @@ public void addProperty(String key, String value) { @Override public String getProperty(String key) { Assert.notNull(key, "Property key must not be null"); - List list = this.properties.get(key); - return (list != null && list.size() > 0 ? (String) list.get(0) : null); + List<String> list = this.properties.get(key); + return (list != null && list.size() > 0 ? list.get(0) : null); } @Override diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/ComplexPortletApplicationContext.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/ComplexPortletApplicationContext.java index b1b1459ee75e..564a2d5722db 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/ComplexPortletApplicationContext.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/ComplexPortletApplicationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,6 +39,7 @@ import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; +import org.springframework.beans.factory.config.BeanReference; import org.springframework.beans.factory.config.ConstructorArgumentValues; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.support.ManagedList; @@ -118,14 +119,14 @@ public void refresh() throws BeansException { ParameterMappingInterceptor parameterMappingInterceptor = new ParameterMappingInterceptor(); parameterMappingInterceptor.setParameterName("interceptingParam"); - List interceptors = new ArrayList(); + List<HandlerInterceptor> interceptors = new ArrayList<HandlerInterceptor>(4); interceptors.add(parameterMappingInterceptor); interceptors.add(userRoleInterceptor); interceptors.add(new MyHandlerInterceptor1()); interceptors.add(new MyHandlerInterceptor2()); MutablePropertyValues pvs = new MutablePropertyValues(); - Map portletModeMap = new ManagedMap(); + Map<String, BeanReference> portletModeMap = new ManagedMap<String, BeanReference>(); portletModeMap.put("view", new RuntimeBeanReference("viewController")); portletModeMap.put("edit", new RuntimeBeanReference("editController")); pvs.add("portletModeMap", portletModeMap); @@ -133,7 +134,7 @@ public void refresh() throws BeansException { registerSingleton("handlerMapping3", PortletModeHandlerMapping.class, pvs); pvs = new MutablePropertyValues(); - Map parameterMap = new ManagedMap(); + Map<String, BeanReference> parameterMap = new ManagedMap<String, BeanReference>(); parameterMap.put("test1", new RuntimeBeanReference("testController1")); parameterMap.put("test2", new RuntimeBeanReference("testController2")); parameterMap.put("requestLocaleChecker", new RuntimeBeanReference("requestLocaleCheckingController")); @@ -148,10 +149,10 @@ public void refresh() throws BeansException { registerSingleton("handlerMapping2", ParameterHandlerMapping.class, pvs); pvs = new MutablePropertyValues(); - Map innerMap = new ManagedMap(); + Map<String, Object> innerMap = new ManagedMap<String, Object>(); innerMap.put("help1", new RuntimeBeanReference("helpController1")); innerMap.put("help2", new RuntimeBeanReference("helpController2")); - Map outerMap = new ManagedMap(); + Map<String, Object> outerMap = new ManagedMap<String, Object>(); outerMap.put("help", innerMap); pvs.add("portletModeParameterMap", outerMap); pvs.add("order", "1"); @@ -171,7 +172,7 @@ public void refresh() throws BeansException { pvs.add("exceptionMappings", "java.lang.Exception=failed-exception\n" + "java.lang.RuntimeException=failed-runtime"); - List mappedHandlers = new ManagedList(); + List<BeanReference> mappedHandlers = new ManagedList<BeanReference>(); mappedHandlers.add(new RuntimeBeanReference("exceptionThrowingHandler1")); pvs.add("mappedHandlers", mappedHandlers); pvs.add("defaultErrorView", "failed-default-0"); @@ -533,7 +534,7 @@ public void cleanupMultipart(MultipartActionRequest request) { } - public static class TestApplicationListener implements ApplicationListener { + public static class TestApplicationListener implements ApplicationListener<ApplicationEvent> { public int counter = 0; diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/DispatcherPortletTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/DispatcherPortletTests.java index 16ee96b7fd89..d99733d26c75 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/DispatcherPortletTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/DispatcherPortletTests.java @@ -1,18 +1,18 @@ /* -* 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. -* 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. -*/ + * Copyright 2002-2014 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.springframework.web.portlet; @@ -125,7 +125,7 @@ public void testPortletModeParameterMappingInvalidHelpRenderRequest() throws Exc request.setPortletMode(PortletMode.HELP); request.setParameter("action", "help3"); complexDispatcherPortlet.doDispatch(request, response); - Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); + Map<?, ?> model = (Map<?, ?>) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); assertTrue(model.get("exception").getClass().equals(NoHandlerFoundException.class)); InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); assertEquals("failed-unavailable", view.getBeanName()); @@ -164,7 +164,7 @@ public void testPortletModeMappingValidViewRenderRequest() throws Exception { request.setParameter("action", "not mapped"); request.setParameter("myParam", "not mapped"); complexDispatcherPortlet.doDispatch(request, response); - Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); + Map<?, ?> model = (Map<?, ?>) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); assertEquals("view was here", model.get("result")); InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); assertEquals("someViewName", view.getBeanName()); @@ -178,7 +178,7 @@ public void testPortletModeMappingViewRenderRequestWithUnauthorizedUserRole() th request.setParameter("action", "not mapped"); request.setParameter("myParam", "not mapped"); complexDispatcherPortlet.doDispatch(request, response); - Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); + Map<?, ?> model = (Map<?, ?>) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); Exception exception = (Exception) model.get("exception"); assertNotNull(exception); assertTrue(exception.getClass().equals(PortletSecurityException.class)); @@ -222,7 +222,7 @@ public void testUnknownHandlerRenderRequest() throws Exception { MockRenderResponse response = new MockRenderResponse(); request.setParameter("myParam", "unknown"); complexDispatcherPortlet.doDispatch(request, response); - Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); + Map<?, ?> model = (Map<?, ?>) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); Exception exception = (Exception)model.get("exception"); assertTrue(exception.getClass().equals(PortletException.class)); assertTrue(exception.getMessage().indexOf("No adapter for handler") != -1); @@ -255,7 +255,7 @@ public void testNoDetectAllHandlerMappingsWithParameterRenderRequest() throws Ex MockRenderResponse response = new MockRenderResponse(); request.setParameter("myParam", "test1"); complexDispatcherPortlet.doDispatch(request, response); - Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); + Map<?, ?> model = (Map<?, ?>) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); Exception exception = (Exception) model.get("exception"); assertTrue(exception.getClass().equals(NoHandlerFoundException.class)); InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); @@ -333,7 +333,7 @@ public void testIncorrectLocaleInRequest() throws Exception { request.setParameter("myParam", "requestLocaleChecker"); request.addPreferredLocale(Locale.ENGLISH); complexDispatcherPortlet.doDispatch(request, response); - Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); + Map<?, ?> model = (Map<?, ?>) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); Exception exception = (Exception) model.get("exception"); assertTrue(exception.getClass().equals(PortletException.class)); assertEquals("Incorrect Locale in RenderRequest", exception.getMessage()); @@ -356,7 +356,7 @@ public void testIncorrectLocaleInLocalContextHolder() throws Exception { request.setParameter("myParam", "contextLocaleChecker"); request.addPreferredLocale(Locale.ENGLISH); complexDispatcherPortlet.doDispatch(request, response); - Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); + Map<?, ?> model = (Map<?, ?>) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); Exception exception = (Exception) model.get("exception"); assertTrue(exception.getClass().equals(PortletException.class)); assertEquals("Incorrect Locale in LocaleContextHolder", exception.getMessage()); @@ -401,7 +401,7 @@ public void testHandlerInterceptorNotClearingModelAndView() throws Exception { request.addUserRole("role1"); request.addParameter("noView", "false"); complexDispatcherPortlet.doDispatch(request, response); - Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); + Map<?, ?> model = (Map<?, ?>) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); assertEquals("view was here", model.get("result")); InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); assertEquals("someViewName", view.getBeanName()); @@ -414,7 +414,7 @@ public void testHandlerInterceptorClearingModelAndView() throws Exception { request.addUserRole("role1"); request.addParameter("noView", "true"); complexDispatcherPortlet.doDispatch(request, response); - Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); + Map<?, ?> model = (Map<?, ?>) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); assertNull(model); InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); assertNull(view); diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestDataBinderTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestDataBinderTests.java index 3bf246248935..7bb97cda6c06 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestDataBinderTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestDataBinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -166,7 +166,7 @@ public void testBindingMap() { public void testBindingSet() { TestBean bean = new TestBean(); - Set set = new LinkedHashSet<>(2); + Set<TestBean> set = new LinkedHashSet<TestBean>(2); set.add(new TestBean("test1")); set.add(new TestBean("test2")); bean.setSomeSet(set); @@ -181,7 +181,7 @@ public void testBindingSet() { assertNotNull(bean.getSomeSet()); assertEquals(2, bean.getSomeSet().size()); - Iterator iter = bean.getSomeSet().iterator(); + Iterator<?> iter = bean.getSomeSet().iterator(); TestBean bean1 = (TestBean) iter.next(); assertEquals("test1", bean1.getName()); diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletWebRequestTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletWebRequestTests.java index e52c722b2c34..da32fcfdc7af 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletWebRequestTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletWebRequestTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,13 +56,13 @@ public void testParameters() { assertEquals("value2", request.getParameterValues("param2")[0]); assertEquals("value2a", request.getParameterValues("param2")[1]); - Map paramMap = request.getParameterMap(); + Map<String, String[]> paramMap = request.getParameterMap(); assertEquals(2, paramMap.size()); - assertEquals(1, ((String[]) paramMap.get("param1")).length); - assertEquals("value1", ((String[]) paramMap.get("param1"))[0]); - assertEquals(2, ((String[]) paramMap.get("param2")).length); - assertEquals("value2", ((String[]) paramMap.get("param2"))[0]); - assertEquals("value2a", ((String[]) paramMap.get("param2"))[1]); + assertEquals(1, paramMap.get("param1").length); + assertEquals("value1", paramMap.get("param1")[0]); + assertEquals(2, paramMap.get("param2").length); + assertEquals("value2", paramMap.get("param2")[0]); + assertEquals("value2a", paramMap.get("param2")[1]); } @Test diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/Portlet20AnnotationControllerTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/Portlet20AnnotationControllerTests.java index 600dc7e8fa60..755738871e03 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/Portlet20AnnotationControllerTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/Portlet20AnnotationControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; + import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.EventResponse; @@ -173,7 +174,7 @@ public void adaptedHandleMethods4() throws Exception { doTestAdaptedHandleMethods(MyAdaptedController4.class); } - private void doTestAdaptedHandleMethods(final Class controllerClass) throws Exception { + private void doTestAdaptedHandleMethods(final Class<?> controllerClass) throws Exception { DispatcherPortlet portlet = new DispatcherPortlet() { @Override protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { @@ -1233,7 +1234,7 @@ public void myDefaultResource(Writer writer) throws IOException { private static class TestView { - public void render(String viewName, Map model, PortletRequest request, MimeResponse response) throws Exception { + public void render(String viewName, Map<String, Object> model, PortletRequest request, MimeResponse response) throws Exception { TestBean tb = (TestBean) model.get("testBean"); if (tb == null) { tb = (TestBean) model.get("myCommand"); @@ -1248,9 +1249,9 @@ public void render(String viewName, Map model, PortletRequest request, MimeRespo if (errors.hasFieldErrors("date")) { throw new IllegalStateException(); } - List<TestBean> testBeans = (List<TestBean>) model.get("testBeanList"); + List<?> testBeans = (List<?>) model.get("testBeanList"); response.getWriter().write(viewName + "-" + tb.getName() + "-" + errors.getFieldError("age").getCode() + - "-" + testBeans.get(0).getName() + "-" + model.get("myKey")); + "-" + ((TestBean) testBeans.get(0)).getName() + "-" + model.get("myKey")); } } diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationControllerTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationControllerTests.java index 7a58b4a1c45d..4ab35eae05d9 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationControllerTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -114,7 +114,7 @@ public void testAdaptedHandleMethods3() throws Exception { doTestAdaptedHandleMethods(MyAdaptedController3.class); } - public void doTestAdaptedHandleMethods(final Class controllerClass) throws Exception { + public void doTestAdaptedHandleMethods(final Class<?> controllerClass) throws Exception { DispatcherPortlet portlet = new DispatcherPortlet() { @Override protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { @@ -796,7 +796,7 @@ public void myHandle(RenderResponse response) throws IOException { private static class TestView { - public void render(String viewName, Map model, PortletRequest request, MimeResponse response) throws Exception { + public void render(String viewName, Map<String, Object> model, PortletRequest request, MimeResponse response) throws Exception { TestBean tb = (TestBean) model.get("testBean"); if (tb == null) { tb = (TestBean) model.get("myCommand"); @@ -811,9 +811,9 @@ public void render(String viewName, Map model, PortletRequest request, MimeRespo if (errors.hasFieldErrors("date")) { throw new IllegalStateException(); } - List<TestBean> testBeans = (List<TestBean>) model.get("testBeanList"); + List<?> testBeans = (List<?>) model.get("testBeanList"); response.getWriter().write(viewName + "-" + tb.getName() + "-" + errors.getFieldError("age").getCode() + - "-" + testBeans.get(0).getName() + "-" + model.get("myKey")); + "-" + ((TestBean) testBeans.get(0)).getName() + "-" + model.get("myKey")); } } @@ -830,7 +830,7 @@ public static class MyModelAndViewResolver implements ModelAndViewResolver { @Override public org.springframework.web.servlet.ModelAndView resolveModelAndView(Method handlerMethod, - Class handlerType, + Class<?> handlerType, Object returnValue, ExtendedModelMap implicitModel, NativeWebRequest webRequest) { diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/util/PortletUtilsTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/util/PortletUtilsTests.java index f7192f7accd0..ba0d45e9719e 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/util/PortletUtilsTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/util/PortletUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -245,8 +245,7 @@ public void testClearAllRenderParameters() throws Exception { public void testClearAllRenderParametersDoesNotPropagateExceptionIfRedirectAlreadySentAtTimeOfCall() throws Exception { MockActionResponse response = new MockActionResponse() { @Override - @SuppressWarnings("unchecked") - public void setRenderParameters(Map parameters) { + public void setRenderParameters(Map<String, String[]> parameters) { throw new IllegalStateException(); } }; @@ -302,7 +301,6 @@ public void testExposeRequestAttributesWithNullAttributesMap() throws Exception PortletUtils.exposeRequestAttributes(new MockPortletRequest(), null); } - @SuppressWarnings("unchecked") @Test public void testExposeRequestAttributesSunnyDay() throws Exception { MockPortletRequest request = new MockPortletRequest(); @@ -314,7 +312,6 @@ public void testExposeRequestAttributesSunnyDay() throws Exception { assertEquals("Roy Fokker", request.getAttribute("mentor")); } - @SuppressWarnings("unchecked") @Test public void testExposeRequestAttributesWithEmptyAttributesMapIsAnIdempotentOperation() throws Exception { MockPortletRequest request = new MockPortletRequest();
0fdcf884987f1906a6ebfe2a2cb7cc86e05440ed
hadoop
HDFS-1330 and HADOOP-6889. Added additional unit- tests. Contributed by John George.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.23@1163464 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 595f4678ce6c4..9ddcdf8bfa8c5 100644 --- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt +++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt @@ -1084,6 +1084,7 @@ Release 0.22.0 - Unreleased (jghoman) HDFS-1330. Make RPCs to DataNodes timeout. (hairong) + Added additional unit tests per HADOOP-6889. (John George via mattf) HDFS-202. HDFS support of listLocatedStatus introduced in HADOOP-6870. HDFS piggyback block locations to each file status when listing a diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSClientRetries.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSClientRetries.java index 05fa648653a75..714bce7045e3a 100644 --- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSClientRetries.java +++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSClientRetries.java @@ -25,7 +25,12 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; +import java.net.SocketTimeoutException; +import org.apache.hadoop.io.IOUtils; +import org.apache.hadoop.io.Writable; +import org.apache.hadoop.io.LongWritable; import java.io.IOException; +import java.net.InetSocketAddress; import java.io.InputStream; import java.io.OutputStream; import java.security.MessageDigest; @@ -44,6 +49,8 @@ import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.protocol.DatanodeID; +import org.apache.hadoop.hdfs.protocol.Block; +import org.apache.hadoop.hdfs.protocol.ClientDatanodeProtocol; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.protocol.ExtendedBlock; import org.apache.hadoop.hdfs.protocol.LocatedBlock; @@ -52,6 +59,11 @@ import org.apache.hadoop.hdfs.server.namenode.NotReplicatedYetException; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.ipc.RemoteException; +import org.apache.hadoop.ipc.Client; +import org.apache.hadoop.ipc.ProtocolSignature; +import org.apache.hadoop.ipc.RPC; +import org.apache.hadoop.ipc.Server; +import org.apache.hadoop.net.NetUtils; import org.mockito.internal.stubbing.answers.ThrowsException; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -61,9 +73,51 @@ * properly in case of errors. */ public class TestDFSClientRetries extends TestCase { + private static final String ADDRESS = "0.0.0.0"; + final static private int PING_INTERVAL = 1000; + final static private int MIN_SLEEP_TIME = 1000; public static final Log LOG = LogFactory.getLog(TestDFSClientRetries.class.getName()); - + final static private Configuration conf = new HdfsConfiguration(); + + private static class TestServer extends Server { + private boolean sleep; + private Class<? extends Writable> responseClass; + + public TestServer(int handlerCount, boolean sleep) throws IOException { + this(handlerCount, sleep, LongWritable.class, null); + } + + public TestServer(int handlerCount, boolean sleep, + Class<? extends Writable> paramClass, + Class<? extends Writable> responseClass) + throws IOException { + super(ADDRESS, 0, paramClass, handlerCount, conf); + this.sleep = sleep; + this.responseClass = responseClass; + } + + @Override + public Writable call(Class<?> protocol, Writable param, long receiveTime) + throws IOException { + if (sleep) { + // sleep a bit + try { + Thread.sleep(PING_INTERVAL + MIN_SLEEP_TIME); + } catch (InterruptedException e) {} + } + if (responseClass != null) { + try { + return responseClass.newInstance(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } else { + return param; // echo param as result + } + } + } + // writes 'len' bytes of data to out. private static void writeData(OutputStream out, int len) throws IOException { byte [] buf = new byte[4096*16]; @@ -80,8 +134,6 @@ private static void writeData(OutputStream out, int len) throws IOException { */ public void testWriteTimeoutAtDataNode() throws IOException, InterruptedException { - Configuration conf = new HdfsConfiguration(); - final int writeTimeout = 100; //milliseconds. // set a very short write timeout for datanode, so that tests runs fast. conf.setInt(DFSConfigKeys.DFS_DATANODE_SOCKET_WRITE_TIMEOUT_KEY, writeTimeout); @@ -136,7 +188,6 @@ public void testNotYetReplicatedErrors() throws IOException { final String exceptionMsg = "Nope, not replicated yet..."; final int maxRetries = 1; // Allow one retry (total of two calls) - Configuration conf = new HdfsConfiguration(); conf.setInt(DFSConfigKeys.DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_KEY, maxRetries); NameNode mockNN = mock(NameNode.class); @@ -182,7 +233,6 @@ public void testFailuresArePerOperation() throws Exception long fileSize = 4096; Path file = new Path("/testFile"); - Configuration conf = new Configuration(); // Set short retry timeout so this test runs faster conf.setInt(DFSConfigKeys.DFS_CLIENT_RETRY_WINDOW_BASE, 10); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build(); @@ -379,7 +429,6 @@ private boolean busyTest(int xcievers, int threads, int fileLen, int timeWin, in long blockSize = 128*1024*1024; // DFS block size int bufferSize = 4096; - Configuration conf = new HdfsConfiguration(); conf.setInt(DFSConfigKeys.DFS_DATANODE_MAX_RECEIVER_THREADS_KEY, xcievers); conf.setInt(DFSConfigKeys.DFS_CLIENT_MAX_BLOCK_ACQUIRE_FAILURES_KEY, retries); @@ -540,7 +589,6 @@ public void testGetFileChecksum() throws Exception { final String f = "/testGetFileChecksum"; final Path p = new Path(f); - final Configuration conf = new Configuration(); final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(3).build(); try { cluster.waitActive(); @@ -566,5 +614,39 @@ public void testGetFileChecksum() throws Exception { cluster.shutdown(); } } + + /** Test that timeout occurs when DN does not respond to RPC. + * Start up a server and ask it to sleep for n seconds. Make an + * RPC to the server and set rpcTimeout to less than n and ensure + * that socketTimeoutException is obtained + */ + public void testClientDNProtocolTimeout() throws IOException { + final Server server = new TestServer(1, true); + server.start(); + + final InetSocketAddress addr = NetUtils.getConnectAddress(server); + DatanodeID fakeDnId = new DatanodeID( + "localhost:" + addr.getPort(), "fake-storage", 0, addr.getPort()); + + ExtendedBlock b = new ExtendedBlock("fake-pool", new Block(12345L)); + LocatedBlock fakeBlock = new LocatedBlock(b, new DatanodeInfo[0]); + + ClientDatanodeProtocol proxy = null; + + try { + proxy = DFSUtil.createClientDatanodeProtocolProxy( + fakeDnId, conf, 500, fakeBlock); + + proxy.getReplicaVisibleLength(null); + fail ("Did not get expected exception: SocketTimeoutException"); + } catch (SocketTimeoutException e) { + LOG.info("Got the expected Exception: SocketTimeoutException"); + } finally { + if (proxy != null) { + RPC.stopProxy(proxy); + } + server.stop(); + } + } } diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestInterDatanodeProtocol.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestInterDatanodeProtocol.java index eb58f7f195afc..b1f1fc911c9a9 100644 --- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestInterDatanodeProtocol.java +++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestInterDatanodeProtocol.java @@ -22,6 +22,20 @@ import java.io.IOException; import java.util.List; +import java.net.InetSocketAddress; + +import java.net.SocketTimeoutException; +import org.apache.hadoop.io.IOUtils; +import org.apache.hadoop.io.Writable; +import org.apache.hadoop.io.LongWritable; +import org.apache.hadoop.security.UserGroupInformation; +import org.apache.hadoop.util.StringUtils; + +import org.apache.hadoop.ipc.Client; +import org.apache.hadoop.ipc.ProtocolSignature; +import org.apache.hadoop.ipc.RPC; +import org.apache.hadoop.ipc.Server; +import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; @@ -38,6 +52,7 @@ import org.apache.hadoop.hdfs.protocol.LocatedBlocks; import org.apache.hadoop.hdfs.protocol.RecoveryInProgressException; import org.apache.hadoop.hdfs.server.common.HdfsConstants.ReplicaState; +import org.apache.hadoop.hdfs.protocol.DatanodeID; import org.apache.hadoop.hdfs.server.protocol.InterDatanodeProtocol; import org.apache.hadoop.hdfs.server.protocol.ReplicaRecoveryInfo; import org.apache.hadoop.hdfs.server.protocol.BlockRecoveryCommand.RecoveringBlock; @@ -48,6 +63,50 @@ * This tests InterDataNodeProtocol for block handling. */ public class TestInterDatanodeProtocol { + private static final String ADDRESS = "0.0.0.0"; + final static private int PING_INTERVAL = 1000; + final static private int MIN_SLEEP_TIME = 1000; + private static Configuration conf = new HdfsConfiguration(); + + + private static class TestServer extends Server { + private boolean sleep; + private Class<? extends Writable> responseClass; + + public TestServer(int handlerCount, boolean sleep) throws IOException { + this(handlerCount, sleep, LongWritable.class, null); + } + + public TestServer(int handlerCount, boolean sleep, + Class<? extends Writable> paramClass, + Class<? extends Writable> responseClass) + throws IOException { + super(ADDRESS, 0, paramClass, handlerCount, conf); + this.sleep = sleep; + this.responseClass = responseClass; + } + + @Override + public Writable call(Class<?> protocol, Writable param, long receiveTime) + throws IOException { + if (sleep) { + // sleep a bit + try { + Thread.sleep(PING_INTERVAL + MIN_SLEEP_TIME); + } catch (InterruptedException e) {} + } + if (responseClass != null) { + try { + return responseClass.newInstance(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } else { + return param; // echo param as result + } + } + } + public static void checkMetaInfo(ExtendedBlock b, DataNode dn) throws IOException { Block metainfo = dn.data.getStoredBlock(b.getBlockPoolId(), b.getBlockId()); Assert.assertEquals(b.getBlockId(), metainfo.getBlockId()); @@ -73,7 +132,6 @@ public static LocatedBlock getLastLocatedBlock( */ @Test public void testBlockMetaDataInfo() throws Exception { - Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = null; try { @@ -222,7 +280,6 @@ public void testInitReplicaRecovery() throws IOException { * */ @Test public void testUpdateReplicaUnderRecovery() throws IOException { - final Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = null; try { @@ -291,4 +348,33 @@ public void testUpdateReplicaUnderRecovery() throws IOException { if (cluster != null) cluster.shutdown(); } } + + /** Test to verify that InterDatanode RPC timesout as expected when + * the server DN does not respond. + */ + @Test + public void testInterDNProtocolTimeout() throws Exception { + final Server server = new TestServer(1, true); + server.start(); + + final InetSocketAddress addr = NetUtils.getConnectAddress(server); + DatanodeID fakeDnId = new DatanodeID( + "localhost:" + addr.getPort(), "fake-storage", 0, addr.getPort()); + DatanodeInfo dInfo = new DatanodeInfo(fakeDnId); + InterDatanodeProtocol proxy = null; + + try { + proxy = DataNode.createInterDataNodeProtocolProxy( + dInfo, conf, 500); + proxy.initReplicaRecovery(null); + fail ("Expected SocketTimeoutException exception, but did not get."); + } catch (SocketTimeoutException e) { + DataNode.LOG.info("Got expected Exception: SocketTimeoutException" + e); + } finally { + if (proxy != null) { + RPC.stopProxy(proxy); + } + server.stop(); + } + } }
fbf70d4fbfd01a5f7f5798c32d61aad97b7ca540
drools
fix test using using no longer existing- ConsequenceException.getRule() method--
c
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java b/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java index c2b421650e1..7ce9c814c87 100644 --- a/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java +++ b/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java @@ -2874,7 +2874,7 @@ public void testConsequenceException() throws Exception { fail( "Should throw an Exception from the Consequence" ); } catch ( final org.drools.runtime.rule.ConsequenceException e ) { assertEquals( "Throw Consequence Exception", - e.getRule().getName() ); + e.getActivation().getRule().getName() ); assertEquals( "this should throw an exception", e.getCause().getMessage() ); }
1fa7b71cf82cc30757ecf5d2a8e0cfba654ed469
hbase
HBASE-14807 TestWALLockup is flakey--
c
https://github.com/apache/hbase
diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestWALLockup.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestWALLockup.java index a7014434f62b..708801033e24 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestWALLockup.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestWALLockup.java @@ -20,7 +20,6 @@ import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.io.IOException; import java.util.concurrent.CountDownLatch; @@ -30,6 +29,7 @@ import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; +import org.apache.hadoop.hbase.CellScanner; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HTableDescriptor; @@ -103,7 +103,7 @@ String getName() { * <p>First I need to set up some mocks for Server and RegionServerServices. I also need to * set up a dodgy WAL that will throw an exception when we go to append to it. */ - @Test (timeout=30000) + @Test (timeout=15000) public void testLockupWhenSyncInMiddleOfZigZagSetup() throws IOException { // A WAL that we can have throw exceptions when a flag is set. class DodgyFSLog extends FSHLog { @@ -209,15 +209,21 @@ public long getLength() throws IOException { put.addColumn(COLUMN_FAMILY_BYTES, Bytes.toBytes("1"), bytes); WALKey key = new WALKey(region.getRegionInfo().getEncodedNameAsBytes(), htd.getTableName()); WALEdit edit = new WALEdit(); + CellScanner CellScanner = put.cellScanner(); + assertTrue(CellScanner.advance()); + edit.add(CellScanner.current()); // Put something in memstore and out in the WAL. Do a big number of appends so we push // out other side of the ringbuffer. If small numbers, stuff doesn't make it to WAL for (int i = 0; i < 1000; i++) { - dodgyWAL.append(htd, region.getRegionInfo(), key, edit, true); + region.put(put); } // Set it so we start throwing exceptions. + LOG.info("SET throwing of exception on append"); dodgyWAL.throwException = true; - // This append provokes a WAL roll. + // This append provokes a WAL roll request dodgyWAL.append(htd, region.getRegionInfo(), key, edit, true); + // Now wait until the dodgy WAL is latched. + while (dodgyWAL.latch.getCount() <= 0) Threads.sleep(1); boolean exception = false; try { dodgyWAL.sync(); @@ -229,20 +235,25 @@ public long getLength() throws IOException { // Get a memstore flush going too so we have same hung profile as up in the issue over // in HBASE-14317. Flush hangs trying to get sequenceid because the ringbuffer is held up // by the zigzaglatch waiting on syncs to come home. - Thread t = new Thread ("flusher") { + Thread t = new Thread ("Flusher") { public void run() { try { + if (region.getMemstoreSize() <= 0) { + throw new IOException("memstore size=" + region.getMemstoreSize()); + } region.flush(false); } catch (IOException e) { + // Can fail trying to flush in middle of a roll. Not a failure. Will succeed later + // when roll completes. LOG.info("In flush", e); - fail(); } + LOG.info("Exiting"); }; }; t.setDaemon(true); t.start(); - // Wait till it gets into flushing. It will get stuck on getSequenceId. Then proceed. - while (!region.writestate.flushing) Threads.sleep(1); + // Wait until + while (dodgyWAL.latch.getCount() > 0) Threads.sleep(1); // Now assert I got a new WAL file put in place even though loads of errors above. assertTrue(originalWAL != dodgyWAL.getCurrentFileName()); // Can I append to it?
04fcbeb2f833e55887de9149cbd25bfaec38d4de
adangel$pmd
Refactoring - pushed property mgmt functionality into new superclass now shared by the report renderers git-svn-id: https://pmd.svn.sourceforge.net/svnroot/pmd/trunk@7294 51baf565-9d33-0410-a72c-fc3788e3496d
p
https://github.com/adangel/pmd
diff --git a/pmd/src/net/sourceforge/pmd/AbstractPropertySource.java b/pmd/src/net/sourceforge/pmd/AbstractPropertySource.java new file mode 100644 index 00000000000..d88b0a5aa1f --- /dev/null +++ b/pmd/src/net/sourceforge/pmd/AbstractPropertySource.java @@ -0,0 +1,173 @@ +package net.sourceforge.pmd; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import net.sourceforge.pmd.util.CollectionUtil; + +/** + * + * @author Brian Remedios + */ +public abstract class AbstractPropertySource { + + protected List<PropertyDescriptor<?>> propertyDescriptors = new ArrayList<PropertyDescriptor<?>>(); + protected Map<PropertyDescriptor<?>, Object> propertyValuesByDescriptor = new HashMap<PropertyDescriptor<?>, Object>(); + + public AbstractPropertySource() { + super(); + } + + protected List<PropertyDescriptor<?>> copyPropertyDescriptors() { + List<PropertyDescriptor<?>> copy = new ArrayList<PropertyDescriptor<?>>(propertyDescriptors.size()); + copy.addAll(propertyDescriptors); + return copy; + } + + protected Map<PropertyDescriptor<?>, Object> copyPropertyValues() { + Map<PropertyDescriptor<?>, Object> copy = new HashMap<PropertyDescriptor<?>, Object>(propertyValuesByDescriptor.size()); + copy.putAll(propertyValuesByDescriptor); + return copy; + } + + /** + * @see Rule#ignoredProperties() + */ + public Set<PropertyDescriptor<?>> ignoredProperties() { + return Collections.emptySet(); + } + + /** + * @see Rule#definePropertyDescriptor(PropertyDescriptor) + */ + public void definePropertyDescriptor(PropertyDescriptor<?> propertyDescriptor) { + // Check to ensure the property does not already exist. + for (PropertyDescriptor<?> descriptor : propertyDescriptors) { + if (descriptor.name().equals(propertyDescriptor.name())) { + throw new IllegalArgumentException("There is already a PropertyDescriptor with name '" + + propertyDescriptor.name() + "' defined on Rule " + getName() + "."); + } + } + propertyDescriptors.add(propertyDescriptor); + // Sort in UI order + Collections.sort(propertyDescriptors); + } + + public abstract String getName(); + + /** + * @see Rule#getPropertyDescriptor(String) + */ + public PropertyDescriptor<?> getPropertyDescriptor(String name) { + for (PropertyDescriptor<?> propertyDescriptor : propertyDescriptors) { + if (name.equals(propertyDescriptor.name())) { + return propertyDescriptor; + } + } + return null; + } + + /** + * @see Rule#hasDescriptor(PropertyDescriptor) + */ + public boolean hasDescriptor(PropertyDescriptor<?> descriptor) { + + if (propertyValuesByDescriptor.isEmpty()) { + getPropertiesByPropertyDescriptor(); // compute it + } + + return propertyValuesByDescriptor.containsKey(descriptor); + } + + /** + * @see Rule#getPropertyDescriptors() + */ + public List<PropertyDescriptor<?>> getPropertyDescriptors() { + return propertyDescriptors; + } + + /** + * @see Rule#getProperty(PropertyDescriptor) + */ + @SuppressWarnings("unchecked") + public <T> T getProperty(PropertyDescriptor<T> propertyDescriptor) { + checkValidPropertyDescriptor(propertyDescriptor); + T value; + if (propertyValuesByDescriptor.containsKey(propertyDescriptor)) { + value = (T) propertyValuesByDescriptor.get(propertyDescriptor); + } else { + value = propertyDescriptor.defaultValue(); + } + return value; + } + + /** + * @see Rule#setProperty(PropertyDescriptor, Object) + */ + public <T> void setProperty(PropertyDescriptor<T> propertyDescriptor, T value) { + checkValidPropertyDescriptor(propertyDescriptor); + propertyValuesByDescriptor.put(propertyDescriptor, value); + } + + private void checkValidPropertyDescriptor(PropertyDescriptor<?> propertyDescriptor) { + if (!propertyDescriptors.contains(propertyDescriptor)) { + throw new IllegalArgumentException("Property descriptor not defined for Rule " + getName() + ": " + + propertyDescriptor); + } + } + + /** + * @see Rule#getPropertiesByPropertyDescriptor() + */ + public Map<PropertyDescriptor<?>, Object> getPropertiesByPropertyDescriptor() { + if (propertyDescriptors.isEmpty()) { + return Collections.emptyMap(); + } + + Map<PropertyDescriptor<?>, Object> propertiesByPropertyDescriptor = new HashMap<PropertyDescriptor<?>, Object>( + propertyDescriptors.size()); + // Fill with existing explicitly values + propertiesByPropertyDescriptor.putAll(this.propertyValuesByDescriptor); + + // Add default values for anything not yet set + for (PropertyDescriptor<?> propertyDescriptor : this.propertyDescriptors) { + if (!propertiesByPropertyDescriptor.containsKey(propertyDescriptor)) { + propertiesByPropertyDescriptor.put(propertyDescriptor, propertyDescriptor.defaultValue()); + } + } + + return propertiesByPropertyDescriptor; + } + + /** + * @see Rule#usesDefaultValues() + */ + public boolean usesDefaultValues() { + + Map<PropertyDescriptor<?>, Object> valuesByProperty = getPropertiesByPropertyDescriptor(); + if (valuesByProperty.isEmpty()) { + return true; + } + + Iterator<Map.Entry<PropertyDescriptor<?>, Object>> iter = valuesByProperty.entrySet().iterator(); + + while (iter.hasNext()) { + Map.Entry<PropertyDescriptor<?>, Object> entry = iter.next(); + if (!CollectionUtil.areEqual(entry.getKey().defaultValue(), entry.getValue())) { + return false; + } + } + + return true; + } + + public void useDefaultValueFor(PropertyDescriptor<?> desc) { + propertyValuesByDescriptor.remove(desc); + } + +} \ No newline at end of file diff --git a/pmd/src/net/sourceforge/pmd/PropertySource.java b/pmd/src/net/sourceforge/pmd/PropertySource.java new file mode 100644 index 00000000000..38524c1e7c3 --- /dev/null +++ b/pmd/src/net/sourceforge/pmd/PropertySource.java @@ -0,0 +1,90 @@ +package net.sourceforge.pmd; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * + * @author Brian Remedios + */ +public interface PropertySource { + + /** + * Define a new property via a PropertyDescriptor. + * + * @param propertyDescriptor The property descriptor. + * @throws IllegalArgumentException If there is already a property defined the same name. + */ + void definePropertyDescriptor(PropertyDescriptor<?> propertyDescriptor) throws IllegalArgumentException; + + /** + * Get the PropertyDescriptor for the given property name. + * + * @param name The name of the property. + * @return The PropertyDescriptor for the named property, <code>null</code> if there is no such property defined. + */ + PropertyDescriptor<?> getPropertyDescriptor(String name); + + /** + * Get the PropertyDescriptors for all defined properties. The properties + * are returned sorted by UI order. + * + * @return The PropertyDescriptors in UI order. + */ + List<PropertyDescriptor<?>> getPropertyDescriptors(); + + /** + * Get the typed value for the given property. + * + * @param <T> The underlying type of the property descriptor. + * @param propertyDescriptor The property descriptor. + * @return The property value. + */ + <T> T getProperty(PropertyDescriptor<T> propertyDescriptor); + + /** + * Set the property value specified (will be type-checked) + * + * @param <T> The underlying type of the property descriptor. + * @param propertyDescriptor The property descriptor. + * @param value The value to set. + */ + <T> void setProperty(PropertyDescriptor<T> propertyDescriptor, T value); + + /** + * Returns all the current property values for the receiver or an + * immutable empty map if none are specified. + */ + Map<PropertyDescriptor<?>, Object> getPropertiesByPropertyDescriptor(); + + /** + * Returns whether this Rule has the specified PropertyDescriptor. + * + * @param descriptor The PropertyDescriptor for which to check. + * @return boolean <code>true</code> if the descriptor is present, <code>false</code> otherwise. + */ + boolean hasDescriptor(PropertyDescriptor<?> descriptor); + + /** + * Returns whether this Rule uses default values for properties. + * @return boolean <code>true</code> if the properties all have default values, <code>false</code> otherwise. + */ + boolean usesDefaultValues(); + + /** + * Clears out any user-specified value for the property allowing it to use the default + * value in the descriptor. + * + * @param desc + */ + void useDefaultValueFor(PropertyDescriptor<?> desc); + + /** + * Return the properties that are effectively ignored due to the configuration + * of the rule and values held by other properties. This can be used to disable + * corresponding widgets in a UI. + * + */ + Set<PropertyDescriptor<?>> ignoredProperties(); +} diff --git a/pmd/src/net/sourceforge/pmd/Rule.java b/pmd/src/net/sourceforge/pmd/Rule.java index 04f84062519..ac5326c52b4 100644 --- a/pmd/src/net/sourceforge/pmd/Rule.java +++ b/pmd/src/net/sourceforge/pmd/Rule.java @@ -4,8 +4,6 @@ package net.sourceforge.pmd; import java.util.List; -import java.util.Map; -import java.util.Set; import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageVersion; @@ -18,7 +16,7 @@ * This is the basic Rule interface for PMD rules. */ //FUTURE Implement Cloneable and clone() -public interface Rule { +public interface Rule extends PropertySource { /** * The property descriptor to universally suppress violations with messages matching a regular expression. @@ -84,14 +82,6 @@ public interface Rule { */ String dysfunctionReason(); - /** - * Return the properties that are effectively ignored due to the configuration - * of the rule and values held by other properties. This can be used to disable - * corresponding widgets in a UI. - * - */ - Set<PropertyDescriptor<?>> ignoredProperties(); - /** * Sets whether this Rule is deprecated. */ @@ -199,76 +189,6 @@ public interface Rule { * return a new instance on each call. */ ParserOptions getParserOptions(); - - /** - * Define a new property via a PropertyDescriptor. - * - * @param propertyDescriptor The property descriptor. - * @throws IllegalArgumentException If there is already a property defined the same name. - */ - void definePropertyDescriptor(PropertyDescriptor<?> propertyDescriptor) throws IllegalArgumentException; - - /** - * Get the PropertyDescriptor for the given property name. - * - * @param name The name of the property. - * @return The PropertyDescriptor for the named property, <code>null</code> if there is no such property defined. - */ - PropertyDescriptor<?> getPropertyDescriptor(String name); - - /** - * Get the PropertyDescriptors for all defined properties. The properties - * are returned sorted by UI order. - * - * @return The PropertyDescriptors in UI order. - */ - List<PropertyDescriptor<?>> getPropertyDescriptors(); - - /** - * Get the typed value for the given property. - * - * @param <T> The underlying type of the property descriptor. - * @param propertyDescriptor The property descriptor. - * @return The property value. - */ - <T> T getProperty(PropertyDescriptor<T> propertyDescriptor); - - /** - * Set the property value specified (will be type-checked) - * - * @param <T> The underlying type of the property descriptor. - * @param propertyDescriptor The property descriptor. - * @param value The value to set. - */ - <T> void setProperty(PropertyDescriptor<T> propertyDescriptor, T value); - - /** - * Returns all the current property values for the receiver or an - * immutable empty map if none are specified. - */ - Map<PropertyDescriptor<?>, Object> getPropertiesByPropertyDescriptor(); - - /** - * Returns whether this Rule has the specified PropertyDescriptor. - * - * @param descriptor The PropertyDescriptor for which to check. - * @return boolean <code>true</code> if the descriptor is present, <code>false</code> otherwise. - */ - boolean hasDescriptor(PropertyDescriptor<?> descriptor); - - /** - * Returns whether this Rule uses default values for properties. - * @return boolean <code>true</code> if the properties all have default values, <code>false</code> otherwise. - */ - boolean usesDefaultValues(); - - /** - * Clears out any user-specified value for the property allowing it to use the default - * value in the descriptor. - * - * @param desc - */ - void useDefaultValueFor(PropertyDescriptor<?> desc); /** * Sets whether this Rule uses Data Flow Analysis. diff --git a/pmd/src/net/sourceforge/pmd/lang/rule/AbstractRule.java b/pmd/src/net/sourceforge/pmd/lang/rule/AbstractRule.java index d01baf4d03c..9ee79b4089d 100644 --- a/pmd/src/net/sourceforge/pmd/lang/rule/AbstractRule.java +++ b/pmd/src/net/sourceforge/pmd/lang/rule/AbstractRule.java @@ -4,14 +4,9 @@ package net.sourceforge.pmd.lang.rule; import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; import java.util.List; -import java.util.Map; -import java.util.Set; -import net.sourceforge.pmd.PropertyDescriptor; +import net.sourceforge.pmd.AbstractPropertySource; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.RulePriority; @@ -19,7 +14,6 @@ import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.ParserOptions; import net.sourceforge.pmd.lang.ast.Node; -import net.sourceforge.pmd.util.CollectionUtil; /** * Basic abstract implementation of all parser-independent methods of the Rule @@ -28,7 +22,7 @@ * @author pieter_van_raemdonck - Application Engineers NV/SA - www.ae.be */ // FUTURE Implement Cloneable and clone()? -public abstract class AbstractRule implements Rule { +public abstract class AbstractRule extends AbstractPropertySource implements Rule { private Language language; private LanguageVersion minimumLanguageVersion; @@ -43,9 +37,6 @@ public abstract class AbstractRule implements Rule { private List<String> examples = new ArrayList<String>(); private String externalInfoUrl; private RulePriority priority = RulePriority.LOW; - private List<PropertyDescriptor<?>> propertyDescriptors = new ArrayList<PropertyDescriptor<?>>(); - // Map of explicitly set property values. - private Map<PropertyDescriptor<?>, Object> propertyValuesByDescriptor = new HashMap<PropertyDescriptor<?>, Object>(); private boolean usesDFA; private boolean usesTypeResolution; private List<String> ruleChainVisits = new ArrayList<String>(); @@ -82,18 +73,6 @@ private List<String> copyExamples() { return copy; } - private List<PropertyDescriptor<?>> copyPropertyDescriptors() { - List<PropertyDescriptor<?>> copy = new ArrayList<PropertyDescriptor<?>>(propertyDescriptors.size()); - copy.addAll(propertyDescriptors); - return copy; - } - - private Map<PropertyDescriptor<?>, Object> copyPropertyValues() { - Map<PropertyDescriptor<?>, Object> copy = new HashMap<PropertyDescriptor<?>, Object>(propertyValuesByDescriptor.size()); - copy.putAll(propertyValuesByDescriptor); - return copy; - } - private List<String> copyRuleChainVisits() { List<String> copy = new ArrayList<String>(ruleChainVisits.size()); copy.addAll(ruleChainVisits); @@ -160,13 +139,6 @@ public String dysfunctionReason() { return null; } - /** - * @see Rule#ignoredProperties() - */ - public Set<PropertyDescriptor<?>> ignoredProperties() { - return Collections.EMPTY_SET; - } - /** * @see Rule#setDeprecated(boolean) */ @@ -310,132 +282,6 @@ public ParserOptions getParserOptions() { return new ParserOptions(); } - /** - * @see Rule#definePropertyDescriptor(PropertyDescriptor) - */ - public void definePropertyDescriptor(PropertyDescriptor<?> propertyDescriptor) { - // Check to ensure the property does not already exist. - for (PropertyDescriptor<?> descriptor : propertyDescriptors) { - if (descriptor.name().equals(propertyDescriptor.name())) { - throw new IllegalArgumentException("There is already a PropertyDescriptor with name '" - + propertyDescriptor.name() + "' defined on Rule " + this.getName() + "."); - } - } - propertyDescriptors.add(propertyDescriptor); - // Sort in UI order - Collections.sort(propertyDescriptors); - } - - /** - * @see Rule#getPropertyDescriptor(String) - */ - public PropertyDescriptor<?> getPropertyDescriptor(String name) { - for (PropertyDescriptor<?> propertyDescriptor : propertyDescriptors) { - if (name.equals(propertyDescriptor.name())) { - return propertyDescriptor; - } - } - return null; - } - - /** - * @see Rule#hasDescriptor(PropertyDescriptor) - */ - public boolean hasDescriptor(PropertyDescriptor<?> descriptor) { - - if (propertyValuesByDescriptor.isEmpty()) { - getPropertiesByPropertyDescriptor(); // compute it - } - - return propertyValuesByDescriptor.containsKey(descriptor); - } - - /** - * @see Rule#getPropertyDescriptors() - */ - public List<PropertyDescriptor<?>> getPropertyDescriptors() { - return propertyDescriptors; - } - - /** - * @see Rule#getProperty(PropertyDescriptor) - */ - @SuppressWarnings("unchecked") - public <T> T getProperty(PropertyDescriptor<T> propertyDescriptor) { - checkValidPropertyDescriptor(propertyDescriptor); - T value; - if (propertyValuesByDescriptor.containsKey(propertyDescriptor)) { - value = (T) propertyValuesByDescriptor.get(propertyDescriptor); - } else { - value = propertyDescriptor.defaultValue(); - } - return value; - } - - /** - * @see Rule#setProperty(PropertyDescriptor, Object) - */ - public <T> void setProperty(PropertyDescriptor<T> propertyDescriptor, T value) { - checkValidPropertyDescriptor(propertyDescriptor); - propertyValuesByDescriptor.put(propertyDescriptor, value); - } - - private void checkValidPropertyDescriptor(PropertyDescriptor<?> propertyDescriptor) { - if (!propertyDescriptors.contains(propertyDescriptor)) { - throw new IllegalArgumentException("Property descriptor not defined for Rule " + this.getName() + ": " - + propertyDescriptor); - } - } - - /** - * @see Rule#getPropertiesByPropertyDescriptor() - */ - public Map<PropertyDescriptor<?>, Object> getPropertiesByPropertyDescriptor() { - if (propertyDescriptors.isEmpty()) { - return Collections.emptyMap(); - } - - Map<PropertyDescriptor<?>, Object> propertiesByPropertyDescriptor = new HashMap<PropertyDescriptor<?>, Object>( - propertyDescriptors.size()); - // Fill with existing explicitly values - propertiesByPropertyDescriptor.putAll(this.propertyValuesByDescriptor); - - // Add default values for anything not yet set - for (PropertyDescriptor<?> propertyDescriptor : this.propertyDescriptors) { - if (!propertiesByPropertyDescriptor.containsKey(propertyDescriptor)) { - propertiesByPropertyDescriptor.put(propertyDescriptor, propertyDescriptor.defaultValue()); - } - } - - return propertiesByPropertyDescriptor; - } - - /** - * @see Rule#usesDefaultValues() - */ - public boolean usesDefaultValues() { - - Map<PropertyDescriptor<?>, Object> valuesByProperty = getPropertiesByPropertyDescriptor(); - if (valuesByProperty.isEmpty()) { - return true; - } - - Iterator<Map.Entry<PropertyDescriptor<?>, Object>> iter = valuesByProperty.entrySet().iterator(); - - while (iter.hasNext()) { - Map.Entry<PropertyDescriptor<?>, Object> entry = iter.next(); - if (!CollectionUtil.areEqual(entry.getKey().defaultValue(), entry.getValue())) { - return false; - } - } - - return true; - } - - public void useDefaultValueFor(PropertyDescriptor<?> desc) { - propertyValuesByDescriptor.remove(desc); - } - /** * @see Rule#setUsesDFA() */ diff --git a/pmd/src/net/sourceforge/pmd/renderers/AbstractRenderer.java b/pmd/src/net/sourceforge/pmd/renderers/AbstractRenderer.java index c8b178c55ef..3b31ef02fbc 100644 --- a/pmd/src/net/sourceforge/pmd/renderers/AbstractRenderer.java +++ b/pmd/src/net/sourceforge/pmd/renderers/AbstractRenderer.java @@ -8,11 +8,14 @@ import java.util.Map; import java.util.Properties; +import net.sourceforge.pmd.AbstractPropertySource; +import net.sourceforge.pmd.lang.rule.properties.StringProperty; + /** * Abstract base class for {@link Renderer} implementations. */ -public abstract class AbstractRenderer implements Renderer { - +public abstract class AbstractRenderer extends AbstractPropertySource implements Renderer { + protected String name; protected String description; protected Map<String, String> propertyDefinitions = new LinkedHashMap<String, String>(); @@ -21,9 +24,9 @@ public abstract class AbstractRenderer implements Renderer { protected Writer writer; public AbstractRenderer(String name, String description, Properties properties) { - this.name = name; - this.description = description; - this.properties = properties; + this.name = name; + this.description = description; + this.properties = properties; } /** diff --git a/pmd/src/net/sourceforge/pmd/renderers/Renderer.java b/pmd/src/net/sourceforge/pmd/renderers/Renderer.java index f6b30c5dcf5..d0d56d9b192 100644 --- a/pmd/src/net/sourceforge/pmd/renderers/Renderer.java +++ b/pmd/src/net/sourceforge/pmd/renderers/Renderer.java @@ -7,6 +7,7 @@ import java.io.Writer; import java.util.Map; +import net.sourceforge.pmd.PropertySource; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.util.datasource.DataSource; @@ -30,7 +31,7 @@ * Renderer. */ // TODO Are implementations expected to be thread-safe? -public interface Renderer { +public interface Renderer extends PropertySource { /** * Get the name of the Renderer.
8ef67e8fbfbfc72605c7a2b45ba9ad82ccce7a15
Vala
clutter-1.0: Text.position_to_coords float params are out and nullable Fixes bug 621491.
c
https://github.com/GNOME/vala/
diff --git a/vapi/clutter-1.0.vapi b/vapi/clutter-1.0.vapi index b093aac5bd..ffb18fe13d 100644 --- a/vapi/clutter-1.0.vapi +++ b/vapi/clutter-1.0.vapi @@ -1043,7 +1043,7 @@ namespace Clutter { public unowned string get_selection (); public void insert_text (string text, ssize_t position); public void insert_unichar (unichar wc); - public bool position_to_coords (int position, float x, float y, float line_height); + public bool position_to_coords (int position, out float? x = null, out float? y = null, out float? line_height = null); public void set_attributes (Pango.AttrList attrs); public void set_cursor_position (int position); public void set_font_description (Pango.FontDescription font_desc); diff --git a/vapi/packages/clutter-1.0/clutter-1.0.metadata b/vapi/packages/clutter-1.0/clutter-1.0.metadata index b3df426058..82d460e789 100644 --- a/vapi/packages/clutter-1.0/clutter-1.0.metadata +++ b/vapi/packages/clutter-1.0/clutter-1.0.metadata @@ -369,6 +369,9 @@ clutter_text_get_single_line_mode hidden="1" clutter_text_get_text hidden="1" clutter_text_get_use_markup hidden="1" clutter_text_new_with_text.font_name nullable="1" +clutter_text_position_to_coords.x is_out="1" nullable="1" transfer_ownership="1" default_value="null" +clutter_text_position_to_coords.y is_out="1" nullable="1" transfer_ownership="1" default_value="null" +clutter_text_position_to_coords.line_height is_out="1" transfer_ownership="1" nullable="1" default_value="null" clutter_text_set_activatable hidden="1" clutter_text_set_color hidden="1" clutter_text_set_cursor_color hidden="1"
fc8ae4d30dee9b255f7caa7da76a9793b1cc6c25
elasticsearch
[TEST] Added test that verifies data integrity- during and after a simulated network split.--
p
https://github.com/elastic/elasticsearch
diff --git a/src/test/java/org/elasticsearch/discovery/DiscoveryWithNetworkFailuresTests.java b/src/test/java/org/elasticsearch/discovery/DiscoveryWithNetworkFailuresTests.java index 1a2c01ccbbbc8..7c0824cc605ba 100644 --- a/src/test/java/org/elasticsearch/discovery/DiscoveryWithNetworkFailuresTests.java +++ b/src/test/java/org/elasticsearch/discovery/DiscoveryWithNetworkFailuresTests.java @@ -21,13 +21,25 @@ import com.google.common.base.Predicate; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; +import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus; +import org.elasticsearch.action.get.GetResponse; +import org.elasticsearch.action.index.IndexRequestBuilder; +import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.ClusterState; +import org.elasticsearch.cluster.block.ClusterBlock; +import org.elasticsearch.cluster.block.ClusterBlockException; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodes; +import org.elasticsearch.cluster.routing.allocation.decider.ShardsLimitAllocationDecider; import org.elasticsearch.common.Priority; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.unit.TimeValue; +import org.elasticsearch.rest.RestStatus; +import org.elasticsearch.search.SearchHit; +import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.elasticsearch.test.junit.annotations.TestLogging; import org.elasticsearch.test.transport.MockTransportService; @@ -40,26 +52,46 @@ import static org.elasticsearch.test.ElasticsearchIntegrationTest.ClusterScope; import static org.elasticsearch.test.ElasticsearchIntegrationTest.Scope; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; +import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*; +import static org.hamcrest.Matchers.*; /** */ @ClusterScope(scope= Scope.TEST, numDataNodes =0) public class DiscoveryWithNetworkFailuresTests extends ElasticsearchIntegrationTest { + private static final Settings nodeSettings = ImmutableSettings.settingsBuilder() + .put("discovery.type", "zen") // <-- To override the local setting if set externally + .put("discovery.zen.fd.ping_timeout", "1s") // <-- for hitting simulated network failures quickly + .put("discovery.zen.fd.ping_retries", "1") // <-- for hitting simulated network failures quickly + .put("discovery.zen.minimum_master_nodes", 2) + .put(TransportModule.TRANSPORT_SERVICE_TYPE_KEY, MockTransportService.class.getName()) + .build(); + + @Override + protected int numberOfShards() { + return 3; + } + + @Override + protected int numberOfReplicas() { + return 1; + } + + @Override + public Settings indexSettings() { + Settings settings = super.indexSettings(); + return ImmutableSettings.builder() + .put(settings) + .put(ShardsLimitAllocationDecider.INDEX_TOTAL_SHARDS_PER_NODE, 2) + .build(); + } + @Test @TestLogging("discovery.zen:TRACE") public void failWithMinimumMasterNodesConfigured() throws Exception { - final Settings settings = ImmutableSettings.settingsBuilder() - .put("discovery.type", "zen") // <-- To override the local setting if set externally - .put("discovery.zen.fd.ping_timeout", "1s") // <-- for hitting simulated network failures quickly - .put("discovery.zen.fd.ping_retries", "1") // <-- for hitting simulated network failures quickly - .put("discovery.zen.minimum_master_nodes", 2) - .put(TransportModule.TRANSPORT_SERVICE_TYPE_KEY, MockTransportService.class.getName()) - .build(); - List<String> nodes = internalCluster().startNodesAsync(3, settings).get(); + List<String> nodes = internalCluster().startNodesAsync(3, nodeSettings).get(); // Wait until a green status has been reaches and 3 nodes are part of the cluster ClusterHealthResponse clusterHealthResponse = client().admin().cluster().prepareHealth() @@ -145,6 +177,185 @@ public boolean apply(Object input) { } } + @Test + @TestLogging("discovery.zen:TRACE,action:TRACE,cluster.service:TRACE") + public void testDataConsistency() throws Exception { + List<String> nodes = internalCluster().startNodesAsync(3, nodeSettings).get(); + + // Wait until a green status has been reaches and 3 nodes are part of the cluster + ClusterHealthResponse clusterHealthResponse = client().admin().cluster().prepareHealth() + .setWaitForEvents(Priority.LANGUID) + .setWaitForNodes("3") + .get(); + assertThat(clusterHealthResponse.isTimedOut(), is(false)); + + assertAcked(prepareCreate("test") + .addMapping("type", "field", "type=long") + .get()); + + IndexRequestBuilder[] indexRequests = new IndexRequestBuilder[1 + randomInt(1000)]; + for (int i = 0; i < indexRequests.length; i++) { + indexRequests[i] = client().prepareIndex("test", "type", String.valueOf(i)).setSource("field", i); + } + indexRandom(true, indexRequests); + + + for (int i = 0; i < indexRequests.length; i++) { + GetResponse getResponse = client().prepareGet("test", "type", String.valueOf(i)).get(); + assertThat(getResponse.isExists(), is(true)); + assertThat(getResponse.getVersion(), equalTo(1l)); + assertThat(getResponse.getId(), equalTo(String.valueOf(i))); + } + SearchResponse searchResponse = client().prepareSearch("test").setTypes("type") + .addSort("field", SortOrder.ASC) + .get(); + assertHitCount(searchResponse, indexRequests.length); + for (int i = 0; i < searchResponse.getHits().getHits().length; i++) { + SearchHit searchHit = searchResponse.getHits().getAt(i); + assertThat(searchHit.id(), equalTo(String.valueOf(i))); + assertThat((long) searchHit.sortValues()[0], equalTo((long) i)); + } + + // Figure out what is the elected master node + DiscoveryNode masterDiscoNode = null; + for (String node : nodes) { + ClusterState state = internalCluster().client(node).admin().cluster().prepareState().setLocal(true).execute().actionGet().getState(); + assertThat(state.nodes().size(), equalTo(3)); + if (masterDiscoNode == null) { + masterDiscoNode = state.nodes().masterNode(); + } else { + assertThat(state.nodes().masterNode(), equalTo(masterDiscoNode)); + } + } + assert masterDiscoNode != null; + logger.info("---> legit elected master node=" + masterDiscoNode); + final Client masterClient = internalCluster().masterClient(); + + // Everything is stable now, it is now time to simulate evil... + + // Pick a node that isn't the elected master. + String unluckyNode = null; + for (String node : nodes) { + if (!node.equals(masterDiscoNode.getName())) { + unluckyNode = node; + } + } + assert unluckyNode != null; + + // Simulate a network issue between the unlucky node and the rest of the cluster. + for (String nodeId : nodes) { + if (!nodeId.equals(unluckyNode)) { + addFailToSendNoConnectRule(nodeId, unluckyNode); + addFailToSendNoConnectRule(unluckyNode, nodeId); + } + } + try { + // Wait until elected master has removed that the unlucky node... + boolean applied = awaitBusy(new Predicate<Object>() { + @Override + public boolean apply(Object input) { + return masterClient.admin().cluster().prepareState().setLocal(true).get().getState().nodes().size() == 2; + } + }, 1, TimeUnit.MINUTES); + assertThat(applied, is(true)); + + // The unlucky node must report *no* master node, since it can't connect to master and in fact it should + // continuously ping until network failures have been resolved. However + final Client isolatedNodeClient = internalCluster().client(unluckyNode); + // It may a take a bit before the node detects it has been cut off from the elected master + applied = awaitBusy(new Predicate<Object>() { + @Override + public boolean apply(Object input) { + ClusterState localClusterState = isolatedNodeClient.admin().cluster().prepareState().setLocal(true).get().getState(); + DiscoveryNodes localDiscoveryNodes = localClusterState.nodes(); + logger.info("localDiscoveryNodes=" + localDiscoveryNodes.prettyPrint()); + return localDiscoveryNodes.masterNode() == null; + } + }, 10, TimeUnit.SECONDS); + assertThat(applied, is(true)); + + ClusterHealthResponse healthResponse = masterClient.admin().cluster().prepareHealth("test") + .setWaitForYellowStatus().get(); + assertThat(healthResponse.isTimedOut(), is(false)); + assertThat(healthResponse.getStatus(), equalTo(ClusterHealthStatus.YELLOW)); + + // Reads on the right side of the split must work + searchResponse = masterClient.prepareSearch("test").setTypes("type") + .addSort("field", SortOrder.ASC) + .get(); + assertHitCount(searchResponse, indexRequests.length); + for (int i = 0; i < searchResponse.getHits().getHits().length; i++) { + SearchHit searchHit = searchResponse.getHits().getAt(i); + assertThat(searchHit.id(), equalTo(String.valueOf(i))); + assertThat((long) searchHit.sortValues()[0], equalTo((long) i)); + } + + // Reads on the wrong side of the split are partial + searchResponse = isolatedNodeClient.prepareSearch("test").setTypes("type") + .addSort("field", SortOrder.ASC) + .get(); + assertThat(searchResponse.getSuccessfulShards(), lessThan(searchResponse.getTotalShards())); + assertThat(searchResponse.getHits().totalHits(), lessThan((long) indexRequests.length)); + + // Writes on the right side of the split must work + UpdateResponse updateResponse = masterClient.prepareUpdate("test", "type", "0").setDoc("field2", 2).get(); + assertThat(updateResponse.getVersion(), equalTo(2l)); + + // Writes on the wrong side of the split fail + try { + isolatedNodeClient.prepareUpdate("test", "type", "0").setDoc("field2", 2) + .setTimeout(TimeValue.timeValueSeconds(5)) // Fail quick, otherwise we wait 60 seconds. + .get(); + } catch (ClusterBlockException exception) { + assertThat(exception.status(), equalTo(RestStatus.SERVICE_UNAVAILABLE)); + assertThat(exception.blocks().size(), equalTo(1)); + ClusterBlock clusterBlock = exception.blocks().iterator().next(); + assertThat(clusterBlock.id(), equalTo(DiscoverySettings.NO_MASTER_BLOCK_ID)); + } + } finally { + // stop simulating network failures, from this point on the unlucky node is able to rejoin + // We also need to do this even if assertions fail, since otherwise the test framework can't work properly + for (String nodeId : nodes) { + if (!nodeId.equals(unluckyNode)) { + clearNoConnectRule(nodeId, unluckyNode); + clearNoConnectRule(unluckyNode, nodeId); + } + } + } + + // Wait until the master node sees all 3 nodes again. + clusterHealthResponse = masterClient.admin().cluster().prepareHealth() + .setWaitForGreenStatus() + .setWaitForEvents(Priority.LANGUID) + .setWaitForNodes("3") + .get(); + assertThat(clusterHealthResponse.isTimedOut(), is(false)); + + for (String node : nodes) { + Client client = internalCluster().client(node); + searchResponse = client.prepareSearch("test").setTypes("type") + .addSort("field", SortOrder.ASC) + .get(); + for (int i = 0; i < searchResponse.getHits().getHits().length; i++) { + SearchHit searchHit = searchResponse.getHits().getAt(i); + assertThat(searchHit.id(), equalTo(String.valueOf(i))); + assertThat((long) searchHit.sortValues()[0], equalTo((long) i)); + } + + + GetResponse getResponse = client().prepareGet("test", "type", "0").get(); + assertThat(getResponse.isExists(), is(true)); + assertThat(getResponse.getVersion(), equalTo(2l)); + assertThat(getResponse.getId(), equalTo("0")); + for (int i = 1; i < indexRequests.length; i++) { + getResponse = client().prepareGet("test", "type", String.valueOf(i)).get(); + assertThat(getResponse.isExists(), is(true)); + assertThat(getResponse.getVersion(), equalTo(1l)); + assertThat(getResponse.getId(), equalTo(String.valueOf(i))); + } + } + } + private void addFailToSendNoConnectRule(String fromNode, String toNode) { TransportService mockTransportService = internalCluster().getInstance(TransportService.class, fromNode); ((MockTransportService) mockTransportService).addFailToSendNoConnectRule(internalCluster().getInstance(Discovery.class, toNode).localNode());
33660bc78e9b8d0cef71d635bf609c6dcb6ddeea
intellij-community
Fixed typos in test.--
p
https://github.com/JetBrains/intellij-community
diff --git a/python/testSrc/com/jetbrains/python/PyPropertyTestSuite.java b/python/testSrc/com/jetbrains/python/PyPropertyTestSuite.java index 6a6512d0e4eae..9902b4b6d20f4 100644 --- a/python/testSrc/com/jetbrains/python/PyPropertyTestSuite.java +++ b/python/testSrc/com/jetbrains/python/PyPropertyTestSuite.java @@ -27,10 +27,12 @@ abstract static class PyPropertyTest extends PyResolveTestCase { protected PyClass myClass; protected LanguageLevel myLanguageLevel = LanguageLevel.PYTHON26; + abstract String getFileName(); + @Override protected void setUp() throws Exception { super.setUp(); - PsiReference ref = configureByFile("property/"+ "Classic.py"); + PsiReference ref = configureByFile("property/"+ getFileName()); final Project project = ref.getElement().getContainingFile().getProject(); project.putUserData(PyBuiltinCache.TEST_SDK, PythonMockSdk.findOrCreate()); PythonLanguageLevelPusher.setForcedLanguageLevel(project, myLanguageLevel); @@ -49,6 +51,11 @@ public PyClassicPropertyTest() { super(); } + @Override + String getFileName() { + return "Classic.py"; + } + public void testV1() throws Exception { Property p; Maybe<PyFunction> accessor; @@ -148,13 +155,23 @@ public void testV4() throws Exception { public static class PyDecoratedPropertyTest extends PyPropertyTest { public PyDecoratedPropertyTest() { super(); + } + + @Override + String getFileName() { + return "Decorated.py"; + } + + @Override + protected void setUp() throws Exception { + super.setUp(); myLanguageLevel = LanguageLevel.PYTHON26; } public void testW1() throws Exception { Property p; Maybe<PyFunction> accessor; - p = myClass.findProperty("W1"); + p = myClass.findProperty("w1"); assertNotNull(p); assertNull(p.getDoc()); assertNull(p.getDefinitionSite()); @@ -178,7 +195,7 @@ public void testW1() throws Exception { public void testW2() throws Exception { Property p; Maybe<PyFunction> accessor; - p = myClass.findProperty("W2"); + p = myClass.findProperty("w2"); assertNotNull(p); assertNull(p.getDoc()); assertNull(p.getDefinitionSite());
990ddf5896045704ec43ac0e5a3e2df7022fed12
drools
JBRULES-1641: ForEach node - initial core- implementation of a for each node JBRULES-1551: Workflow human tasks - human- task node with swimlane integration--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@20429 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
a
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/main/java/org/drools/xml/ProcessSemanticModule.java b/drools-compiler/src/main/java/org/drools/xml/ProcessSemanticModule.java index f9d4407309d..4969dd5a685 100644 --- a/drools-compiler/src/main/java/org/drools/xml/ProcessSemanticModule.java +++ b/drools-compiler/src/main/java/org/drools/xml/ProcessSemanticModule.java @@ -6,6 +6,7 @@ import org.drools.xml.processes.ConstraintHandler; import org.drools.xml.processes.EndNodeHandler; import org.drools.xml.processes.GlobalHandler; +import org.drools.xml.processes.HumanTaskNodeHandler; import org.drools.xml.processes.ImportHandler; import org.drools.xml.processes.InPortHandler; import org.drools.xml.processes.JoinNodeHandler; @@ -18,6 +19,7 @@ import org.drools.xml.processes.SplitNodeHandler; import org.drools.xml.processes.StartNodeHandler; import org.drools.xml.processes.SubProcessNodeHandler; +import org.drools.xml.processes.SwimlaneHandler; import org.drools.xml.processes.TimerNodeHandler; import org.drools.xml.processes.TypeHandler; import org.drools.xml.processes.ValueHandler; @@ -51,6 +53,8 @@ public ProcessSemanticModule() { new MilestoneNodeHandler() ); addHandler( "timer", new TimerNodeHandler() ); + addHandler( "humanTask", + new HumanTaskNodeHandler() ); addHandler( "composite", new CompositeNodeHandler() ); addHandler( "connection", @@ -61,6 +65,8 @@ public ProcessSemanticModule() { new GlobalHandler() ); addHandler( "variable", new VariableHandler() ); + addHandler( "swimlane", + new SwimlaneHandler() ); addHandler( "type", new TypeHandler() ); addHandler( "value", diff --git a/drools-compiler/src/main/java/org/drools/xml/XmlWorkflowProcessDumper.java b/drools-compiler/src/main/java/org/drools/xml/XmlWorkflowProcessDumper.java index 12bccde50e9..bd4272c12b6 100644 --- a/drools-compiler/src/main/java/org/drools/xml/XmlWorkflowProcessDumper.java +++ b/drools-compiler/src/main/java/org/drools/xml/XmlWorkflowProcessDumper.java @@ -1,9 +1,12 @@ package org.drools.xml; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.Map; +import org.drools.process.core.context.swimlane.Swimlane; +import org.drools.process.core.context.swimlane.SwimlaneContext; import org.drools.process.core.context.variable.Variable; import org.drools.process.core.context.variable.VariableScope; import org.drools.process.core.datatype.DataType; @@ -78,6 +81,10 @@ private void visitHeader(WorkflowProcess process, StringBuffer xmlDump, boolean if (variableScope != null) { visitVariables(variableScope.getVariables(), xmlDump); } + SwimlaneContext swimlaneContext = (SwimlaneContext) process.getDefaultContext(SwimlaneContext.SWIMLANE_SCOPE); + if (swimlaneContext != null) { + visitSwimlanes(swimlaneContext.getSwimlanes(), xmlDump); + } xmlDump.append(" </header>" + EOL + EOL); } @@ -117,6 +124,16 @@ private void visitVariables(List<Variable> variables, StringBuffer xmlDump) { } } + private void visitSwimlanes(Collection<Swimlane> swimlanes, StringBuffer xmlDump) { + if (swimlanes != null && swimlanes.size() > 0) { + xmlDump.append(" <swimlanes>" + EOL); + for (Swimlane swimlane: swimlanes) { + xmlDump.append(" <swimlane name=\"" + swimlane.getName() + "\" />" + EOL); + } + xmlDump.append(" </swimlanes>" + EOL); + } + } + private void visitDataType(DataType dataType, StringBuffer xmlDump) { xmlDump.append(" <type name=\"" + dataType.getClass().getName() + "\" />" + EOL); } diff --git a/drools-compiler/src/main/java/org/drools/xml/processes/HumanTaskNodeHandler.java b/drools-compiler/src/main/java/org/drools/xml/processes/HumanTaskNodeHandler.java new file mode 100644 index 00000000000..0f0cd843707 --- /dev/null +++ b/drools-compiler/src/main/java/org/drools/xml/processes/HumanTaskNodeHandler.java @@ -0,0 +1,53 @@ +package org.drools.xml.processes; + +import org.drools.process.core.Work; +import org.drools.workflow.core.Node; +import org.drools.workflow.core.node.HumanTaskNode; +import org.drools.workflow.core.node.WorkItemNode; +import org.drools.xml.ExtensibleXmlParser; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +public class HumanTaskNodeHandler extends WorkItemNodeHandler { + + public void handleNode(final Node node, final Element element, final String uri, + final String localName, final ExtensibleXmlParser parser) + throws SAXException { + super.handleNode(node, element, uri, localName, parser); + HumanTaskNode humanTaskNode = (HumanTaskNode) node; + final String swimlane = element.getAttribute("swimlane"); + if (swimlane != null && !"".equals(swimlane)) { + humanTaskNode.setSwimlane(swimlane); + } + } + + protected Node createNode() { + return new HumanTaskNode(); + } + + public Class generateNodeFor() { + return HumanTaskNode.class; + } + + public void writeNode(Node node, StringBuffer xmlDump, boolean includeMeta) { + WorkItemNode workItemNode = (WorkItemNode) node; + writeNode("humanTask", workItemNode, xmlDump, includeMeta); + visitParameters(workItemNode, xmlDump); + xmlDump.append(">" + EOL); + Work work = workItemNode.getWork(); + visitWork(work, xmlDump, includeMeta); + visitInMappings(workItemNode.getInMappings(), xmlDump); + visitOutMappings(workItemNode.getOutMappings(), xmlDump); + endNode("humanTask", xmlDump); + } + + protected void visitParameters(WorkItemNode workItemNode, StringBuffer xmlDump) { + super.visitParameters(workItemNode, xmlDump); + HumanTaskNode humanTaskNode = (HumanTaskNode) workItemNode; + String swimlane = humanTaskNode.getSwimlane(); + if (swimlane != null) { + xmlDump.append("swimlane=\"" + swimlane + "\" "); + } + } + +} diff --git a/drools-compiler/src/main/java/org/drools/xml/processes/SwimlaneHandler.java b/drools-compiler/src/main/java/org/drools/xml/processes/SwimlaneHandler.java new file mode 100644 index 00000000000..9ad5da8d546 --- /dev/null +++ b/drools-compiler/src/main/java/org/drools/xml/processes/SwimlaneHandler.java @@ -0,0 +1,67 @@ +package org.drools.xml.processes; + +import java.util.HashSet; + +import org.drools.process.core.Process; +import org.drools.process.core.context.swimlane.Swimlane; +import org.drools.process.core.context.swimlane.SwimlaneContext; +import org.drools.workflow.core.impl.WorkflowProcessImpl; +import org.drools.xml.BaseAbstractHandler; +import org.drools.xml.ExtensibleXmlParser; +import org.drools.xml.Handler; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +public class SwimlaneHandler extends BaseAbstractHandler + implements + Handler { + public SwimlaneHandler() { + if ( (this.validParents == null) && (this.validPeers == null) ) { + this.validParents = new HashSet(); + this.validParents.add( Process.class ); + + this.validPeers = new HashSet(); + this.validPeers.add( null ); + + this.allowNesting = false; + } + } + + + + public Object start(final String uri, + final String localName, + final Attributes attrs, + final ExtensibleXmlParser parser) throws SAXException { + parser.startElementBuilder( localName, + attrs ); + WorkflowProcessImpl process = (WorkflowProcessImpl) parser.getParent(); + final String name = attrs.getValue("name"); + emptyAttributeCheck(localName, "name", name, parser); + + SwimlaneContext swimlaneContext = (SwimlaneContext) + process.getDefaultContext(SwimlaneContext.SWIMLANE_SCOPE); + if (swimlaneContext != null) { + Swimlane swimlane = new Swimlane(name); + swimlaneContext.addSwimlane(swimlane); + } else { + throw new SAXParseException( + "Could not find default swimlane context.", parser.getLocator()); + } + + return null; + } + + public Object end(final String uri, + final String localName, + final ExtensibleXmlParser parser) throws SAXException { + parser.endElementBuilder(); + return null; + } + + public Class generateNodeFor() { + return Swimlane.class; + } + +} diff --git a/drools-compiler/src/main/java/org/drools/xml/processes/WorkItemNodeHandler.java b/drools-compiler/src/main/java/org/drools/xml/processes/WorkItemNodeHandler.java index 91ad673494c..f4628f3df5a 100644 --- a/drools-compiler/src/main/java/org/drools/xml/processes/WorkItemNodeHandler.java +++ b/drools-compiler/src/main/java/org/drools/xml/processes/WorkItemNodeHandler.java @@ -32,48 +32,58 @@ public Class generateNodeFor() { public void writeNode(Node node, StringBuffer xmlDump, boolean includeMeta) { WorkItemNode workItemNode = (WorkItemNode) node; writeNode("workItem", workItemNode, xmlDump, includeMeta); - if (!workItemNode.isWaitForCompletion()) { - xmlDump.append("waitForCompletion=\"false\" "); - } + visitParameters(workItemNode, xmlDump); xmlDump.append(">" + EOL); Work work = workItemNode.getWork(); - if (work != null) { - visitWork(work, xmlDump, includeMeta); + visitWork(work, xmlDump, includeMeta); + visitInMappings(workItemNode.getInMappings(), xmlDump); + visitOutMappings(workItemNode.getOutMappings(), xmlDump); + endNode("workItem", xmlDump); + } + + protected void visitParameters(WorkItemNode workItemNode, StringBuffer xmlDump) { + if (!workItemNode.isWaitForCompletion()) { + xmlDump.append("waitForCompletion=\"false\" "); } - Map<String, String> inMappings = workItemNode.getInMappings(); + } + + protected void visitInMappings(Map<String, String> inMappings, StringBuffer xmlDump) { for (Map.Entry<String, String> inMapping: inMappings.entrySet()) { xmlDump.append( " <mapping type=\"in\" " + "from=\"" + inMapping.getValue() + "\" " + "to=\"" + inMapping.getKey() + "\" />" + EOL); } - Map<String, String> outMappings = workItemNode.getOutMappings(); + } + + protected void visitOutMappings(Map<String, String> outMappings, StringBuffer xmlDump) { for (Map.Entry<String, String> outMapping: outMappings.entrySet()) { xmlDump.append( " <mapping type=\"out\" " + "from=\"" + outMapping.getKey() + "\" " + "to=\"" + outMapping.getValue() + "\" />" + EOL); } - endNode("workItem", xmlDump); } - private void visitWork(Work work, StringBuffer xmlDump, boolean includeMeta) { - xmlDump.append(" <work name=\"" + work.getName() + "\" >" + EOL); - for (ParameterDefinition paramDefinition: work.getParameterDefinitions()) { - if (paramDefinition == null) { - throw new IllegalArgumentException( - "Could not find parameter definition " + paramDefinition.getName() - + " for work " + work.getName()); - } - xmlDump.append(" <parameter name=\"" + paramDefinition.getName() + "\" " + - "type=\"" + paramDefinition.getType().getClass().getName() + "\" "); - Object value = work.getParameter(paramDefinition.getName()); - if (value == null) { - xmlDump.append("/>" + EOL); - } else { - xmlDump.append(">" + value + "</parameter>" + EOL); + protected void visitWork(Work work, StringBuffer xmlDump, boolean includeMeta) { + if (work != null) { + xmlDump.append(" <work name=\"" + work.getName() + "\" >" + EOL); + for (ParameterDefinition paramDefinition: work.getParameterDefinitions()) { + if (paramDefinition == null) { + throw new IllegalArgumentException( + "Could not find parameter definition " + paramDefinition.getName() + + " for work " + work.getName()); + } + xmlDump.append(" <parameter name=\"" + paramDefinition.getName() + "\" " + + "type=\"" + paramDefinition.getType().getClass().getName() + "\" "); + Object value = work.getParameter(paramDefinition.getName()); + if (value == null) { + xmlDump.append("/>" + EOL); + } else { + xmlDump.append(">" + value + "</parameter>" + EOL); + } } + xmlDump.append(" </work>" + EOL); } - xmlDump.append(" </work>" + EOL); } } diff --git a/drools-compiler/src/main/resources/META-INF/drools-processes-4.0.xsd b/drools-compiler/src/main/resources/META-INF/drools-processes-4.0.xsd index 65a1fd188ce..a8fab793d0e 100644 --- a/drools-compiler/src/main/resources/META-INF/drools-processes-4.0.xsd +++ b/drools-compiler/src/main/resources/META-INF/drools-processes-4.0.xsd @@ -21,6 +21,7 @@ <xs:element ref="drools:imports"/> <xs:element ref="drools:globals"/> <xs:element ref="drools:variables"/> + <xs:element ref="drools:swimlanes"/> </xs:choice> </xs:complexType> </xs:element> @@ -77,6 +78,18 @@ </xs:simpleContent> </xs:complexType> </xs:element> + <xs:element name="swimlanes"> + <xs:complexType> + <xs:sequence minOccurs="0" maxOccurs="unbounded"> + <xs:element ref="drools:swimlane"/> + </xs:sequence> + </xs:complexType> + </xs:element> + <xs:element name="swimlane"> + <xs:complexType> + <xs:attribute name="name" type="xs:string" use="required"/> + </xs:complexType> + </xs:element> <xs:element name="nodes"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> @@ -90,6 +103,7 @@ <xs:element ref="drools:subProcess"/> <xs:element ref="drools:workItem"/> <xs:element ref="drools:timer"/> + <xs:element ref="drools:humanTask"/> <xs:element ref="drools:composite"/> </xs:choice> </xs:complexType> @@ -268,6 +282,22 @@ <xs:attribute name="period" type="xs:string"/> </xs:complexType> </xs:element> + <xs:element name="humanTask"> + <xs:complexType> + <xs:choice minOccurs="0" maxOccurs="unbounded"> + <xs:element ref="drools:work"/> + <xs:element ref="drools:mapping"/> + </xs:choice> + <xs:attribute name="id" type="xs:string" use="required"/> + <xs:attribute name="name" type="xs:string"/> + <xs:attribute name="x" type="xs:string"/> + <xs:attribute name="y" type="xs:string"/> + <xs:attribute name="width" type="xs:string"/> + <xs:attribute name="height" type="xs:string"/> + <xs:attribute name="waitForCompletion" type="xs:string"/> + <xs:attribute name="swimlane" type="xs:string"/> + </xs:complexType> + </xs:element> <xs:element name="composite"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/ProcessHumanTaskTest.java b/drools-compiler/src/test/java/org/drools/integrationtests/ProcessHumanTaskTest.java new file mode 100644 index 00000000000..3cd48fbd66b --- /dev/null +++ b/drools-compiler/src/test/java/org/drools/integrationtests/ProcessHumanTaskTest.java @@ -0,0 +1,150 @@ +package org.drools.integrationtests; + +import java.io.Reader; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.drools.RuleBase; +import org.drools.RuleBaseFactory; +import org.drools.WorkingMemory; +import org.drools.compiler.PackageBuilder; +import org.drools.process.instance.ProcessInstance; +import org.drools.process.instance.WorkItem; +import org.drools.process.instance.WorkItemHandler; +import org.drools.process.instance.WorkItemManager; +import org.drools.rule.Package; + +import junit.framework.TestCase; + +public class ProcessHumanTaskTest extends TestCase { + + public void testHumanTask() { + PackageBuilder builder = new PackageBuilder(); + Reader source = new StringReader( + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + + "<process xmlns=\"http://drools.org/drools-4.0/process\"\n" + + " xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + + " xs:schemaLocation=\"http://drools.org/drools-4.0/process drools-processes-4.0.xsd\"\n" + + " type=\"RuleFlow\" name=\"flow\" id=\"org.drools.humantask\" package-name=\"org.drools\" version=\"1\" >\n" + + "\n" + + " <header>\n" + + " </header>\n" + + "\n" + + " <nodes>\n" + + " <start id=\"1\" name=\"Start\" />\n" + + " <humanTask id=\"2\" name=\"HumanTask\" >\n" + + " <work name=\"Human Task\" >\n" + + " <parameter name=\"ActorId\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" >John Doe</parameter>\n" + + " <parameter name=\"TaskName\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" >Do something</parameter>\n" + + " <parameter name=\"Priority\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n" + + " <parameter name=\"Comment\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n" + + " </work>\n" + + " </humanTask>\n" + + " <end id=\"3\" name=\"End\" />\n" + + " </nodes>\n" + + "\n" + + " <connections>\n" + + " <connection from=\"1\" to=\"2\" />\n" + + " <connection from=\"2\" to=\"3\" />\n" + + " </connections>\n" + + "\n" + + "</process>"); + builder.addRuleFlow(source); + Package pkg = builder.getPackage(); + RuleBase ruleBase = RuleBaseFactory.newRuleBase(); + ruleBase.addPackage( pkg ); + WorkingMemory workingMemory = ruleBase.newStatefulSession(); + TestWorkItemHandler handler = new TestWorkItemHandler(); + workingMemory.getWorkItemManager().registerWorkItemHandler("Human Task", handler); + ProcessInstance processInstance = + workingMemory.startProcess("org.drools.humantask"); + assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState()); + WorkItem workItem = handler.getWorkItem(); + assertNotNull(workItem); + workingMemory.getWorkItemManager().completeWorkItem(workItem.getId(), null); + assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState()); + } + + public void testSwimlane() { + PackageBuilder builder = new PackageBuilder(); + Reader source = new StringReader( + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + + "<process xmlns=\"http://drools.org/drools-4.0/process\"\n" + + " xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + + " xs:schemaLocation=\"http://drools.org/drools-4.0/process drools-processes-4.0.xsd\"\n" + + " type=\"RuleFlow\" name=\"flow\" id=\"org.drools.humantask\" package-name=\"org.drools\" version=\"1\" >\n" + + "\n" + + " <header>\n" + + " <swimlanes>\n" + + " <swimlane name=\"actor1\" />\n" + + " </swimlanes>\n" + + " </header>\n" + + "\n" + + " <nodes>\n" + + " <start id=\"1\" name=\"Start\" />\n" + + " <humanTask id=\"2\" name=\"HumanTask\" swimlane=\"actor1\" >\n" + + " <work name=\"Human Task\" >\n" + + " <parameter name=\"ActorId\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" >John Doe</parameter>\n" + + " <parameter name=\"TaskName\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" >Do something</parameter>\n" + + " <parameter name=\"Priority\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n" + + " <parameter name=\"Comment\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n" + + " </work>\n" + + " </humanTask>\n" + + " <humanTask id=\"3\" name=\"HumanTask\" swimlane=\"actor1\" >\n" + + " <work name=\"Human Task\" >\n" + + " <parameter name=\"ActorId\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n" + + " <parameter name=\"TaskName\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" >Do something else</parameter>\n" + + " <parameter name=\"Priority\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n" + + " <parameter name=\"Comment\" type=\"org.drools.process.core.datatype.impl.type.StringDataType\" />\n" + + " </work>\n" + + " </humanTask>\n" + + " <end id=\"4\" name=\"End\" />\n" + + " </nodes>\n" + + "\n" + + " <connections>\n" + + " <connection from=\"1\" to=\"2\" />\n" + + " <connection from=\"2\" to=\"3\" />\n" + + " <connection from=\"3\" to=\"4\" />\n" + + " </connections>\n" + + "\n" + + "</process>"); + builder.addRuleFlow(source); + Package pkg = builder.getPackage(); + RuleBase ruleBase = RuleBaseFactory.newRuleBase(); + ruleBase.addPackage( pkg ); + WorkingMemory workingMemory = ruleBase.newStatefulSession(); + TestWorkItemHandler handler = new TestWorkItemHandler(); + workingMemory.getWorkItemManager().registerWorkItemHandler("Human Task", handler); + ProcessInstance processInstance = + workingMemory.startProcess("org.drools.humantask"); + assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState()); + WorkItem workItem = handler.getWorkItem(); + assertNotNull(workItem); + assertEquals("Do something", workItem.getParameter("TaskName")); + assertEquals("John Doe", workItem.getParameter("ActorId")); + Map<String, Object> results = new HashMap<String, Object>(); + results.put("ActorId", "Jane Doe"); + workingMemory.getWorkItemManager().completeWorkItem(workItem.getId(), results); + workItem = handler.getWorkItem(); + assertNotNull(workItem); + assertEquals("Do something else", workItem.getParameter("TaskName")); + assertEquals("Jane Doe", workItem.getParameter("ActorId")); + workingMemory.getWorkItemManager().completeWorkItem(workItem.getId(), null); + assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState()); + } + + private static class TestWorkItemHandler implements WorkItemHandler { + private WorkItem workItem; + public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { + this.workItem = workItem; + } + public void abortWorkItem(WorkItem workItem, WorkItemManager manager) { + } + public WorkItem getWorkItem() { + return workItem; + } + } +} diff --git a/drools-compiler/src/test/java/org/drools/xml/processes/XMLPersistenceTest.java b/drools-compiler/src/test/java/org/drools/xml/processes/XMLPersistenceTest.java index 63dc64f742b..c1e4e01c26a 100644 --- a/drools-compiler/src/test/java/org/drools/xml/processes/XMLPersistenceTest.java +++ b/drools-compiler/src/test/java/org/drools/xml/processes/XMLPersistenceTest.java @@ -13,6 +13,7 @@ import org.drools.compiler.PackageBuilderConfiguration; import org.drools.process.core.ParameterDefinition; import org.drools.process.core.Work; +import org.drools.process.core.context.swimlane.Swimlane; import org.drools.process.core.context.variable.Variable; import org.drools.process.core.datatype.impl.type.IntegerDataType; import org.drools.process.core.datatype.impl.type.StringDataType; @@ -28,6 +29,7 @@ import org.drools.workflow.core.impl.DroolsConsequenceAction; import org.drools.workflow.core.node.ActionNode; import org.drools.workflow.core.node.EndNode; +import org.drools.workflow.core.node.HumanTaskNode; import org.drools.workflow.core.node.Join; import org.drools.workflow.core.node.MilestoneNode; import org.drools.workflow.core.node.RuleSetNode; @@ -60,6 +62,7 @@ public void addNode(Node node) { process.addNode(new SubProcessNode()); process.addNode(new WorkItemNode()); process.addNode(new TimerNode()); + process.addNode(new HumanTaskNode()); String xml = XmlRuleFlowProcessDumper.INSTANCE.dump(process, false); if (xml == null) { @@ -76,7 +79,7 @@ public void addNode(Node node) { throw new IllegalArgumentException("Failed to reload process!"); } - assertEquals(10, process.getNodes().length); + assertEquals(11, process.getNodes().length); // System.out.println("************************************"); @@ -124,6 +127,9 @@ public void addNode(Node node) { variables.add(variable); process.getVariableScope().setVariables(variables); + process.getSwimlaneContext().addSwimlane(new Swimlane("actor1")); + process.getSwimlaneContext().addSwimlane(new Swimlane("actor2")); + StartNode startNode = new StartNode(); startNode.setName("start"); startNode.setMetaData("x", 1); @@ -187,7 +193,6 @@ public void addNode(Node node) { process.addNode(join); new ConnectionImpl(actionNode, Node.CONNECTION_DEFAULT_TYPE, join, Node.CONNECTION_DEFAULT_TYPE); new ConnectionImpl(ruleSetNode, Node.CONNECTION_DEFAULT_TYPE, join, Node.CONNECTION_DEFAULT_TYPE); - MilestoneNode milestone = new MilestoneNode(); milestone.setName("milestone"); @@ -234,6 +239,24 @@ public void addNode(Node node) { connection = new ConnectionImpl(subProcess, Node.CONNECTION_DEFAULT_TYPE, workItemNode, Node.CONNECTION_DEFAULT_TYPE); connection.setMetaData("bendpoints", "[]"); + HumanTaskNode humanTaskNode = new HumanTaskNode(); + work = humanTaskNode.getWork(); + parameterDefinitions = new HashSet<ParameterDefinition>(); + parameterDefinition = new ParameterDefinitionImpl("TaskName", new StringDataType()); + parameterDefinitions.add(parameterDefinition); + parameterDefinition = new ParameterDefinitionImpl("ActorId", new StringDataType()); + parameterDefinitions.add(parameterDefinition); + parameterDefinition = new ParameterDefinitionImpl("Priority", new StringDataType()); + parameterDefinitions.add(parameterDefinition); + parameterDefinition = new ParameterDefinitionImpl("Comment", new StringDataType()); + parameterDefinitions.add(parameterDefinition); + work.setParameterDefinitions(parameterDefinitions); + work.setParameter("TaskName", "Do something"); + work.setParameter("ActorId", "John Doe"); + workItemNode.setWaitForCompletion(false); + process.addNode(humanTaskNode); + connection = new ConnectionImpl(workItemNode, Node.CONNECTION_DEFAULT_TYPE, humanTaskNode, Node.CONNECTION_DEFAULT_TYPE); + TimerNode timerNode = new TimerNode(); timerNode.setName("timer"); timerNode.setMetaData("x", 1); @@ -245,7 +268,7 @@ public void addNode(Node node) { timer.setPeriod(1000); timerNode.setTimer(timer); process.addNode(timerNode); - new ConnectionImpl(workItemNode, Node.CONNECTION_DEFAULT_TYPE, timerNode, Node.CONNECTION_DEFAULT_TYPE); + new ConnectionImpl(humanTaskNode, Node.CONNECTION_DEFAULT_TYPE, timerNode, Node.CONNECTION_DEFAULT_TYPE); EndNode endNode = new EndNode(); endNode.setName("end"); @@ -270,7 +293,7 @@ public void addNode(Node node) { throw new IllegalArgumentException("Failed to reload process!"); } - assertEquals(10, process.getNodes().length); + assertEquals(11, process.getNodes().length); // System.out.println("************************************");
fbee40cdf5483c5747e80f6661aeeda15d1725d4
Vala
Support [CCode (free_function_address_of = true)] attribute Fixes bug 589795.
a
https://github.com/GNOME/vala/
diff --git a/codegen/valaccodebasemodule.vala b/codegen/valaccodebasemodule.vala index 756275e919..2f7dc9428f 100644 --- a/codegen/valaccodebasemodule.vala +++ b/codegen/valaccodebasemodule.vala @@ -1961,6 +1961,38 @@ internal class Vala.CCodeBaseModule : CCodeModule { return dup_func; } + protected string generate_destroy_func_wrapper (DataType type) { + string destroy_func = "_vala_%s_free".printf (type.data_type.get_cname ()); + + if (!add_wrapper (destroy_func)) { + // wrapper already defined + return destroy_func; + } + + // declaration + + var function = new CCodeFunction (destroy_func, "void"); + function.add_parameter (new CCodeFormalParameter ("self", type.get_cname ())); + + // definition + + var block = new CCodeBlock (); + + var free_call = new CCodeFunctionCall (new CCodeIdentifier (type.data_type.get_free_function ())); + free_call.add_argument (new CCodeUnaryExpression (CCodeUnaryOperator.ADDRESS_OF, new CCodeIdentifier ("self"))); + + block.add_statement (new CCodeExpressionStatement (free_call)); + + // append to file + + source_declarations.add_type_member_declaration (function.copy ()); + + function.block = block; + source_type_member_definition.append (function); + + return destroy_func; + } + public CCodeExpression? get_destroy_func_expression (DataType type) { if (context.profile == Profile.GOBJECT && (type.data_type == glist_type || type.data_type == gslist_type)) { // create wrapper function to free list elements if necessary @@ -1992,7 +2024,12 @@ internal class Vala.CCodeBaseModule : CCodeModule { return null; } } else { - unref_function = type.data_type.get_free_function (); + var cl = type.data_type as Class; + if (cl != null && cl.free_function_address_of) { + unref_function = generate_destroy_func_wrapper (type); + } else { + unref_function = type.data_type.get_free_function (); + } } } else { if (type.nullable) { diff --git a/vala/valaclass.vala b/vala/valaclass.vala index 0549131117..ad76ded983 100644 --- a/vala/valaclass.vala +++ b/vala/valaclass.vala @@ -103,6 +103,12 @@ public class Vala.Class : ObjectTypeSymbol { */ public bool has_class_private_fields { get; private set; } + /** + * Specifies whether the free function requires the address of a + * pointer instead of just the pointer. + */ + public bool free_function_address_of { get; private set; } + private string cname; private string const_cname; private string lower_case_cprefix; @@ -627,6 +633,9 @@ public class Vala.Class : ObjectTypeSymbol { if (a.has_argument ("free_function")) { set_free_function (a.get_string ("free_function")); } + if (a.has_argument ("free_function_address_of")) { + free_function_address_of = a.get_bool ("free_function_address_of"); + } if (a.has_argument ("type_id")) { type_id = a.get_string ("type_id"); }
36de13782eb7da2427b048bbead58e75acdfe256
Vala
atk: make Atk.State inherit from uint64 Fixes bug 613949.
c
https://github.com/GNOME/vala/
diff --git a/vapi/atk.vapi b/vapi/atk.vapi index ea6e91d215..6114340f60 100644 --- a/vapi/atk.vapi +++ b/vapi/atk.vapi @@ -186,13 +186,6 @@ namespace Atk { public unowned Atk.Relation get_relation_by_type (Atk.RelationType relationship); public void remove (Atk.Relation relation); } - [Compact] - [CCode (cheader_filename = "atk/atk.h")] - public class State { - public static Atk.StateType type_for_name (string name); - public static unowned string type_get_name (Atk.StateType type); - public static Atk.StateType type_register (string name); - } [CCode (cheader_filename = "atk/atk.h")] public class StateSet : GLib.Object { [CCode (has_construct_function = false)] @@ -425,6 +418,14 @@ namespace Atk { public int width; public int height; } + [CCode (cheader_filename = "atk/atk.h")] + [SimpleType] + [IntegerType (rank = 11)] + public struct State : uint64 { + public static Atk.StateType type_for_name (string name); + public static unowned string type_get_name (Atk.StateType type); + public static Atk.StateType type_register (string name); + } [CCode (cprefix = "ATK_XY_", cheader_filename = "atk/atk.h")] public enum CoordType { SCREEN, diff --git a/vapi/packages/atk/atk.metadata b/vapi/packages/atk/atk.metadata index b0c2f95764..a0087b6ab5 100644 --- a/vapi/packages/atk/atk.metadata +++ b/vapi/packages/atk/atk.metadata @@ -1,3 +1,4 @@ Atk cheader_filename="atk/atk.h" gir_namespace="Atk" gir_version="1.0" +AtkState is_value_type="1" simple_type="1" base_type="uint64" rank="11" AtkRectangle is_value_type="1"
1ffcd613de9c2fcc691b31355c635df9ffd6caca
drools
JBRULES-446 Support rulebase configuration via- jsr94 registerRuleExecutionSet properties--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@13123 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
a
https://github.com/kiegroup/drools
diff --git a/drools-jsr94/.classpath b/drools-jsr94/.classpath index cab36f7a135..332f406afe5 100644 --- a/drools-jsr94/.classpath +++ b/drools-jsr94/.classpath @@ -1,22 +1,24 @@ -<classpath> - <classpathentry kind="src" path="src/main/java"/> - <classpathentry kind="src" path="src/main/resources" excluding="**/*.java"/> - <classpathentry kind="src" path="src/test/java" output="target/test-classes"/> - <classpathentry kind="src" path="src/test/resources" output="target/test-classes" excluding="**/*.java"/> - <classpathentry kind="output" path="target/classes"/> - <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> - <classpathentry kind="var" path="M2_REPO/xpp3/xpp3/1.1.3.4.O/xpp3-1.1.3.4.O.jar"/> - <classpathentry kind="src" path="/drools-core"/> - <classpathentry kind="src" path="/drools-compiler"/> - <classpathentry kind="var" path="M2_REPO/xerces/xercesImpl/2.4.0/xercesImpl-2.4.0.jar"/> - <classpathentry kind="var" path="M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar"/> - <classpathentry kind="var" path="M2_REPO/org/mvel/mvel14/1.2beta27/mvel14-1.2beta27.jar"/> - <classpathentry kind="var" path="M2_REPO/jsr94/jsr94/1.1/jsr94-1.1.jar"/> - <classpathentry kind="var" path="M2_REPO/org/eclipse/jdt/core/3.2.3.v_686_R32x/core-3.2.3.v_686_R32x.jar"/> - <classpathentry kind="var" path="M2_REPO/janino/janino/2.5.7/janino-2.5.7.jar"/> - <classpathentry kind="var" path="M2_REPO/org/antlr/antlr-runtime/3.0/antlr-runtime-3.0.jar"/> - <classpathentry kind="var" path="M2_REPO/jsr94/jsr94-sigtest/1.1/jsr94-sigtest-1.1.jar"/> - <classpathentry kind="var" path="M2_REPO/xml-apis/xml-apis/1.0.b2/xml-apis-1.0.b2.jar"/> - <classpathentry kind="var" path="M2_REPO/xstream/xstream/1.1.3/xstream-1.1.3.jar"/> - <classpathentry kind="var" path="M2_REPO/jsr94/jsr94-tck/1.0.3/jsr94-tck-1.0.3.jar"/> -</classpath> \ No newline at end of file +<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry kind="src" path="src/main/java"/> + <classpathentry excluding="**/*.java" kind="src" path="src/main/resources"/> + <classpathentry kind="src" output="target/test-classes" path="src/test/java"/> + <classpathentry excluding="**/*.java" kind="src" output="target/test-classes" path="src/test/resources"/> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> + <classpathentry kind="var" path="M2_REPO/xpp3/xpp3/1.1.3.4.O/xpp3-1.1.3.4.O.jar"/> + <classpathentry kind="src" path="/drools-core"/> + <classpathentry kind="src" path="/drools-compiler"/> + <classpathentry kind="var" path="M2_REPO/xerces/xercesImpl/2.4.0/xercesImpl-2.4.0.jar"/> + <classpathentry kind="var" path="M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar"/> + <classpathentry kind="var" path="M2_REPO/org/mvel/mvel14/1.2beta27/mvel14-1.2beta27.jar"/> + <classpathentry kind="var" path="M2_REPO/jsr94/jsr94/1.1/jsr94-1.1.jar"/> + <classpathentry kind="var" path="M2_REPO/org/eclipse/jdt/core/3.2.3.v_686_R32x/core-3.2.3.v_686_R32x.jar"/> + <classpathentry kind="var" path="M2_REPO/janino/janino/2.5.7/janino-2.5.7.jar"/> + <classpathentry kind="var" path="M2_REPO/org/antlr/antlr-runtime/3.0/antlr-runtime-3.0.jar"/> + <classpathentry kind="var" path="M2_REPO/jsr94/jsr94-sigtest/1.1/jsr94-sigtest-1.1.jar"/> + <classpathentry kind="var" path="M2_REPO/xml-apis/xml-apis/1.0.b2/xml-apis-1.0.b2.jar"/> + <classpathentry kind="var" path="M2_REPO/xstream/xstream/1.1.3/xstream-1.1.3.jar"/> + <classpathentry kind="var" path="M2_REPO/jsr94/jsr94-tck/1.0.3/jsr94-tck-1.0.3.jar"/> + <classpathentry combineaccessrules="false" kind="src" path="/drools-decisiontables"/> + <classpathentry kind="output" path="target/classes"/> +</classpath> diff --git a/drools-jsr94/src/main/java/org/drools/jsr94/rules/Constants.java b/drools-jsr94/src/main/java/org/drools/jsr94/rules/Constants.java index 1de15d3560b..0c4b40f427d 100644 --- a/drools-jsr94/src/main/java/org/drools/jsr94/rules/Constants.java +++ b/drools-jsr94/src/main/java/org/drools/jsr94/rules/Constants.java @@ -37,4 +37,18 @@ private Constants() { /** <code>RuleExecutionSet</code> description constant. */ public static final String RES_DESCRIPTION = "javax.rules.admin.RuleExecutionSet.description"; + + public static final String RES_SOURCE = "javax.rules.admin.RuleExecutionSet.source"; + + public static final String RES_SOURCE_TYPE_XML = "javax.rules.admin.RuleExecutionSet.source.xml"; + + public static final String RES_SOURCE_TYPE_DECISION_TABLE = "javax.rules.admin.RuleExecutionSet.source.decisiontable"; + + public static final String RES_DSRL = "javax.rules.admin.RuleExecutionSet.dsrl"; + + /** <code>RuleExecutionSet</code> rulebase config constant. */ + public static final String RES_RULEBASE_CONFIG = "javax.rules.admin.RuleExecutionSet.ruleBaseConfiguration"; + + /** <code>RuleExecutionSet</code> package builder config constant. */ + public static final String RES_PACKAGEBUILDER_CONFIG = "javax.rules.admin.RuleExecutionSet.ruleBaseConfiguration"; } diff --git a/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/LocalRuleExecutionSetProviderImpl.java b/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/LocalRuleExecutionSetProviderImpl.java index 252567344e4..78cba0e8602 100644 --- a/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/LocalRuleExecutionSetProviderImpl.java +++ b/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/LocalRuleExecutionSetProviderImpl.java @@ -30,6 +30,10 @@ import org.drools.IntegrationException; import org.drools.compiler.DroolsParserException; import org.drools.compiler.PackageBuilder; +import org.drools.compiler.PackageBuilderConfiguration; +import org.drools.decisiontable.InputType; +import org.drools.decisiontable.SpreadsheetCompiler; +import org.drools.jsr94.rules.Constants; import org.drools.rule.Package; /** @@ -73,8 +77,23 @@ public LocalRuleExecutionSetProviderImpl() { * @return The created <code>RuleExecutionSet</code>. */ public RuleExecutionSet createRuleExecutionSet(final InputStream ruleExecutionSetStream, - final Map properties) throws RuleExecutionSetCreateException { - return createRuleExecutionSet( new InputStreamReader( ruleExecutionSetStream ), properties); + final Map properties) throws RuleExecutionSetCreateException { + if ( properties != null ) { + String source = ( String ) properties.get( Constants.RES_SOURCE ); + if ( source == null ) { + // support legacy name + source = ( String ) properties.get( "source" ); + } + if ( source != null && source.equals( Constants.RES_SOURCE_TYPE_DECISION_TABLE ) ) { + final SpreadsheetCompiler converter = new SpreadsheetCompiler(); + final String drl = converter.compile( ruleExecutionSetStream, + InputType.XLS ); + return createRuleExecutionSet( new StringReader( drl ), properties ); + } else { + return createRuleExecutionSet( new InputStreamReader( ruleExecutionSetStream ), properties); + } + } else + return createRuleExecutionSet( new InputStreamReader( ruleExecutionSetStream ), properties); } @@ -99,37 +118,56 @@ public RuleExecutionSet createRuleExecutionSet(final InputStream ruleExecutionSe public RuleExecutionSet createRuleExecutionSet(final Reader ruleExecutionSetReader, final Map properties) throws RuleExecutionSetCreateException { try { - final PackageBuilder builder = new PackageBuilder(); - Object dsl = null; + PackageBuilderConfiguration config= null; + + if ( properties != null ) { + config = (PackageBuilderConfiguration) properties.get( Constants.RES_PACKAGEBUILDER_CONFIG ); + } + + PackageBuilder builder = null; + if ( config != null ) { + builder = new PackageBuilder(config); + } else { + builder = new PackageBuilder(); + } + + Object dsrl = null; String source = null; if ( properties != null ) { - dsl = properties.get( "dsl" ); - source = ( String ) properties.get( "source" ); + dsrl = properties.get( Constants.RES_DSRL ); + if ( dsrl == null ) { + // check for old legacy name ending + dsrl = properties.get( "dsl" ); + } + source = ( String ) properties.get( Constants.RES_SOURCE ); + if ( source == null ) { + // check for old legacy name ending + source = ( String ) properties.get( "source" ); + } } if ( source == null ) { source = "drl"; - } - + } - if ( dsl == null ) { - if ( source.equals( "xml" ) ) { + if ( dsrl == null ) { + if ( source.equals( Constants.RES_SOURCE_TYPE_XML ) || source.equals( "xml" ) ) { builder.addPackageFromXml( ruleExecutionSetReader ); } else { builder.addPackageFromDrl( ruleExecutionSetReader ); } } else { - if ( source.equals( "xml" ) ) { + if ( source.equals( Constants.RES_SOURCE_TYPE_XML ) || source.equals( "xml" ) ) { // xml cannot specify a dsl builder.addPackageFromXml( ruleExecutionSetReader ); } else { - if ( dsl instanceof Reader ) { + if ( dsrl instanceof Reader ) { builder.addPackageFromDrl( ruleExecutionSetReader, - (Reader) dsl ); + (Reader) dsrl ); } else { builder.addPackageFromDrl( ruleExecutionSetReader, - new StringReader( (String) dsl ) ); + new StringReader( (String) dsrl ) ); } } } diff --git a/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/RuleExecutionSetImpl.java b/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/RuleExecutionSetImpl.java index 6da640ecd37..3636b65ff09 100644 --- a/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/RuleExecutionSetImpl.java +++ b/drools-jsr94/src/main/java/org/drools/jsr94/rules/admin/RuleExecutionSetImpl.java @@ -26,9 +26,11 @@ import org.drools.IntegrationException; import org.drools.RuleBase; +import org.drools.RuleBaseConfiguration; import org.drools.RuleIntegrationException; import org.drools.StatefulSession; import org.drools.StatelessSession; +import org.drools.jsr94.rules.Constants; import org.drools.jsr94.rules.Jsr94FactHandleFactory; import org.drools.rule.Package; import org.drools.rule.Rule; @@ -114,9 +116,17 @@ public class RuleExecutionSetImpl } this.pkg = pkg; this.description = pkg.getName();//..getDocumentation( ); - - final org.drools.reteoo.ReteooRuleBase ruleBase = new org.drools.reteoo.ReteooRuleBase( UUIDGenerator.getInstance().generateRandomBasedUUID().toString(), - new Jsr94FactHandleFactory() ); + + RuleBaseConfiguration config = ( RuleBaseConfiguration ) this.properties.get( Constants.RES_RULEBASE_CONFIG ); + org.drools.reteoo.ReteooRuleBase ruleBase; + if ( config != null ) { + ruleBase = new org.drools.reteoo.ReteooRuleBase( UUIDGenerator.getInstance().generateRandomBasedUUID().toString(), + config, + new Jsr94FactHandleFactory() ); + } else { + ruleBase = new org.drools.reteoo.ReteooRuleBase( UUIDGenerator.getInstance().generateRandomBasedUUID().toString(), + new Jsr94FactHandleFactory() ); + } ruleBase.addPackage( pkg ); this.ruleBase = ruleBase; diff --git a/drools-jsr94/src/test/java/org/drools/decisiontable/Cheese.java b/drools-jsr94/src/test/java/org/drools/decisiontable/Cheese.java new file mode 100644 index 00000000000..d6ae471da6e --- /dev/null +++ b/drools-jsr94/src/test/java/org/drools/decisiontable/Cheese.java @@ -0,0 +1,45 @@ +package org.drools.decisiontable; + +/* + * Copyright 2005 JBoss Inc + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +public class Cheese { + private String type; + private int price; + + public Cheese() { + + } + public Cheese(final String type, + final int price) { + super(); + this.type = type; + this.price = price; + } + + public int getPrice() { + return this.price; + } + + public String getType() { + return this.type; + } + + public void setPrice(final int price) { + this.price = price; + } + +} \ No newline at end of file diff --git a/drools-jsr94/src/test/java/org/drools/decisiontable/Person.java b/drools-jsr94/src/test/java/org/drools/decisiontable/Person.java new file mode 100644 index 00000000000..b467a800e0a --- /dev/null +++ b/drools-jsr94/src/test/java/org/drools/decisiontable/Person.java @@ -0,0 +1,93 @@ +package org.drools.decisiontable; + +/* + * Copyright 2005 JBoss Inc + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +public class Person { + private String name; + private String likes; + private int age; + + private char sex; + + private boolean alive; + + private String status; + + public Person() { + + } + public Person(final String name) { + this( name, + "", + 0 ); + } + + public Person(final String name, + final String likes) { + this( name, + likes, + 0 ); + } + + public Person(final String name, + final String likes, + final int age) { + this.name = name; + this.likes = likes; + this.age = age; + } + + public String getStatus() { + return this.status; + } + + public void setStatus(final String status) { + this.status = status; + } + + public String getLikes() { + return this.likes; + } + + public String getName() { + return this.name; + } + + public int getAge() { + return this.age; + } + + public boolean isAlive() { + return this.alive; + } + + public void setAlive(final boolean alive) { + this.alive = alive; + } + + public char getSex() { + return this.sex; + } + + public void setSex(final char sex) { + this.sex = sex; + } + + public String toString() { + return "[Person name='" + this.name + "']"; + } +} \ No newline at end of file diff --git a/drools-jsr94/src/test/java/org/drools/decisiontable/SpreadsheetIntegrationTest.java b/drools-jsr94/src/test/java/org/drools/decisiontable/SpreadsheetIntegrationTest.java new file mode 100644 index 00000000000..4a7c9e302e0 --- /dev/null +++ b/drools-jsr94/src/test/java/org/drools/decisiontable/SpreadsheetIntegrationTest.java @@ -0,0 +1,91 @@ +package org.drools.decisiontable; + +/* + * Copyright 2005 JBoss Inc + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.rules.RuleRuntime; +import javax.rules.RuleServiceProvider; +import javax.rules.RuleServiceProviderManager; +import javax.rules.RuleSession; +import javax.rules.StatefulRuleSession; +import javax.rules.admin.LocalRuleExecutionSetProvider; +import javax.rules.admin.RuleAdministrator; +import javax.rules.admin.RuleExecutionSet; + +import junit.framework.TestCase; + +import org.acme.insurance.launcher.PricingRuleLauncher; +import org.drools.RuleBase; +import org.drools.RuleBaseFactory; +import org.drools.WorkingMemory; +import org.drools.compiler.PackageBuilder; +import org.drools.jsr94.rules.Constants; +import org.drools.jsr94.rules.ExampleRuleEngineFacade; +import org.drools.jsr94.rules.RuleEngineTestBase; +import org.drools.jsr94.rules.RuleServiceProviderImpl; +import org.drools.rule.Package; + +public class SpreadsheetIntegrationTest extends TestCase { + + public void testExecute() throws Exception { + Map properties = new HashMap(); + properties.put( Constants.RES_SOURCE, + Constants.RES_SOURCE_TYPE_DECISION_TABLE ); + + RuleServiceProviderManager.registerRuleServiceProvider( ExampleRuleEngineFacade.RULE_SERVICE_PROVIDER, + RuleServiceProviderImpl.class ); + + RuleServiceProvider ruleServiceProvider = RuleServiceProviderManager.getRuleServiceProvider( ExampleRuleEngineFacade.RULE_SERVICE_PROVIDER ); + RuleAdministrator ruleAdministrator = ruleServiceProvider.getRuleAdministrator(); + LocalRuleExecutionSetProvider ruleSetProvider = ruleAdministrator.getLocalRuleExecutionSetProvider( null ); + + RuleExecutionSet ruleExecutionSet = ruleSetProvider.createRuleExecutionSet( SpreadsheetIntegrationTest.class.getResourceAsStream( "IntegrationExampleTest.xls" ), + properties ); + + ruleAdministrator.registerRuleExecutionSet( "IntegrationExampleTest.xls", + ruleExecutionSet, + properties ); + + properties.clear(); + final List list = new ArrayList(); + properties.put( "list", + list ); + + RuleRuntime ruleRuntime = ruleServiceProvider.getRuleRuntime(); + StatefulRuleSession session = (StatefulRuleSession) ruleRuntime.createRuleSession( "IntegrationExampleTest.xls", + properties, + RuleRuntime.STATEFUL_SESSION_TYPE ); + + //ASSERT AND FIRE + session.addObject( new Cheese( "stilton", + 42 ) ); + session.addObject( new Person( "michael", + "stilton", + 42 ) ); + + session.executeRules(); + assertEquals( 1, + list.size() ); + + } + +} \ No newline at end of file diff --git a/drools-jsr94/src/test/java/org/drools/jsr94/rules/ExampleRuleEngineFacade.java b/drools-jsr94/src/test/java/org/drools/jsr94/rules/ExampleRuleEngineFacade.java index 18128d1e679..f735ca4ee47 100644 --- a/drools-jsr94/src/test/java/org/drools/jsr94/rules/ExampleRuleEngineFacade.java +++ b/drools-jsr94/src/test/java/org/drools/jsr94/rules/ExampleRuleEngineFacade.java @@ -86,7 +86,7 @@ public ExampleRuleEngineFacade() throws Exception { this.ruleAdministrator = this.ruleServiceProvider.getRuleAdministrator(); this.ruleSetProvider = this.ruleAdministrator.getLocalRuleExecutionSetProvider( null ); - } + } public void addRuleExecutionSet(final String bindUri, final InputStream resourceAsStream) throws Exception { diff --git a/drools-jsr94/src/test/resources/org/drools/decisiontable/IntegrationExampleTest.xls b/drools-jsr94/src/test/resources/org/drools/decisiontable/IntegrationExampleTest.xls new file mode 100644 index 00000000000..adf5d9829a8 Binary files /dev/null and b/drools-jsr94/src/test/resources/org/drools/decisiontable/IntegrationExampleTest.xls differ
0b556bfe84ce5ad659e2e944a010a9d5c927a7b6
Vala
girparser: Support interface aliases
a
https://github.com/GNOME/vala/
diff --git a/vala/valagirparser.vala b/vala/valagirparser.vala index e1f4f9dbd8..a50879dcd0 100644 --- a/vala/valagirparser.vala +++ b/vala/valagirparser.vala @@ -3352,6 +3352,16 @@ public class Vala.GirParser : CodeVisitor { cl.comment = alias.comment; cl.external = true; alias.symbol = cl; + } else if (type_sym is Interface) { + // this is not a correct alias, but what can we do otherwise? + var iface = new Interface (alias.name, alias.source_reference); + iface.access = SymbolAccessibility.PUBLIC; + if (base_type != null) { + iface.add_prerequisite (base_type); + } + iface.comment = alias.comment; + iface.external = true; + alias.symbol = iface; } else if (type_sym is Delegate) { var orig = (Delegate) type_sym; if (base_node != null) { diff --git a/vapi/cogl-pango-1.0.vapi b/vapi/cogl-pango-1.0.vapi index 20e0ae51ee..689e2a08bc 100644 --- a/vapi/cogl-pango-1.0.vapi +++ b/vapi/cogl-pango-1.0.vapi @@ -2,18 +2,6 @@ [CCode (cprefix = "CoglPango", gir_namespace = "CoglPango", gir_version = "1.0", lower_case_cprefix = "cogl_pango_")] namespace CoglPango { - [CCode (cheader_filename = "cogl-pango/cogl-pango.h")] - public class FontMap : Pango.FontMap { - [CCode (has_construct_function = false)] - protected FontMap (); - public static void clear_glyph_cache (Pango.CairoFontMap font_map); - public static Pango.Context create_context (Pango.CairoFontMap font_map); - public static unowned Pango.Renderer get_renderer (Pango.CairoFontMap font_map); - public static Cogl.Bool get_use_mipmapping (Pango.CairoFontMap font_map); - public static Pango.FontMap @new (); - public static void set_resolution (Pango.CairoFontMap font_map, double dpi); - public static void set_use_mipmapping (Pango.CairoFontMap font_map, Cogl.Bool value); - } [CCode (cheader_filename = "cogl-pango/cogl-pango.h", type_id = "cogl_pango_renderer_get_type ()")] public class Renderer : Pango.Renderer { [CCode (has_construct_function = false)] @@ -21,6 +9,16 @@ namespace CoglPango { public void* context { construct; } } [CCode (cheader_filename = "cogl-pango/cogl-pango.h")] + public interface FontMap : Pango.CairoFontMap, GLib.Object { + public static void clear_glyph_cache (CoglPango.FontMap font_map); + public static Pango.Context create_context (CoglPango.FontMap font_map); + public static unowned Pango.Renderer get_renderer (CoglPango.FontMap font_map); + public static Cogl.Bool get_use_mipmapping (CoglPango.FontMap font_map); + public static Pango.FontMap @new (); + public static void set_resolution (CoglPango.FontMap font_map, double dpi); + public static void set_use_mipmapping (CoglPango.FontMap font_map, Cogl.Bool value); + } + [CCode (cheader_filename = "cogl-pango/cogl-pango.h")] public static void ensure_glyph_cache_for_layout (Pango.Layout layout); [CCode (cheader_filename = "cogl-pango/cogl-pango.h")] [Deprecated (since = "1.16")]
c4dd556b92f4b712e3a151181fc15af067322c3d
kotlin
Fix for EA-39487--
c
https://github.com/JetBrains/kotlin
diff --git a/idea/src/org/jetbrains/jet/plugin/quickfix/ExclExclCallFix.java b/idea/src/org/jetbrains/jet/plugin/quickfix/ExclExclCallFix.java index a267e2c58223c..d6507d823ee4b 100644 --- a/idea/src/org/jetbrains/jet/plugin/quickfix/ExclExclCallFix.java +++ b/idea/src/org/jetbrains/jet/plugin/quickfix/ExclExclCallFix.java @@ -26,6 +26,7 @@ import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.psi.JetExpression; import org.jetbrains.jet.lang.psi.JetFile; import org.jetbrains.jet.lang.psi.JetPostfixExpression; @@ -112,14 +113,14 @@ private static boolean isAvailableForRemove(Editor editor, PsiFile file) { private static PsiElement getExclExclElement(Editor editor, PsiFile file) { final PsiElement elementAtCaret = file.findElementAt(editor.getCaretModel().getOffset()); - if (elementAtCaret instanceof LeafPsiElement) { - LeafPsiElement leafElement = (LeafPsiElement) elementAtCaret; - if (leafElement.getElementType() == JetTokens.EXCLEXCL) { - return elementAtCaret; - } + if (isExclExclLeaf(elementAtCaret)) { + return elementAtCaret; + } - LeafPsiElement prevLeaf = (LeafPsiElement) PsiTreeUtil.prevLeaf(leafElement); - if (prevLeaf != null && prevLeaf.getElementType() == JetTokens.EXCLEXCL) { + if (elementAtCaret != null) { + // Case when caret is placed right after !! + PsiElement prevLeaf = PsiTreeUtil.prevLeaf(elementAtCaret); + if (isExclExclLeaf(prevLeaf)) { return prevLeaf; } } @@ -127,6 +128,10 @@ private static PsiElement getExclExclElement(Editor editor, PsiFile file) { return null; } + private static boolean isExclExclLeaf(@Nullable PsiElement element) { + return (element instanceof LeafPsiElement) && ((LeafPsiElement) element).getElementType() == JetTokens.EXCLEXCL; + } + private static JetExpression getExpressionForIntroduceCall(Editor editor, PsiFile file) { final PsiElement elementAtCaret = file.findElementAt(editor.getCaretModel().getOffset()); if (elementAtCaret != null) {
5fe6054a3835b11a4432e3da770f779183de4291
Mylyn Reviews
Minor cleanup -ignore warning about internal api -minor reformatting
p
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/internal/CreateReviewActionFromAttachment.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/CreateReviewActionFromAttachment.java index d9265032..81c8bf28 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/CreateReviewActionFromAttachment.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/CreateReviewActionFromAttachment.java @@ -39,6 +39,12 @@ import org.eclipse.mylyn.tasks.ui.TasksUi; import org.eclipse.ui.IActionDelegate; +/** + * + * @author mattk + * + */ +@SuppressWarnings("restriction") public class CreateReviewActionFromAttachment extends Action implements IActionDelegate { @@ -53,7 +59,8 @@ public void run(IAction action) { ITaskDataManager manager = TasksUi.getTaskDataManager(); TaskData parentTaskData = manager.getTaskData(taskAttachment .getTask()); - ITaskProperties parentTask= TaskProperties.fromTaskData(manager, parentTaskData); + ITaskProperties parentTask = TaskProperties.fromTaskData(manager, + parentTaskData); TaskMapper initializationData = new TaskMapper(parentTaskData); IReviewMapper taskMapper = ReviewsUiPlugin.getMapper(); @@ -69,12 +76,13 @@ public void run(IAction action) { ITaskProperties taskProperties = TaskProperties.fromTaskData( manager, taskData); - taskProperties.setSummary("[review] " + parentTask.getDescription()); + taskProperties + .setSummary("[review] " + parentTask.getDescription()); String reviewer = taskRepository.getUserName(); taskProperties.setAssignedTo(reviewer); - initTaskProperties(taskMapper, taskProperties,parentTask); + initTaskProperties(taskMapper, taskProperties, parentTask); TasksUiInternal.createAndOpenNewTask(taskData); } catch (CoreException e) { @@ -84,15 +92,13 @@ public void run(IAction action) { } private void initTaskProperties(IReviewMapper taskMapper, - ITaskProperties taskProperties,ITaskProperties parentTask) { + ITaskProperties taskProperties, ITaskProperties parentTask) { ReviewScope scope = new ReviewScope(); for (ITaskAttachment taskAttachment : selection2) { // FIXME date from task attachment - Attachment attachment = ReviewsUtil - .findAttachment(taskAttachment.getFileName(), - taskAttachment.getAuthor().getPersonId(), - taskAttachment.getCreationDate().toString(), - parentTask); + Attachment attachment = ReviewsUtil.findAttachment(taskAttachment + .getFileName(), taskAttachment.getAuthor().getPersonId(), + taskAttachment.getCreationDate().toString(), parentTask); if (attachment.isPatch()) { scope.addScope(new PatchScopeItem(attachment)); } else { @@ -127,5 +133,4 @@ public void selectionChanged(IAction action, ISelection selection) { } } } - } diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPage.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPage.java index a7b674ca..71f035d5 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPage.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPage.java @@ -40,6 +40,7 @@ /* * @author Kilian Matt */ +@SuppressWarnings("restriction") public class ReviewTaskEditorPage extends AbstractTaskEditorPage { private ReviewScope scope;
27b237422064ba6c910ae73fe4adeb79e04e5166
Valadoc
Add a metadata-format for gir files
a
https://github.com/GNOME/vala/
diff --git a/src/libvaladoc/Makefile.am b/src/libvaladoc/Makefile.am index b2f07a629d..b54bbdef18 100755 --- a/src/libvaladoc/Makefile.am +++ b/src/libvaladoc/Makefile.am @@ -44,6 +44,7 @@ libvaladoc_la_VALASOURCES = \ documentation/wikiscanner.vala \ documentation/gtkdoccommentparser.vala \ documentation/gtkdoccommentscanner.vala \ + documentation/girmetadata.vala \ importer/documentationimporter.vala \ importer/valadocdocumentationimporter.vala \ importer/valadocdocumentationimporterscanner.vala \ diff --git a/src/libvaladoc/documentation/girmetadata.vala b/src/libvaladoc/documentation/girmetadata.vala new file mode 100644 index 0000000000..010ecd9e20 --- /dev/null +++ b/src/libvaladoc/documentation/girmetadata.vala @@ -0,0 +1,132 @@ +/* girmetadata.vala + * + * Copyright (C) 2012 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: + * Brosch Florian <[email protected]> + */ + +/** + * Metadata reader for GIR files + */ +public class GirMetaData : Object { + private string? metadata_path = null; + private string? resource_dir = null; + + /** + * Used to manipulate paths to resources inside gir-files + */ + public string get_resource_path (string resource) { + if (resource_dir == null || metadata_path == null) { + return resource; + } + + if (Path.is_absolute (resource_dir)) { + return Path.build_filename (resource_dir, resource); + } + + return Path.build_filename (Path.get_dirname (metadata_path), resource_dir, resource); + } + + private string? get_metadata_file_name (string gir_file_path) { + string metadata_file_name = Path.get_basename (gir_file_path); + int last_dot_pos = metadata_file_name.last_index_of ("."); + if (last_dot_pos < 0) { + return null; + } + + metadata_file_name = metadata_file_name.substring (0, last_dot_pos); + return metadata_file_name + ".valadoc.metadata"; + } + + private string? get_metadata_path (string gir_file_path, string[] metadata_dirs) { + string? metadata_file_name = get_metadata_file_name (gir_file_path); + if (metadata_file_name == null) { + return null; + } + + // search for metatada at the same location as the gir file + string metadata_path = Path.build_filename (Path.get_dirname (gir_file_path), metadata_file_name); + if (FileUtils.test (metadata_path, FileTest.IS_REGULAR)) { + return metadata_path; + } + + foreach (string metadata_dir in metadata_dirs) { + metadata_path = Path.build_filename (metadata_dir, metadata_file_name); + if (FileUtils.test (metadata_path, FileTest.IS_REGULAR)) { + return metadata_path; + } + } + + return null; + } + + private void load_general_metadata (KeyFile key_file) throws KeyFileError { + foreach (string key in key_file.get_keys ("General")) { + switch (key) { + case "resources": + this.resource_dir = key_file.get_string ("General", "resources"); + break; + + default: + stderr.printf ("Unknown key 'General.%s' in '%s'", key, metadata_path); + break; + } + } + } + + public GirMetaData (string gir_file_path, string[] metadata_dirs) { + if (!FileUtils.test (gir_file_path, FileTest.IS_REGULAR)) { + return ; + } + + metadata_path = get_metadata_path (gir_file_path, metadata_dirs); + if (metadata_path == null) { + return ; + } + + KeyFile key_file; + + try { + key_file = new KeyFile (); + key_file.load_from_file (metadata_path, KeyFileFlags.NONE); + } catch (KeyFileError e) { + stdout.printf ("Key file error: '%s': in %s\n", metadata_path, e.message); + return ; + } catch (FileError e) { + stdout.printf ("File error: '%s': in %s\n", metadata_path, e.message); + return ; + } + + try { + foreach (string group in key_file.get_groups ()) { + switch (group) { + case "General": + load_general_metadata (key_file); + break; + + default: + stdout.printf ("Unknown group '%s' in %s\n", group, metadata_path); + break; + } + } + } catch (KeyFileError e) { + stderr.printf ("%s: %s", metadata_path, e.message); + } + } +} + diff --git a/src/libvaladoc/documentation/gtkdoccommentparser.vala b/src/libvaladoc/documentation/gtkdoccommentparser.vala index b1486069d4..d63774bf4a 100644 --- a/src/libvaladoc/documentation/gtkdoccommentparser.vala +++ b/src/libvaladoc/documentation/gtkdoccommentparser.vala @@ -46,6 +46,23 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { private Regex? normalize_regex = null; + private HashMap<Api.SourceFile, GirMetaData> metadata = new HashMap<Api.SourceFile, GirMetaData> (); + private GirMetaData? current_metadata = null; + + private GirMetaData get_metadata_for_comment (Api.GirSourceComment gir_comment) { + GirMetaData metadata = metadata.get (gir_comment.file); + if (metadata != null) { + return metadata; + } + + metadata = new GirMetaData (gir_comment.file.relative_path, settings.metadata_directories); + this.metadata.set (gir_comment.file, metadata); + return metadata; + } + + private inline string fix_resource_path (string path) { + return this.current_metadata.get_resource_path (path); + } private void reset (Api.SourceComment comment) { this.scanner.reset (comment.content); @@ -218,6 +235,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { private Api.Node? element; public Comment? parse (Api.Node element, Api.GirSourceComment gir_comment) { + this.current_metadata = get_metadata_for_comment (gir_comment); this.element = element; Comment? comment = this.parse_main_content (gir_comment); @@ -756,7 +774,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { } Embedded e = factory.create_embedded (); - e.url = current.attributes.get ("fileref"); + e.url = fix_resource_path (current.attributes.get ("fileref")); next (); parse_docbook_spaces (); @@ -821,7 +839,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { if (current.type == TokenType.XML_OPEN && current.content == "programlisting") { append_block_content_not_null (content, parse_docbook_programlisting ()); - } else if (current.type == TokenType.XML_OPEN && current.content == "programlisting") { + } else if (current.type == TokenType.XML_OPEN && current.content == "inlinegraphic") { Embedded? img = parse_docbook_inlinegraphic (); Paragraph p = factory.create_paragraph (); append_block_content_not_null (content, p);
dee6fa9c5b599abf685527e357ffb7e89494a1e1
ReactiveX-RxJava
Implemented range operator--
a
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/Observable.java b/rxjava-core/src/main/java/rx/Observable.java index 0fd95c0068..0df09cb3c7 100644 --- a/rxjava-core/src/main/java/rx/Observable.java +++ b/rxjava-core/src/main/java/rx/Observable.java @@ -53,6 +53,7 @@ import rx.operators.OperationZip; import rx.util.AtomicObservableSubscription; import rx.util.AtomicObserver; +import rx.util.Range; import rx.util.functions.Action0; import rx.util.functions.Action1; import rx.util.functions.Func1; @@ -547,6 +548,20 @@ public static <T> Observable<T> from(T... items) { return toObservable(items); } + /** + * Generates an observable sequence of integral numbers within a specified range. + * + * @param start The value of the first integer in the sequence + * @param count The number of sequential integers to generate. + * + * @return An observable sequence that contains a range of sequential integral numbers. + * + * @see <a href="http://msdn.microsoft.com/en-us/library/hh229460(v=vs.103).aspx">Observable.Range Method (Int32, Int32)</a> + */ + public static Observable<Integer> range(int start, int count) { + return from(Range.createWithCount(start, count)); + } + /** * Returns an Observable that notifies an {@link Observer} of a single value and then completes. * <p> diff --git a/rxjava-core/src/main/java/rx/util/Range.java b/rxjava-core/src/main/java/rx/util/Range.java new file mode 100644 index 0000000000..bfc1bad44d --- /dev/null +++ b/rxjava-core/src/main/java/rx/util/Range.java @@ -0,0 +1,107 @@ +/** + * Copyright 2013 Netflix, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package rx.util; + +import org.junit.Test; + +import java.util.*; + +import static org.junit.Assert.assertEquals; + +public final class Range implements Iterable<Integer> { + private final int start; + private final int end; + private final int step; + + public static Range createWithCount(int start, int count) { + return create(start, start * (count + 1)); + } + + public static Range create(int start, int end) { + return new Range(start, end, 1); + } + + public static Range createWithStep(int start, int end, int step) { + return new Range(start, end, step); + } + + private Range(int start, int end, int step) { + this.start = start; + this.end = end; + this.step = step; + } + + @Override + public Iterator<Integer> iterator() { + return new Iterator<Integer>() { + private int current = start; + + @Override + public boolean hasNext() { + return current < end; + } + + @Override + public Integer next() { + if (!hasNext()) { + throw new NoSuchElementException("No more elements"); + } + int result = current; + current += step; + return result; + } + + @Override + public void remove() { + throw new UnsupportedOperationException("Read only iterator"); + } + }; + } + + @Override + public String toString() { + return "Range (" + start + ", " + end + "), step " + step; + } + + + public static class UnitTest { + + @Test + public void testSimpleRange() { + assertEquals(Arrays.asList(1, 2, 3, 4), toList(Range.create(1, 5))); + } + + @Test + public void testRangeWithStep() { + assertEquals(Arrays.asList(1, 3, 5, 7, 9), toList(Range.createWithStep(1, 10, 2))); + } + + @Test + public void testRangeWithCount() { + assertEquals(Arrays.asList(1, 2, 3, 4, 5), toList(Range.createWithCount(1, 5))); + } + + + private static <T> List<T> toList(Iterable<T> iterable) { + List<T> result = new ArrayList<T>(); + for (T element : iterable) { + result.add(element); + } + return result; + } + + } +} \ No newline at end of file
02b0fc2fa3a41f340a75235d407d8516fe4c7a63
restlet-framework-java
- Disabled failing test cases (temp)--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/AllServiceTests.java b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/AllServiceTests.java index 22c32949cc..f07b1d3823 100644 --- a/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/AllServiceTests.java +++ b/modules/org.restlet.test/src/org/restlet/test/jaxrs/services/tests/AllServiceTests.java @@ -60,7 +60,7 @@ public static Test suite() { mySuite.addTestSuite(InheritAnnotationTest.class); mySuite.addTestSuite(InjectionTest.class); mySuite.addTestSuite(Issue593Test.class); - mySuite.addTestSuite(JsonTest.class); + // mySuite.addTestSuite(JsonTest.class); mySuite.addTestSuite(ListParamTest.class); mySuite.addTestSuite(MatchedTest.class); mySuite.addTestSuite(MatrixParamTest.class); @@ -74,7 +74,7 @@ public static Test suite() { mySuite.addTestSuite(PathParamTest3.class); mySuite.addTestSuite(PersonsTest.class); mySuite.addTestSuite(PrimitiveWrapperEntityTest.class); - mySuite.addTestSuite(ProviderTest.class); + // mySuite.addTestSuite(ProviderTest.class); mySuite.addTestSuite(QueryParamTest.class); mySuite.addTestSuite(RecursiveTest.class); mySuite.addTestSuite(RepresentationTest.class);
b840ee2fb3875069fa1148c9c51a57fed5a9632c
intellij-community
IDEADEV-25382: idiotic "...please recompile"- error message killed--
c
https://github.com/JetBrains/intellij-community
diff --git a/compiler/impl/com/intellij/openapi/deployment/DeploymentUtilImpl.java b/compiler/impl/com/intellij/openapi/deployment/DeploymentUtilImpl.java index 87b13ed5164a3..d15996469fa1b 100644 --- a/compiler/impl/com/intellij/openapi/deployment/DeploymentUtilImpl.java +++ b/compiler/impl/com/intellij/openapi/deployment/DeploymentUtilImpl.java @@ -56,7 +56,7 @@ public boolean addModuleOutputContents(@NotNull CompileContext context, String[] sourceRoots = getSourceRootUrlsInReadAction(sourceModule); boolean ok = true; if (outputPath != null && sourceRoots.length != 0) { - ok = checkModuleOutputExists(outputPath, sourceModule, context); + ok = outputPath.exists(); boolean added = addItemsRecursively(items, outputPath, targetModule, outputRelativePath, fileFilter, possibleBaseOuputPath); if (!added) { LOG.assertTrue(possibleBaseOuputPath != null); @@ -91,18 +91,6 @@ public File compute() { }); } - private static boolean checkModuleOutputExists(final File outputPath, final Module sourceModule, CompileContext context) { - if (outputPath == null || !outputPath.exists()) { - String moduleName = ModuleUtil.getModuleNameInReadAction(sourceModule); - final String message = CompilerBundle.message("message.text.directory.not.found.please.recompile", - outputPath == null ? moduleName : FileUtil.toSystemDependentName(outputPath.getPath()), - moduleName); - context.addMessage(CompilerMessageCategory.ERROR, message, null, -1, -1); - return false; - } - return true; - } - public void addLibraryLink(@NotNull final CompileContext context, @NotNull final BuildRecipe items, @NotNull final LibraryLink libraryLink, @@ -433,7 +421,6 @@ private static void addJarJavaModuleOutput(BuildRecipe instructions, final String[] sourceUrls = getSourceRootUrlsInReadAction(module); if (sourceUrls.length > 0) { final File outputPath = getModuleOutputPath(module); - checkModuleOutputExists(outputPath, module, context); if (outputPath != null) { if ("/".equals(relativePath) || "".equals(relativePath) || getRelativePathForManifestLinking("/").equals(relativePath)) { context.addMessage(CompilerMessageCategory.ERROR, CompilerBundle.message("message.text.invalid.output.path.for.module.jar", relativePath, module.getName(), linkContainerDescription), null, -1, -1);
5804249b521c4edda47d0dffc514075cd6fb4503
intellij-community
Mac laf: add support for search controls with- history popups--
a
https://github.com/JetBrains/intellij-community
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/intellij/MacIntelliJTextFieldUI.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/intellij/MacIntelliJTextFieldUI.java index 21ec9d3211230..3190fac057a9b 100644 --- a/platform/platform-impl/src/com/intellij/ide/ui/laf/intellij/MacIntelliJTextFieldUI.java +++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/intellij/MacIntelliJTextFieldUI.java @@ -127,13 +127,15 @@ protected void paintSearchField(Graphics2D g, JTextComponent c, Rectangle r) { gg.dispose(); right.paintIcon(c, g, stop, r.y); - Icon label = MacIntelliJIconCache.getIcon("searchFieldLabel"); - if (StringUtil.isEmpty(c.getText()) && !c.hasFocus()) { + boolean withHistoryPopup = isSearchFieldWithHistoryPopup(c); + Icon label = MacIntelliJIconCache.getIcon(withHistoryPopup ? "searchFieldWithHistory" : "searchFieldLabel"); + if (StringUtil.isEmpty(c.getText()) && !c.hasFocus() && !withHistoryPopup) { label.paintIcon(c, g, r.x + (r.width - label.getIconWidth())/ 2, r.y); } else { gg = g.create(0, 0, c.getWidth(), c.getHeight()); - gg.setClip(r.x + 8, r.y, StringUtil.isEmpty(c.getText()) ? label.getIconWidth() : 16, label.getIconHeight()); - label.paintIcon(c, gg, r.x + 8, r.y); + int offset = withHistoryPopup ? 5 : 8; + gg.setClip(r.x + offset, r.y, StringUtil.isEmpty(c.getText()) ? label.getIconWidth() : 16, label.getIconHeight()); + label.paintIcon(c, gg, r.x + offset, r.y); } if (!StringUtil.isEmpty(c.getText())) { @@ -145,7 +147,7 @@ protected void paintSearchField(Graphics2D g, JTextComponent c, Rectangle r) { @Override protected Rectangle getVisibleEditorRect() { Rectangle rect = super.getVisibleEditorRect(); - if (isSearchField(myTextField)) { + if (rect != null && isSearchField(myTextField)) { rect.width -= 36; rect.x += 19; rect.y +=1;
30209c4c9a736fd937ecc7df25b5fb1ce893ae6f
Mylyn Reviews
322734: Result types in section text
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 5404ec38..48900dd4 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 @@ -22,6 +22,7 @@ import org.eclipse.jface.viewers.Viewer; import org.eclipse.mylyn.reviews.core.ReviewSubTask; import org.eclipse.mylyn.reviews.core.ReviewsUtil; +import org.eclipse.mylyn.reviews.core.model.review.Rating; import org.eclipse.mylyn.reviews.ui.Images; import org.eclipse.mylyn.tasks.core.ITask; import org.eclipse.mylyn.tasks.core.ITaskContainer; @@ -45,6 +46,7 @@ public class ReviewSummaryTaskEditorPart extends AbstractTaskEditorPart { public static final String ID_PART_REVIEWSUMMARY = "org.eclipse.mylyn.reviews.ui.editors.parts.reviewsummary"; //$NON-NLS-1$ + private Section summarySection; public ReviewSummaryTaskEditorPart() { setPartName(Messages.ReviewSummaryTaskEditorPart_Partname); @@ -52,13 +54,13 @@ public ReviewSummaryTaskEditorPart() { @Override public void createControl(final Composite parent, FormToolkit toolkit) { - Section summarySection = createSection(parent, toolkit, + summarySection = createSection(parent, toolkit, ExpandableComposite.TITLE_BAR | ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED); summarySection.setLayout(new FillLayout(SWT.HORIZONTAL)); summarySection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - summarySection.setText(Messages.ReviewSummaryTaskEditorPart_Partname); + // summarySection.setText(Messages.ReviewSummaryTaskEditorPart_Partname); Composite reviewResultsComposite = toolkit .createComposite(summarySection); toolkit.paintBordersFor(reviewResultsComposite); @@ -120,7 +122,32 @@ public Object[] getElements(Object inputElement) { TasksUi.getTaskDataManager(), TasksUi.getRepositoryModel(), new NullProgressMonitor()); + int passedCount = 0; + int warningCount = 0; + int failedCount = 0; + int noResultCount = 0; + for (ReviewSubTask subtask : reviewSubTasks) { + switch (subtask.getResult()) { + case PASSED: + passedCount++; + break; + case WARNING: + warningCount++; + break; + case FAILED: + failedCount++; + break; + case NONE: + noResultCount++; + break; + + } + } + summarySection.setText(String + .format("Review Summary (PASSED: %s / WARNING: %s / FAILED: %s / ?: %s)", + passedCount, warningCount, failedCount, + noResultCount)); return reviewSubTasks .toArray(new ReviewSubTask[reviewSubTasks.size()]); }
b33e61cf7b3e2b2913062d7ff3c978ffadaca3c4
Delta Spike
DELTASPIKE-402 cdicontainer.version for tomee via arquillian
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/provider/BeanProviderTest.java b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/provider/BeanProviderTest.java index d9c9feba9..94fecbc0e 100644 --- a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/provider/BeanProviderTest.java +++ b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/provider/BeanProviderTest.java @@ -42,6 +42,7 @@ public class BeanProviderTest { private static final String CONTAINER_OWB_1_1_x = "owb-1\\.1\\..*"; + private static final String CONTAINER_TOMEE_1_5_x = "tomee-1\\.5\\..*"; /** @@ -221,6 +222,7 @@ public void testDependentBeanSerialization() throws Exception { // this test is known to not work under owb-1.1.x as ManagedBean for Dependent scoped classes did not implement PassivationCapable. Assume.assumeTrue(!CdiContainerUnderTest.is(CONTAINER_OWB_1_1_x)); + Assume.assumeTrue(!CdiContainerUnderTest.is(CONTAINER_TOMEE_1_5_x)); DependentProvider<DependentTestBean> dependentTestBeanProvider = BeanProvider.getDependent(DependentTestBean.class); diff --git a/deltaspike/core/impl/src/test/resources/arquillian.xml b/deltaspike/core/impl/src/test/resources/arquillian.xml index 973dbb451..1d669d295 100644 --- a/deltaspike/core/impl/src/test/resources/arquillian.xml +++ b/deltaspike/core/impl/src/test/resources/arquillian.xml @@ -79,6 +79,7 @@ <property name="ajpPort">-1</property> <property name="stopPort">-1</property> <property name="appWorkingDir">target/arquillian-test-working-dir</property> + <property name="catalina_opts">-Dcdicontainer.version=tomee-${tomee.version}</property> </configuration> </container> </arquillian> diff --git a/deltaspike/parent/code/pom.xml b/deltaspike/parent/code/pom.xml index 97ecb03df..0368bff79 100644 --- a/deltaspike/parent/code/pom.xml +++ b/deltaspike/parent/code/pom.xml @@ -330,7 +330,7 @@ <id>tomee-build-managed</id> <properties> - <cdicontainer.version>owb-${owb.version}</cdicontainer.version> + <cdicontainer.version>tomee-${tomee.version}</cdicontainer.version> </properties> <dependencies>
ce424d73a2f43880f8e8d4f074ce4be8e9f6d80f
adangel$pmd
refactored type lookup functionality with a new TypeMap git-svn-id: https://pmd.svn.sourceforge.net/svnroot/pmd/trunk@4703 51baf565-9d33-0410-a72c-fc3788e3496d
p
https://github.com/adangel/pmd
diff --git a/pmd/src/net/sourceforge/pmd/rules/design/LooseCoupling.java b/pmd/src/net/sourceforge/pmd/rules/design/LooseCoupling.java index 4d2ed6a810d..85ee2eb13de 100644 --- a/pmd/src/net/sourceforge/pmd/rules/design/LooseCoupling.java +++ b/pmd/src/net/sourceforge/pmd/rules/design/LooseCoupling.java @@ -3,8 +3,6 @@ */ package net.sourceforge.pmd.rules.design; -import java.util.Set; - import net.sourceforge.pmd.AbstractRule; import net.sourceforge.pmd.ast.ASTClassOrInterfaceType; import net.sourceforge.pmd.ast.ASTFieldDeclaration; @@ -16,12 +14,12 @@ public class LooseCoupling extends AbstractRule { // TODO - these should be brought in via external properties - private static final Set implClassNames = CollectionUtil.asSet( new Object[] { - "ArrayList", "HashSet", "HashMap", "LinkedHashMap", "LinkedHashSet", "TreeSet", "TreeMap", "Vector", - "java.util.ArrayList", "java.util.HashSet", "java.util.HashMap", - "java.util.LinkedHashMap", "java.util.LinkedHashSet", "java.util.TreeSet", - "java.util.TreeMap", "java.util.Vector" - }); +// private static final Set implClassNames = CollectionUtil.asSet( new Object[] { +// "ArrayList", "HashSet", "HashMap", "LinkedHashMap", "LinkedHashSet", "TreeSet", "TreeMap", "Vector", +// "java.util.ArrayList", "java.util.HashSet", "java.util.HashMap", +// "java.util.LinkedHashMap", "java.util.LinkedHashSet", "java.util.TreeSet", +// "java.util.TreeMap", "java.util.Vector" +// }); public LooseCoupling() { super(); @@ -29,8 +27,9 @@ public LooseCoupling() { public Object visit(ASTClassOrInterfaceType node, Object data) { Node parent = node.jjtGetParent().jjtGetParent().jjtGetParent(); - if (implClassNames.contains(node.getImage()) && (parent instanceof ASTFieldDeclaration || parent instanceof ASTFormalParameter || parent instanceof ASTResultType)) { - addViolation(data, node, node.getImage()); + String typeName = node.getImage(); + if (CollectionUtil.isCollectionType(typeName, false) && (parent instanceof ASTFieldDeclaration || parent instanceof ASTFormalParameter || parent instanceof ASTResultType)) { + addViolation(data, node, typeName); } return data; } diff --git a/pmd/src/net/sourceforge/pmd/util/ClassUtil.java b/pmd/src/net/sourceforge/pmd/util/ClassUtil.java index 6cfc879457d..aac7fac0883 100644 --- a/pmd/src/net/sourceforge/pmd/util/ClassUtil.java +++ b/pmd/src/net/sourceforge/pmd/util/ClassUtil.java @@ -1,7 +1,6 @@ package net.sourceforge.pmd.util; import java.math.BigDecimal; -import java.util.Map; /** @@ -13,39 +12,40 @@ public class ClassUtil { private ClassUtil() {}; - private static final Map primitiveTypesByName = CollectionUtil.mapFrom( new Object[][] { - {"int", int.class }, - {"byte", byte.class }, - {"long", long.class }, - {"short", short.class }, - {"float", float.class }, - {"double", double.class }, - {"char", char.class }, - {"boolean", boolean.class }, + private static final TypeMap primitiveTypesByName = new TypeMap( new Class[] { + int.class, + byte.class, + long.class, + short.class, + float.class, + double.class, + char.class, + boolean.class, }); - private static final Map typesByShortName = CollectionUtil.mapFrom( new Object[][] { - {"Integer", Integer.class }, - {"Byte", Byte.class }, - {"Long", Long.class }, - {"Short", Short.class }, - {"Float", Float.class }, - {"Double", Double.class }, - {"Character", Character.class }, - {"Boolean", Boolean.class }, - {"BigDecimal", BigDecimal.class }, - {"String", String.class }, - {"Object", Object.class }, - {"Object[]", Object[].class } + private static final TypeMap typesByNames = new TypeMap( new Class[] { + Integer.class, + Byte.class, + Long.class, + Short.class, + Float.class, + Double.class, + Character.class, + Boolean.class, + BigDecimal.class, + String.class, + Object.class, }); /** - * Method getPrimitiveTypeFor. + * Returns the type(class) for the name specified + * or null if not found. + * * @param name String * @return Class */ public static Class getPrimitiveTypeFor(String name) { - return (Class)primitiveTypesByName.get(name); + return primitiveTypesByName.typeFor(name); } /** @@ -56,13 +56,28 @@ public static Class getPrimitiveTypeFor(String name) { */ public static Class getTypeFor(String shortName) { - Class cls = (Class)typesByShortName.get(shortName); - if (cls != null) return cls; + Class type = typesByNames.typeFor(shortName); + if (type != null) return type; - cls = (Class)primitiveTypesByName.get(shortName); - if (cls != null) return cls; + type = primitiveTypesByName.typeFor(shortName); + if (type != null) return type; return CollectionUtil.getCollectionTypeFor(shortName); } - + /** + * Returns the abbreviated name of the type, + * without the package name + * + * @param fullTypeName + * @return String + */ + + public static String withoutPackageName(String fullTypeName) { + + int dotPos = fullTypeName.lastIndexOf('.'); + + return dotPos > 0 ? + fullTypeName.substring(dotPos+1) : + fullTypeName; + } } diff --git a/pmd/src/net/sourceforge/pmd/util/CollectionUtil.java b/pmd/src/net/sourceforge/pmd/util/CollectionUtil.java index 8f7a5f542b3..1bfb95d5fcc 100644 --- a/pmd/src/net/sourceforge/pmd/util/CollectionUtil.java +++ b/pmd/src/net/sourceforge/pmd/util/CollectionUtil.java @@ -15,31 +15,56 @@ */ public class CollectionUtil { - public static final Map collectionTypesByShortName = mapFrom( new Object[][] { - {"List", java.util.List.class }, - {"Collection", java.util.Collection.class }, - {"Map", java.util.Map.class }, - {"ArrayList", java.util.ArrayList.class }, - {"LinkedList", java.util.LinkedList.class }, - {"Vector", java.util.Vector.class }, - {"HashMap", java.util.HashMap.class }, - {"TreeMap", java.util.TreeMap.class }, - {"Set", java.util.Set.class }, - {"HashSet", java.util.HashSet.class } - }); + public static final TypeMap collectionInterfacesByNames = new TypeMap( new Class[] { + java.util.List.class, + java.util.Collection.class, + java.util.Map.class, + java.util.Set.class, + }); + + public static final TypeMap collectionClassesByNames = new TypeMap( new Class[] { + java.util.ArrayList.class, + java.util.LinkedList.class, + java.util.Vector.class, + java.util.HashMap.class, + java.util.LinkedHashMap.class, + java.util.TreeMap.class, + java.util.TreeSet.class, + java.util.HashSet.class, + java.util.LinkedHashSet.class + }); private CollectionUtil() {}; /** - * Returns the collection type if we know it by its short name. + * Returns the collection type if we recognize it by its short name. * - * @param name String + * @param shortName String * @return Class */ - public static Class getCollectionTypeFor(String name) { - return (Class)collectionTypesByShortName.get(name); + public static Class getCollectionTypeFor(String shortName) { + Class cls = collectionClassesByNames.typeFor(shortName); + if (cls != null) return cls; + + return collectionInterfacesByNames.typeFor(shortName); } + /** + * Return whether we can identify the typeName as a java.util collection class + * or interface as specified. + * + * @param typeName String + * @param includeInterfaces boolean + * @return boolean + */ + public static boolean isCollectionType(String typeName, boolean includeInterfaces) { + + if (collectionClassesByNames.contains(typeName)) return true; + + return includeInterfaces && collectionInterfacesByNames.contains(typeName); + } + + /** * Returns the items as a populated set. * diff --git a/pmd/src/net/sourceforge/pmd/util/TypeMap.java b/pmd/src/net/sourceforge/pmd/util/TypeMap.java new file mode 100644 index 00000000000..644066d58a8 --- /dev/null +++ b/pmd/src/net/sourceforge/pmd/util/TypeMap.java @@ -0,0 +1,84 @@ +package net.sourceforge.pmd.util; + +import java.util.HashMap; +import java.util.Map; + +/** + * A specialized map that stores classes by both their full and short names. + * + * @author Brian Remedios + */ +public class TypeMap { + + private Map typesByName; + + /** + * Constructor for TypeMap. + * @param initialSize int + */ + public TypeMap(int initialSize) { + typesByName = new HashMap(initialSize); + } + + /** + * Constructor for TypeMap that takes in an initial set of types. + * + * @param types Class[] + */ + public TypeMap(Class[] types) { + this(types.length); + add(types); + } + + /** + * Adds a type to the receiver and stores it keyed by both its full + * and short names. + * + * @param type Class + */ + public void add(Class type) { + typesByName.put(type.getName(), type); + typesByName.put(ClassUtil.withoutPackageName(type.getName()), type); + } + + /** + * Returns whether the type is known to the receiver. + * + * @param type Class + * @return boolean + */ + public boolean contains(Class type) { + return typesByName.containsValue(type); + } + + /** + * Returns whether the typeName is known to the receiver. + * + * @param typeName String + * @return boolean + */ + public boolean contains(String typeName) { + return typesByName.containsKey(typeName); + } + + /** + * Returns the type for the typeName specified. + * + * @param typeName String + * @return Class + */ + public Class typeFor(String typeName) { + return (Class)typesByName.get(typeName); + } + + /** + * Adds an array of types to the receiver at once. + * + * @param types Class[] + */ + public void add(Class[] types) { + for (int i=0; i<types.length; i++) { + add(types[i]); + } + } +}
c873ad72e7d2c6e2f5340deea5ec7b7eefa92839
edwardkort$wwidesigner
Move functionality into StudyModel, to facilitate standalone testing of that class. StudyModel now encapsulates uses of the bind factories; they are no longer needed in StudyView.
p
https://github.com/edwardkort/wwidesigner
diff --git a/WWIDesigner/src/main/com/wwidesigner/gui/StudyModel.java b/WWIDesigner/src/main/com/wwidesigner/gui/StudyModel.java index b84a272..8fe8476 100644 --- a/WWIDesigner/src/main/com/wwidesigner/gui/StudyModel.java +++ b/WWIDesigner/src/main/com/wwidesigner/gui/StudyModel.java @@ -1,8 +1,6 @@ -/** - * - */ package com.wwidesigner.gui; +import java.io.File; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; @@ -24,6 +22,8 @@ import com.wwidesigner.util.PhysicalParameters; /** + * Abstract class to encapsulate processes for analyzing and optimizing + * instrument models. * @author kort * */ @@ -39,6 +39,11 @@ public abstract class StudyModel // Preferences. protected BaseObjectiveFunction.OptimizerType preferredOptimizerType; + // Statistics saved from the most recent call to optimizeInstrument + + protected double initialNorm; // Initial value of objective function. + protected double finalNorm; // Final value of objective function. + /** * Tree of selectable categories that the study model supports. */ @@ -94,6 +99,15 @@ public void setCategorySelection(Category category, String subCategoryName) } } + /** + * Class to encapsulate a main branch of the study model selection tree. + * The derived study model defines a set of main branches, typically + * a static set. + * At present, this class is public, to allow StudyView to display + * and select items in the category tree. Should be changed to + * expose only category names, not the Category type. + * + */ public static class Category { private String name; @@ -130,7 +144,11 @@ public void removeSub(String name) public Map<String, Object> getSubs() { - return subs == null ? new TreeMap<String, Object>() : subs; + if (subs == null) + { + subs = new TreeMap<String, Object>(); + } + return subs; } public void setSelectedSub(String key) @@ -145,6 +163,10 @@ public String getSelectedSub() public Object getSelectedSubValue() { + if (subs == null) + { + return null; + } return subs.get(selectedSub); } @@ -153,6 +175,10 @@ public void replaceSub(String newName, FileDataModel source) // Find sub by matching dataModel reference String oldName = null; boolean isSelected = false; + if (subs == null) + { + subs = new TreeMap<String, Object>(); + } for (Map.Entry<String, Object> entry : subs.entrySet()) { FileDataModel model = (FileDataModel) entry.getValue(); @@ -178,6 +204,113 @@ public void replaceSub(String newName, FileDataModel source) } } + protected static String getCategoryName(String xmlString) + { + // Check for an Instrument + BindFactory bindFactory = GeometryBindFactory.getInstance(); + if (bindFactory.isValidXml(xmlString, "Instrument", true)) // TODO Make + // constants + // in + // binding + // framework + { + return INSTRUMENT_CATEGORY_ID; + } + + // Check for a Tuning + bindFactory = NoteBindFactory.getInstance(); + if (bindFactory.isValidXml(xmlString, "Tuning", true)) // TODO Make + // constants in + // binding + // framework + { + return TUNING_CATEGORY_ID; + } + + return null; + } + + /** + * Add an Instrument or Tuning to the category tree, from a JIDE FileDataModel. + * Post: If dataModel is valid XML, it is added to INSTRUMENT_CATEGORY_ID, + * or TUNING_CATEGORY_ID, as appropriate, and addDataModel returns true. + * @param dataModel - FileDataModel containing instrument or tuning XML. + * @return true if the dataModel contained valid instrument or tuning XML. + */ + public boolean addDataModel(FileDataModel dataModel) + { + String data = (String) dataModel.getData(); + String categoryName = getCategoryName(data); + if (categoryName == null) + { + return false; + } + Category category = getCategory(categoryName); + category.addSub(dataModel.getName(), dataModel); + category.setSelectedSub(dataModel.getName()); + return true; + } + + /** + * Remove an Instrument or Tuning from the category tree, + * given a JIDE FileDataModel. + * Pre: Assumes that the type of XML, Instrument or Tuning, + * has not changed since the call to addDataModel. + * Post: The specified dataModel is no longer in INSTRUMENT_CATEGORY_ID, + * or TUNING_CATEGORY_ID, as appropriate. + * @param dataModel - FileDataModel containing instrument or tuning XML. + * @return true. + */ + public boolean removeDataModel(FileDataModel dataModel) + { + String data = (String) dataModel.getData(); + String categoryName = getCategoryName(data); + Category category; + if (categoryName == null) + { + // Invalid XML. Remove from both categories. + category = getCategory(INSTRUMENT_CATEGORY_ID); + category.removeSub(dataModel.getName()); + category = getCategory(TUNING_CATEGORY_ID); + category.removeSub(dataModel.getName()); + return true; + } + category = getCategory(categoryName); + category.removeSub(dataModel.getName()); + return true; + } + + /** + * Add an Instrument or Tuning to the category tree, from a JIDE FileDataModel, + * replacing any existing instance. + * Pre: Assumes that the type of XML, Instrument or Tuning, + * has not changed since the call to addDataModel (if any). + * Post: The prior instance of dataModel is removed from INSTRUMENT_CATEGORY_ID, + * or TUNING_CATEGORY_ID, as appropriate + * If dataModel is valid XML, it is added to INSTRUMENT_CATEGORY_ID, + * or TUNING_CATEGORY_ID, as appropriate, and addDataModel returns true. + * @param dataModel - FileDataModel containing instrument or tuning XML. + * @return true if the dataModel contained valid instrument or tuning XML. + */ + public boolean replaceDataModel(FileDataModel dataModel) + { + String data = (String) dataModel.getData(); + String categoryName = getCategoryName(data); + if (categoryName == null) + { + removeDataModel(dataModel); + return false; + } + Category category = getCategory(categoryName); + category.replaceSub(dataModel.getName(), dataModel); + category.setSelectedSub(dataModel.getName()); + return true; + } + + /** + * @return true if category selections are sufficient for calls to + * calculateTuning() and graphTuning(). + */ public boolean canTune() { Category tuningCategory = getCategory(TUNING_CATEGORY_ID); @@ -189,6 +322,10 @@ public boolean canTune() return tuningSelected != null && instrumentSelected != null; } + /** + * @return true if category selections are sufficient for calls to + * optimizeInstrument(). + */ public boolean canOptimize() { if ( ! canTune() ) @@ -207,15 +344,11 @@ public void calculateTuning(String title) throws Exception Category category = this.getCategory(INSTRUMENT_CATEGORY_ID); String instrumentName = category.getSelectedSub(); - FileDataModel model = (FileDataModel) category.getSelectedSubValue(); - model.getApplication().getDataView(model).updateModel(model); - tuner.setInstrument((String) model.getData()); + tuner.setInstrument(getSelectedXmlString(INSTRUMENT_CATEGORY_ID)); category = getCategory(TUNING_CATEGORY_ID); String tuningName = category.getSelectedSub(); - model = (FileDataModel) category.getSelectedSubValue(); - model.getApplication().getDataView(model).updateModel(model); - tuner.setTuning((String) model.getData()); + tuner.setTuning(getSelectedXmlString(TUNING_CATEGORY_ID)); tuner.setCalculator(getCalculator()); @@ -229,15 +362,11 @@ public void graphTuning(String title) throws Exception Category category = this.getCategory(INSTRUMENT_CATEGORY_ID); String instrumentName = category.getSelectedSub(); - FileDataModel model = (FileDataModel) category.getSelectedSubValue(); - model.getApplication().getDataView(model).updateModel(model); - tuner.setInstrument((String) model.getData()); + tuner.setInstrument(getSelectedXmlString(INSTRUMENT_CATEGORY_ID)); category = getCategory(TUNING_CATEGORY_ID); String tuningName = category.getSelectedSub(); - model = (FileDataModel) category.getSelectedSubValue(); - model.getApplication().getDataView(model).updateModel(model); - tuner.setTuning((String) model.getData()); + tuner.setTuning(getSelectedXmlString(TUNING_CATEGORY_ID)); tuner.setCalculator(getCalculator()); @@ -260,12 +389,16 @@ public String optimizeInstrument() throws Exception optimizerType = preferredOptimizerType; } + initialNorm = 1.0; + finalNorm = 1.0; if ( ObjectiveFunctionOptimizer.optimizeObjectiveFunction(objective, optimizerType) ) { Instrument instrument = objective.getInstrument(); // Convert back to the input unit-of-measure values instrument.convertToLengthType(); String xmlString = marshal(instrument); + initialNorm = ObjectiveFunctionOptimizer.getInitialNorm(); + finalNorm = ObjectiveFunctionOptimizer.getFinalNorm(); return xmlString; } return null; @@ -289,8 +422,8 @@ public void compareInstrument(String newName, Instrument newInstrument) throws E table.buildTable(oldName, oldInstrument, newName, newInstrument); table.showTable(false); } - - protected String marshal(Instrument instrument) throws Exception + + public static String marshal(Instrument instrument) throws Exception { BindFactory binder = GeometryBindFactory.getInstance(); StringWriter writer = new StringWriter(); @@ -299,13 +432,27 @@ protected String marshal(Instrument instrument) throws Exception return writer.toString(); } + public static String marshal(Tuning tuning) throws Exception + { + BindFactory binder = NoteBindFactory.getInstance(); + StringWriter writer = new StringWriter(); + binder.marshalToXml(tuning, writer); + + return writer.toString(); + } + protected String getSelectedXmlString(String categoryName) throws Exception { String xmlString = null; Category category = getCategory(categoryName); FileDataModel model = (FileDataModel) category.getSelectedSubValue(); - model.getApplication().getDataView(model).updateModel(model); + if (model.getApplication() != null) + { + // If the file is a data view in an active application, + // update the data in model with the latest from the application's data view. + model.getApplication().getDataView(model).updateModel(model); + } xmlString = (String) model.getData(); return xmlString; @@ -320,7 +467,7 @@ protected Instrument getInstrument() throws Exception return instrument; } - protected Instrument getInstrument(String xmlString) + public static Instrument getInstrument(String xmlString) { try { @@ -344,6 +491,28 @@ protected Tuning getTuning() throws Exception return tuning; } + public static Instrument getInstrumentFromFile(String fileName) throws Exception + { + BindFactory geometryBindFactory = GeometryBindFactory.getInstance(); + String inputPath = BindFactory.getPathFromName(fileName); + File inputFile = new File(inputPath); + Instrument instrument = (Instrument) geometryBindFactory.unmarshalXml( + inputFile, true); + instrument.updateComponents(); + + return instrument; + } + + public static Tuning getTuningFromFile(String fileName) throws Exception + { + BindFactory noteBindFactory = NoteBindFactory.getInstance(); + String inputPath = BindFactory.getPathFromName(fileName); + File inputFile = new File(inputPath); + Tuning tuning = (Tuning) noteBindFactory.unmarshalXml(inputFile, true); + + return tuning; + } + public PhysicalParameters getParams() { return params; @@ -400,6 +569,23 @@ else if ( optimizerPreference.contentEquals(OptimizationPreferences.OPT_POWELL_N preferredOptimizerType = null; } } + + // Methods to return statistics from an optimization. + + public double getInitialNorm() + { + return initialNorm; + } + + public double getFinalNorm() + { + return finalNorm; + } + + public double getResidualErrorRatio() + { + return finalNorm/initialNorm; + } // Methods to create objects that will perform this study, // according to components that the user has selected. diff --git a/WWIDesigner/src/main/com/wwidesigner/gui/StudyView.java b/WWIDesigner/src/main/com/wwidesigner/gui/StudyView.java index a120f20..99cbe92 100644 --- a/WWIDesigner/src/main/com/wwidesigner/gui/StudyView.java +++ b/WWIDesigner/src/main/com/wwidesigner/gui/StudyView.java @@ -19,7 +19,6 @@ import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; -import com.jidesoft.app.framework.BasicDataModel; import com.jidesoft.app.framework.DataModel; import com.jidesoft.app.framework.event.EventSubscriber; import com.jidesoft.app.framework.event.SubscriberEvent; @@ -28,10 +27,7 @@ import com.jidesoft.app.framework.gui.filebased.FileBasedApplication; import com.jidesoft.tree.TreeUtils; import com.wwidesigner.geometry.Instrument; -import com.wwidesigner.geometry.bind.GeometryBindFactory; import com.wwidesigner.gui.StudyModel.Category; -import com.wwidesigner.note.bind.NoteBindFactory; -import com.wwidesigner.util.BindFactory; /** * @author kort @@ -149,60 +145,39 @@ protected void updateActions() public void doEvent(SubscriberEvent event) { String eventId = event.getEvent(); - DataModel source = (DataModel) event.getSource(); - if (source instanceof FileDataModel) + Object eventSource = event.getSource(); + if (eventSource instanceof FileDataModel) { - String data = (String) ((FileDataModel) source).getData(); - String categoryName = getCategoryName(data); - if (categoryName != null) + FileDataModel source = (FileDataModel) eventSource; + switch (eventId) { - Category category = study.getCategory(categoryName); - String subName = source.getName(); - switch (eventId) - { - case NafOptimizationRunner.FILE_OPENED_EVENT_ID: - category.addSub(subName, source); - category.setSelectedSub(subName); - break; - case NafOptimizationRunner.FILE_CLOSED_EVENT_ID: - category.removeSub(subName); - break; - case NafOptimizationRunner.FILE_SAVED_EVENT_ID: - case NafOptimizationRunner.WINDOW_RENAMED_EVENT_ID: - category.replaceSub(subName, (FileDataModel) source); - break; - } - updateView(); + case NafOptimizationRunner.FILE_OPENED_EVENT_ID: + if (! study.addDataModel(source)) + { + System.out.print("\nError: Data in editor tab, "); + System.out.print(source.getName()); + System.out.println(", is not valid Instrument or Tuning XML."); + System.out.println("Fix and close the file, then re-open it."); + } + break; + case NafOptimizationRunner.FILE_CLOSED_EVENT_ID: + study.removeDataModel(source); + break; + case NafOptimizationRunner.FILE_SAVED_EVENT_ID: + case NafOptimizationRunner.WINDOW_RENAMED_EVENT_ID: + if (! study.replaceDataModel(source)) + { + System.out.print("\nError: Data in editor tab, "); + System.out.print(source.getName()); + System.out.println(", is not valid Instrument or Tuning XML."); + System.out.println("Fix and close the file, then re-open it."); + } + break; } + updateView(); } } - protected String getCategoryName(String xmlString) - { - // Check Instrument - BindFactory bindFactory = GeometryBindFactory.getInstance(); - if (bindFactory.isValidXml(xmlString, "Instrument", true)) // TODO Make - // constants - // in - // binding - // framework - { - return StudyModel.INSTRUMENT_CATEGORY_ID; - } - - // Check Tuning - bindFactory = NoteBindFactory.getInstance(); - if (bindFactory.isValidXml(xmlString, "Tuning", true)) // TODO Make - // constants in - // binding - // framework - { - return StudyModel.TUNING_CATEGORY_ID; - } - - return null; - } - public void getTuning() { try @@ -237,9 +212,10 @@ public void optimizeInstrument() if (xmlInstrument != null && ! xmlInstrument.isEmpty()) { FileBasedApplication app = (FileBasedApplication) getApplication(); - DataModel data = app.newData("xml"); - ((BasicDataModel)data).setData(xmlInstrument); - addDataModelToStudy(data); + FileDataModel data = (FileDataModel) app.newData("xml"); + data.setData(xmlInstrument); + study.addDataModel(data); + updateView(); } } catch (Exception e) @@ -261,7 +237,7 @@ public void compareInstrument() if (view != null) { String xmlInstrument2 = view.getText(); - Instrument instrument2 = study.getInstrument(xmlInstrument2); + Instrument instrument2 = StudyModel.getInstrument(xmlInstrument2); if (instrument2 == null) { System.out.print("\nError: Current editor tab, "); @@ -281,21 +257,6 @@ public void compareInstrument() } } - private void addDataModelToStudy(DataModel dataModel) - { - if (dataModel instanceof FileDataModel) - { - String data = (String) ((FileDataModel) dataModel).getData(); - String categoryName = getCategoryName(data); - if (categoryName != null) - { - Category category = study.getCategory(categoryName); - category.addSub(dataModel.getName(), dataModel); - updateView(); - } - } - } - public StudyModel getStudyModel() { return study; @@ -306,13 +267,22 @@ public StudyModel getStudyModel() */ public void setStudyModel(StudyModel study) { - DataModel[] models = getApplication().getDataModels(); this.study = study; - updateView(); + + DataModel[] models = getApplication().getDataModels(); for ( DataModel model : models ) { - addDataModelToStudy(model); + if (model instanceof FileDataModel) + { + if (! study.addDataModel((FileDataModel) model)) + { + System.out.print("\nError: Data in editor tab, "); + System.out.print(model.getName()); + System.out.println(", is not valid Instrument or Tuning XML."); + } + } } + updateView(); } /**
c30c9f9f4d9f9bd9a76593ac0053e43bbb5e9cb3
getrailo$railo
extended the ImageFilter functionality
p
https://github.com/getrailo/railo
diff --git a/railo-java/railo-core/src/railo/runtime/functions/image/ImageFilter.java b/railo-java/railo-core/src/railo/runtime/functions/image/ImageFilter.java index e524cc5b10..eb51361b3e 100644 --- a/railo-java/railo-core/src/railo/runtime/functions/image/ImageFilter.java +++ b/railo-java/railo-core/src/railo/runtime/functions/image/ImageFilter.java @@ -51,7 +51,7 @@ public class ImageFilter { filters.put("chromakey",ChromaKeyFilter.class); filters.put("chrome",ChromeFilter.class); filters.put("circle",CircleFilter.class); - filters.put("composite",CompositeFilter.class); + ////////filters.put("composite",CompositeFilter.class); //filters.put("compound",CompoundFilter.class); filters.put("contour",ContourFilter.class); filters.put("contrast",ContrastFilter.class); diff --git a/railo-java/railo-core/src/railo/runtime/functions/image/ImageColorMap.java b/railo-java/railo-core/src/railo/runtime/functions/image/ImageFilterColorMap.java similarity index 81% rename from railo-java/railo-core/src/railo/runtime/functions/image/ImageColorMap.java rename to railo-java/railo-core/src/railo/runtime/functions/image/ImageFilterColorMap.java index d416c0a930..ac9b7da467 100644 --- a/railo-java/railo-core/src/railo/runtime/functions/image/ImageColorMap.java +++ b/railo-java/railo-core/src/railo/runtime/functions/image/ImageFilterColorMap.java @@ -11,7 +11,7 @@ import railo.runtime.img.filter.LinearColormap; import railo.runtime.img.filter.SpectrumColormap; -public class ImageColorMap { +public class ImageFilterColorMap { public static Object call(PageContext pc, String type) throws PageException { return call(pc, type, null, null); } @@ -35,10 +35,10 @@ else if(!isEmpty1 && !isEmpty2) { return new LinearColormap(color1.getRGB(),color2.getRGB()); } else - throw new FunctionException(pc, "ImageColorMap", 2, "lineColor1", "when you define linecolor1 you have to define linecolor2 as well"); + throw new FunctionException(pc, "ImageFilterColorMap", 2, "lineColor1", "when you define linecolor1 you have to define linecolor2 as well"); } - else throw new FunctionException(pc, "ImageColorMap", 1, "type", "invalid type defintion, valid types are [grayscale,spectrum,linear]"); + else throw new FunctionException(pc, "ImageFilterColorMap", 1, "type", "invalid type defintion, valid types are [grayscale,spectrum,linear]"); diff --git a/railo-java/railo-core/src/railo/runtime/functions/image/ImageFilterCurves.java b/railo-java/railo-core/src/railo/runtime/functions/image/ImageFilterCurves.java new file mode 100644 index 0000000000..4ce5c38df9 --- /dev/null +++ b/railo-java/railo-core/src/railo/runtime/functions/image/ImageFilterCurves.java @@ -0,0 +1,11 @@ +package railo.runtime.functions.image; + +import railo.runtime.PageContext; +import railo.runtime.exp.PageException; +import railo.runtime.img.filter.CurvesFilter; + +public class ImageFilterCurves { + public static Object call(PageContext pc) throws PageException { + return new CurvesFilter.Curve(); + } +} diff --git a/railo-java/railo-core/src/railo/runtime/functions/image/ImageFilterKernel.java b/railo-java/railo-core/src/railo/runtime/functions/image/ImageFilterKernel.java new file mode 100644 index 0000000000..d74c533e64 --- /dev/null +++ b/railo-java/railo-core/src/railo/runtime/functions/image/ImageFilterKernel.java @@ -0,0 +1,92 @@ +package railo.runtime.functions.image; + +import java.awt.image.Kernel; + +import railo.runtime.PageContext; +import railo.runtime.exp.FunctionException; +import railo.runtime.exp.PageException; +import railo.runtime.op.Caster; +import railo.runtime.op.Decision; + +public class ImageFilterKernel { + public static Object call(PageContext pc, double width, double height, Object oData) throws PageException { + + float[] data=null; + if(oData instanceof float[]) + data=(float[]) oData; + else if(Decision.isNativeArray(oData)) { + data=toFloatArray(pc,oData); + } + else if(Decision.isArray(oData)) { + data=toFloatArray(pc,Caster.toNativeArray(oData)); + } + else + throw new FunctionException(pc, "", 3, "data", "cannot cast data to a float array"); + + return new Kernel(Caster.toIntValue(width),Caster.toIntValue(height),data); + } + + private static float[] toFloatArray(PageContext pc,Object oData) throws PageException { + float[] data=null; + // Object[] + if(oData instanceof Object[]) { + Object[] arr = ((Object[])oData); + data=new float[arr.length]; + for(int i=0;i<arr.length;i++){ + data[i]=Caster.toFloatValue(arr[i]); + } + } + // boolean[] + else if(oData instanceof boolean[]) { + boolean[] arr = ((boolean[])oData); + data=new float[arr.length]; + for(int i=0;i<arr.length;i++){ + data[i]=Caster.toFloatValue(arr[i]); + } + } + // byte[] + else if(oData instanceof byte[]) { + byte[] arr = ((byte[])oData); + data=new float[arr.length]; + for(int i=0;i<arr.length;i++){ + data[i]=Caster.toFloatValue(arr[i]); + } + } + // short[] + else if(oData instanceof short[]) { + short[] arr = ((short[])oData); + data=new float[arr.length]; + for(int i=0;i<arr.length;i++){ + data[i]=Caster.toFloatValue(arr[i]); + } + } + // long[] + else if(oData instanceof long[]) { + long[] arr = ((long[])oData); + data=new float[arr.length]; + for(int i=0;i<arr.length;i++){ + data[i]=Caster.toFloatValue(arr[i]); + } + } + // int[] + else if(oData instanceof int[]) { + int[] arr = ((int[])oData); + data=new float[arr.length]; + for(int i=0;i<arr.length;i++){ + data[i]=Caster.toFloatValue(arr[i]); + } + } + // double[] + else if(oData instanceof double[]) { + double[] arr = ((double[])oData); + data=new float[arr.length]; + for(int i=0;i<arr.length;i++){ + data[i]=Caster.toFloatValue(arr[i]); + } + } + else + throw new FunctionException(pc, "", 3, "data", "cannot cast data to a float array"); + + return data; + } +} diff --git a/railo-java/railo-core/src/railo/runtime/functions/image/ImageFilterWarpGrid.java b/railo-java/railo-core/src/railo/runtime/functions/image/ImageFilterWarpGrid.java new file mode 100644 index 0000000000..df11afbf1d --- /dev/null +++ b/railo-java/railo-core/src/railo/runtime/functions/image/ImageFilterWarpGrid.java @@ -0,0 +1,13 @@ +package railo.runtime.functions.image; + +import railo.runtime.PageContext; +import railo.runtime.exp.PageException; +import railo.runtime.img.filter.WarpGrid; +import railo.runtime.op.Caster; + +public class ImageFilterWarpGrid { + + public static Object call(PageContext pc, double rows, double cols, double width, double height) throws PageException { + return new WarpGrid(Caster.toIntValue(rows), Caster.toIntValue(cols), Caster.toIntValue(width), Caster.toIntValue(height)); + } +} diff --git a/railo-java/railo-core/src/railo/runtime/img/filter/BorderFilter.java b/railo-java/railo-core/src/railo/runtime/img/filter/BorderFilter.java index 426e8950ed..d9e89c4858 100644 --- a/railo-java/railo-core/src/railo/runtime/img/filter/BorderFilter.java +++ b/railo-java/railo-core/src/railo/runtime/img/filter/BorderFilter.java @@ -15,6 +15,7 @@ */ package railo.runtime.img.filter; +import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.geom.AffineTransform; @@ -135,12 +136,11 @@ public int getBottomBorder() { } /** - * Set the border paint. - * @param borderPaint the paint with which to fill the border - * @see #getBorderPaint + * Set the border color. + * @param borderColor the color with which to fill the border */ - public void setBorderPaint( Paint borderPaint ) { - this.borderPaint = borderPaint; + public void setBorderColor( Color borderColor ) { + this.borderPaint = borderColor; } /** @@ -184,7 +184,7 @@ public BufferedImage filter(BufferedImage src, BufferedImage dst ,Struct paramet if((o=parameters.removeEL(KeyImpl.init("RightBorder")))!=null)setRightBorder(ImageFilterUtil.toIntValue(o,"RightBorder")); if((o=parameters.removeEL(KeyImpl.init("TopBorder")))!=null)setTopBorder(ImageFilterUtil.toIntValue(o,"TopBorder")); if((o=parameters.removeEL(KeyImpl.init("BottomBorder")))!=null)setBottomBorder(ImageFilterUtil.toIntValue(o,"BottomBorder")); - if((o=parameters.removeEL(KeyImpl.init("BorderPaint")))!=null)setBorderPaint(ImageFilterUtil.toColor(o,"BorderPaint")); + if((o=parameters.removeEL(KeyImpl.init("BorderColor")))!=null)setBorderColor(ImageFilterUtil.toColor(o,"BorderColor")); // check for arguments not supported if(parameters.size()>0) { diff --git a/railo-java/railo-core/src/railo/runtime/img/filter/CircleFilter.java b/railo-java/railo-core/src/railo/runtime/img/filter/CircleFilter.java index 7de52008f4..30607dc7ca 100644 --- a/railo-java/railo-core/src/railo/runtime/img/filter/CircleFilter.java +++ b/railo-java/railo-core/src/railo/runtime/img/filter/CircleFilter.java @@ -212,7 +212,7 @@ public BufferedImage filter(BufferedImage src, BufferedImage dst ,Struct paramet if((o=parameters.removeEL(KeyImpl.init("SpreadAngle")))!=null)setSpreadAngle(ImageFilterUtil.toFloatValue(o,"SpreadAngle")); if((o=parameters.removeEL(KeyImpl.init("CentreX")))!=null)setCentreX(ImageFilterUtil.toFloatValue(o,"CentreX")); if((o=parameters.removeEL(KeyImpl.init("CentreY")))!=null)setCentreY(ImageFilterUtil.toFloatValue(o,"CentreY")); - if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); + //if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); if((o=parameters.removeEL(KeyImpl.init("Height")))!=null)setHeight(ImageFilterUtil.toFloatValue(o,"Height")); if((o=parameters.removeEL(KeyImpl.init("EdgeAction")))!=null)setEdgeAction(ImageFilterUtil.toIntValue(o,"EdgeAction")); if((o=parameters.removeEL(KeyImpl.init("Interpolation")))!=null)setInterpolation(ImageFilterUtil.toIntValue(o,"Interpolation")); diff --git a/railo-java/railo-core/src/railo/runtime/img/filter/FeedbackFilter.java b/railo-java/railo-core/src/railo/runtime/img/filter/FeedbackFilter.java index aedd0f87f3..43671f35f3 100644 --- a/railo-java/railo-core/src/railo/runtime/img/filter/FeedbackFilter.java +++ b/railo-java/railo-core/src/railo/runtime/img/filter/FeedbackFilter.java @@ -296,7 +296,7 @@ public BufferedImage filter(BufferedImage src, BufferedImage dst ,Struct paramet if((o=parameters.removeEL(KeyImpl.init("Angle")))!=null)setAngle(ImageFilterUtil.toFloatValue(o,"Angle")); if((o=parameters.removeEL(KeyImpl.init("CentreX")))!=null)setCentreX(ImageFilterUtil.toFloatValue(o,"CentreX")); if((o=parameters.removeEL(KeyImpl.init("CentreY")))!=null)setCentreY(ImageFilterUtil.toFloatValue(o,"CentreY")); - if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); + //if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); if((o=parameters.removeEL(KeyImpl.init("Distance")))!=null)setDistance(ImageFilterUtil.toFloatValue(o,"Distance")); if((o=parameters.removeEL(KeyImpl.init("Rotation")))!=null)setRotation(ImageFilterUtil.toFloatValue(o,"Rotation")); if((o=parameters.removeEL(KeyImpl.init("Zoom")))!=null)setZoom(ImageFilterUtil.toFloatValue(o,"Zoom")); diff --git a/railo-java/railo-core/src/railo/runtime/img/filter/FlareFilter.java b/railo-java/railo-core/src/railo/runtime/img/filter/FlareFilter.java index d15a0428d6..62b22cdb76 100644 --- a/railo-java/railo-core/src/railo/runtime/img/filter/FlareFilter.java +++ b/railo-java/railo-core/src/railo/runtime/img/filter/FlareFilter.java @@ -93,10 +93,18 @@ public float getRayAmount() { return rayAmount; } - public void setCentre( Point2D centre ) { + public void setCentreY( float centreY ) { + this.centreY = centreY; + } + + public void setCentreX( float centreX ) { + this.centreX = centreX; + } + + /*public void setCentre( Point2D centre ) { this.centreX = (float)centre.getX(); this.centreY = (float)centre.getY(); - } + }*/ public Point2D getCentre() { return new Point2D.Float( centreX, centreY ); @@ -170,7 +178,7 @@ public String toString() { public BufferedImage filter(BufferedImage src, BufferedImage dst ,Struct parameters) throws PageException { Object o; if((o=parameters.removeEL(KeyImpl.init("Radius")))!=null)setRadius(ImageFilterUtil.toFloatValue(o,"Radius")); - if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); + //if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); if((o=parameters.removeEL(KeyImpl.init("RingWidth")))!=null)setRingWidth(ImageFilterUtil.toFloatValue(o,"RingWidth")); if((o=parameters.removeEL(KeyImpl.init("BaseAmount")))!=null)setBaseAmount(ImageFilterUtil.toFloatValue(o,"BaseAmount")); if((o=parameters.removeEL(KeyImpl.init("RingAmount")))!=null)setRingAmount(ImageFilterUtil.toFloatValue(o,"RingAmount")); diff --git a/railo-java/railo-core/src/railo/runtime/img/filter/ImageFilterUtil.java b/railo-java/railo-core/src/railo/runtime/img/filter/ImageFilterUtil.java index d11df6d971..3c7d2159e9 100644 --- a/railo-java/railo-core/src/railo/runtime/img/filter/ImageFilterUtil.java +++ b/railo-java/railo-core/src/railo/runtime/img/filter/ImageFilterUtil.java @@ -15,8 +15,11 @@ import railo.runtime.exp.FunctionException; import railo.runtime.exp.PageException; import railo.runtime.img.Image; +import railo.runtime.img.filter.CurvesFilter.Curve; +import railo.runtime.img.filter.LightFilter.Material; import railo.runtime.img.math.Function2D; import railo.runtime.op.Caster; +import railo.runtime.type.List; import railo.runtime.type.Struct; import railo.runtime.type.util.Type; @@ -55,13 +58,14 @@ public static String toString(Object value, String argName) throws FunctionExcep public static BufferedImage toBufferedImage(Object o, String argName) throws PageException { + if(o instanceof BufferedImage) return (BufferedImage) o; return Image.toImage(o).getBufferedImage(); } public static Colormap toColormap(Object value, String argName) throws FunctionException { if(value instanceof Colormap) return (Colormap) value; - throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", msg(value,"Colormap",argName)+" use function ImageColorMap to create a colormap"); + throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", msg(value,"Colormap",argName)+" use function ImageFilterColorMap to create a colormap"); } public static Kernel toKernel(Object value, String argName) throws FunctionException { @@ -81,6 +85,25 @@ public static int toColorRGB(Object value, String argName) throws PageException return toColor(value, argName).getRGB(); } + + + + public static Point toPoint(Object value, String argName) throws PageException { + if(value instanceof Point) return (Point) value; + String str = Caster.toString(value); + + Struct sct = Caster.toStruct(value,null); + if(sct!=null){ + return new Point(Caster.toIntValue(sct.get("x")),Caster.toIntValue(sct.get("y"))); + } + + String[] arr = List.listToStringArray(str, ','); + if(arr.length==2) { + return new Point(Caster.toIntValue(arr[0]),Caster.toIntValue(arr[1])); + } + throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "use the following format [x,y]"); + + } public static int[] toDimensions(Object value, String argName) throws FunctionException { throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "type int[] not supported yet!"); @@ -91,30 +114,33 @@ public static int[] toDimensions(Object value, String argName) throws FunctionEx return (LightFilter.Material) value; Struct sct = Caster.toStruct(value,null); - if(sct==null) - throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", msg(value,"Struct",argName)); - + if(sct!=null){ + Material material = new LightFilter.Material(); + material.setDiffuseColor(Caster.toIntValue(sct.get("color"))); + material.setOpacity(Caster.toFloatValue(sct.get("opacity"))); + return material; + } + String str = Caster.toString(value,null); + if(str!=null){ + String[] arr = List.listToStringArray(str, ','); + if(arr.length==2) { + Material material = new LightFilter.Material(); + material.setDiffuseColor(Caster.toIntValue(arr[0])); + material.setOpacity(Caster.toFloatValue(arr[1])); + return material; + } + throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "use the following format [color,opacity]"); + + } - LightFilter.Material mat=new LightFilter.Material(); - Object o = sct.get("DiffuseColor",null); - if(o==null) - throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "missing key [DiffuseColor] in struct of parameter ["+argName+"]"); - mat.setDiffuseColor(ColorCaster.toColor(Caster.toString(o)).getRGB()); - o = sct.get("Opacity",null); - if(o==null) - throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "missing key [Opacity] in struct of parameter ["+argName+"]"); - mat.setOpacity((Caster.toFloatValue(o))); + throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "use the following format [\"color,opacity\"] or [{color='#cc0033',opacity=0.5}]"); - return mat; } public static Function2D toFunction2D(Object value, String argName) throws FunctionException { throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "type Function2D not supported yet!"); } - public static Point2D toPoint2D(Object value, String argName) throws FunctionException { - throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "type AffineTransform not supported yet!"); - } public static AffineTransform toAffineTransform(Object value, String argName) throws FunctionException { throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "type BufferedImage not supported yet!"); @@ -124,12 +150,20 @@ public static Composite toComposite(Object value, String argName) throws Functio throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "type Composite not supported yet!"); } - public static CurvesFilter.Curve[] toACurvesFilter$Curve(Object value, String argName) throws FunctionException { - throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "type CurvesFilter.Curve[] not supported yet!"); + public static CurvesFilter.Curve[] toACurvesFilter$Curve(Object value, String argName) throws PageException { + if(value instanceof CurvesFilter.Curve[]) return (CurvesFilter.Curve[]) value; + Object[] arr = Caster.toNativeArray(value); + CurvesFilter.Curve[] curves=new CurvesFilter.Curve[arr.length]; + for(int i=0;i<arr.length;i++){ + curves[i]=toCurvesFilter$Curve(arr[i],argName); + } + return curves; } public static CurvesFilter.Curve toCurvesFilter$Curve(Object value, String argName) throws FunctionException { - throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "type CurvesFilter.Curve not supported yet!"); + if(value instanceof CurvesFilter.Curve) + return (CurvesFilter.Curve) value; + throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", msg(value,"Curve",argName)+" use function ImageFilterCurve to create a Curve"); } public static int[] toAInt(Object value, String argName) throws FunctionException { @@ -145,7 +179,9 @@ public static int[][] toAAInt(Object value, String argName) throws FunctionExcep } public static WarpGrid toWarpGrid(Object value, String argName) throws FunctionException { - throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", "type WarpGrid not supported yet!"); + if(value instanceof WarpGrid) + return (WarpGrid) value; + throw new FunctionException(ThreadLocalPageContext.get(), "ImageFilter", 3, "parameters", msg(value,"WarpGrid",argName)+" use function ImageFilterWarpGrid to create a WarpGrid"); } public static FieldWarpFilter.Line[] toAFieldWarpFilter$Line(Object o, String string) throws FunctionException { @@ -165,11 +201,6 @@ public static Font toFont(Object o, String string) { return null; } - public static Point toPoint(Object o, String string) { - // TODO Auto-generated method stub - return null; - } - diff --git a/railo-java/railo-core/src/railo/runtime/img/filter/KaleidoscopeFilter.java b/railo-java/railo-core/src/railo/runtime/img/filter/KaleidoscopeFilter.java index d74e018e16..2aa806a9cd 100644 --- a/railo-java/railo-core/src/railo/runtime/img/filter/KaleidoscopeFilter.java +++ b/railo-java/railo-core/src/railo/runtime/img/filter/KaleidoscopeFilter.java @@ -211,7 +211,7 @@ public BufferedImage filter(BufferedImage src, BufferedImage dst ,Struct paramet if((o=parameters.removeEL(KeyImpl.init("Angle")))!=null)setAngle(ImageFilterUtil.toFloatValue(o,"Angle")); if((o=parameters.removeEL(KeyImpl.init("CentreX")))!=null)setCentreX(ImageFilterUtil.toFloatValue(o,"CentreX")); if((o=parameters.removeEL(KeyImpl.init("CentreY")))!=null)setCentreY(ImageFilterUtil.toFloatValue(o,"CentreY")); - if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); + //if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); if((o=parameters.removeEL(KeyImpl.init("Sides")))!=null)setSides(ImageFilterUtil.toIntValue(o,"Sides")); if((o=parameters.removeEL(KeyImpl.init("Angle2")))!=null)setAngle2(ImageFilterUtil.toFloatValue(o,"Angle2")); if((o=parameters.removeEL(KeyImpl.init("EdgeAction")))!=null)setEdgeAction(ImageFilterUtil.toIntValue(o,"EdgeAction")); diff --git a/railo-java/railo-core/src/railo/runtime/img/filter/MotionBlurOp.java b/railo-java/railo-core/src/railo/runtime/img/filter/MotionBlurOp.java index 11f15b7e48..57a85768d0 100644 --- a/railo-java/railo-core/src/railo/runtime/img/filter/MotionBlurOp.java +++ b/railo-java/railo-core/src/railo/runtime/img/filter/MotionBlurOp.java @@ -161,16 +161,6 @@ public void setCentreY( float centreY ) { public float getCentreY() { return centreY; } - - /** - * Set the centre of the effect as a proportion of the image size. - * @param centre the center - * @see #getCentre - */ - public void setCentre( Point2D centre ) { - this.centreX = (float)centre.getX(); - this.centreY = (float)centre.getY(); - } /** * Get the centre of the effect as a proportion of the image size. diff --git a/railo-java/railo-core/src/railo/runtime/img/filter/PinchFilter.java b/railo-java/railo-core/src/railo/runtime/img/filter/PinchFilter.java index d8d3fe7128..11be18a2de 100644 --- a/railo-java/railo-core/src/railo/runtime/img/filter/PinchFilter.java +++ b/railo-java/railo-core/src/railo/runtime/img/filter/PinchFilter.java @@ -205,7 +205,7 @@ public BufferedImage filter(BufferedImage src, BufferedImage dst ,Struct paramet if((o=parameters.removeEL(KeyImpl.init("Angle")))!=null)setAngle(ImageFilterUtil.toFloatValue(o,"Angle")); if((o=parameters.removeEL(KeyImpl.init("CentreX")))!=null)setCentreX(ImageFilterUtil.toFloatValue(o,"CentreX")); if((o=parameters.removeEL(KeyImpl.init("CentreY")))!=null)setCentreY(ImageFilterUtil.toFloatValue(o,"CentreY")); - if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); + //if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); if((o=parameters.removeEL(KeyImpl.init("EdgeAction")))!=null)setEdgeAction(ImageFilterUtil.toIntValue(o,"EdgeAction")); if((o=parameters.removeEL(KeyImpl.init("Interpolation")))!=null)setInterpolation(ImageFilterUtil.toIntValue(o,"Interpolation")); diff --git a/railo-java/railo-core/src/railo/runtime/img/filter/RaysFilter.java b/railo-java/railo-core/src/railo/runtime/img/filter/RaysFilter.java index 3b903ffc42..3386abb199 100644 --- a/railo-java/railo-core/src/railo/runtime/img/filter/RaysFilter.java +++ b/railo-java/railo-core/src/railo/runtime/img/filter/RaysFilter.java @@ -214,7 +214,7 @@ public BufferedImage filter(BufferedImage src, BufferedImage dst ,Struct paramet if((o=parameters.removeEL(KeyImpl.init("Angle")))!=null)setAngle(ImageFilterUtil.toFloatValue(o,"Angle")); if((o=parameters.removeEL(KeyImpl.init("CentreX")))!=null)setCentreX(ImageFilterUtil.toFloatValue(o,"CentreX")); if((o=parameters.removeEL(KeyImpl.init("CentreY")))!=null)setCentreY(ImageFilterUtil.toFloatValue(o,"CentreY")); - if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); + //if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); if((o=parameters.removeEL(KeyImpl.init("Distance")))!=null)setDistance(ImageFilterUtil.toFloatValue(o,"Distance")); if((o=parameters.removeEL(KeyImpl.init("Rotation")))!=null)setRotation(ImageFilterUtil.toFloatValue(o,"Rotation")); if((o=parameters.removeEL(KeyImpl.init("Zoom")))!=null)setZoom(ImageFilterUtil.toFloatValue(o,"Zoom")); diff --git a/railo-java/railo-core/src/railo/runtime/img/filter/ShatterFilter.java b/railo-java/railo-core/src/railo/runtime/img/filter/ShatterFilter.java index a664a3c41b..09a1920e6d 100644 --- a/railo-java/railo-core/src/railo/runtime/img/filter/ShatterFilter.java +++ b/railo-java/railo-core/src/railo/runtime/img/filter/ShatterFilter.java @@ -108,11 +108,6 @@ public void setCentreY( float centreY ) { public float getCentreY() { return centreY; } - - public void setCentre( Point2D centre ) { - this.centreX = (float)centre.getX(); - this.centreY = (float)centre.getY(); - } public Point2D getCentre() { return new Point2D.Float( centreX, centreY ); @@ -245,7 +240,7 @@ public BufferedImage filter(BufferedImage src, BufferedImage dst ,Struct paramet if((o=parameters.removeEL(KeyImpl.init("Iterations")))!=null)setIterations(ImageFilterUtil.toIntValue(o,"Iterations")); if((o=parameters.removeEL(KeyImpl.init("CentreX")))!=null)setCentreX(ImageFilterUtil.toFloatValue(o,"CentreX")); if((o=parameters.removeEL(KeyImpl.init("CentreY")))!=null)setCentreY(ImageFilterUtil.toFloatValue(o,"CentreY")); - if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); + //if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); if((o=parameters.removeEL(KeyImpl.init("Transition")))!=null)setTransition(ImageFilterUtil.toFloatValue(o,"Transition")); if((o=parameters.removeEL(KeyImpl.init("Distance")))!=null)setDistance(ImageFilterUtil.toFloatValue(o,"Distance")); if((o=parameters.removeEL(KeyImpl.init("Rotation")))!=null)setRotation(ImageFilterUtil.toFloatValue(o,"Rotation")); diff --git a/railo-java/railo-core/src/railo/runtime/img/filter/SphereFilter.java b/railo-java/railo-core/src/railo/runtime/img/filter/SphereFilter.java index 6ed47488b1..04be9c0f70 100644 --- a/railo-java/railo-core/src/railo/runtime/img/filter/SphereFilter.java +++ b/railo-java/railo-core/src/railo/runtime/img/filter/SphereFilter.java @@ -185,7 +185,7 @@ public BufferedImage filter(BufferedImage src, BufferedImage dst ,Struct paramet if((o=parameters.removeEL(KeyImpl.init("Radius")))!=null)setRadius(ImageFilterUtil.toFloatValue(o,"Radius")); if((o=parameters.removeEL(KeyImpl.init("CentreX")))!=null)setCentreX(ImageFilterUtil.toFloatValue(o,"CentreX")); if((o=parameters.removeEL(KeyImpl.init("CentreY")))!=null)setCentreY(ImageFilterUtil.toFloatValue(o,"CentreY")); - if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); + //if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); if((o=parameters.removeEL(KeyImpl.init("RefractionIndex")))!=null)setRefractionIndex(ImageFilterUtil.toFloatValue(o,"RefractionIndex")); if((o=parameters.removeEL(KeyImpl.init("EdgeAction")))!=null)setEdgeAction(ImageFilterUtil.toIntValue(o,"EdgeAction")); if((o=parameters.removeEL(KeyImpl.init("Interpolation")))!=null)setInterpolation(ImageFilterUtil.toIntValue(o,"Interpolation")); diff --git a/railo-java/railo-core/src/railo/runtime/img/filter/TwirlFilter.java b/railo-java/railo-core/src/railo/runtime/img/filter/TwirlFilter.java index 5c43d8341d..e50b4e82e7 100644 --- a/railo-java/railo-core/src/railo/runtime/img/filter/TwirlFilter.java +++ b/railo-java/railo-core/src/railo/runtime/img/filter/TwirlFilter.java @@ -174,7 +174,7 @@ public BufferedImage filter(BufferedImage src, BufferedImage dst ,Struct paramet if((o=parameters.removeEL(KeyImpl.init("Angle")))!=null)setAngle(ImageFilterUtil.toFloatValue(o,"Angle")); if((o=parameters.removeEL(KeyImpl.init("CentreX")))!=null)setCentreX(ImageFilterUtil.toFloatValue(o,"CentreX")); if((o=parameters.removeEL(KeyImpl.init("CentreY")))!=null)setCentreY(ImageFilterUtil.toFloatValue(o,"CentreY")); - if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); + //if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); if((o=parameters.removeEL(KeyImpl.init("EdgeAction")))!=null)setEdgeAction(ImageFilterUtil.toIntValue(o,"EdgeAction")); if((o=parameters.removeEL(KeyImpl.init("Interpolation")))!=null)setInterpolation(ImageFilterUtil.toIntValue(o,"Interpolation")); diff --git a/railo-java/railo-core/src/railo/runtime/img/filter/WaterFilter.java b/railo-java/railo-core/src/railo/runtime/img/filter/WaterFilter.java index 15df5ef81f..74ca423fb9 100644 --- a/railo-java/railo-core/src/railo/runtime/img/filter/WaterFilter.java +++ b/railo-java/railo-core/src/railo/runtime/img/filter/WaterFilter.java @@ -213,7 +213,7 @@ public BufferedImage filter(BufferedImage src, BufferedImage dst ,Struct paramet if((o=parameters.removeEL(KeyImpl.init("Radius")))!=null)setRadius(ImageFilterUtil.toFloatValue(o,"Radius")); if((o=parameters.removeEL(KeyImpl.init("CentreX")))!=null)setCentreX(ImageFilterUtil.toFloatValue(o,"CentreX")); if((o=parameters.removeEL(KeyImpl.init("CentreY")))!=null)setCentreY(ImageFilterUtil.toFloatValue(o,"CentreY")); - if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); + //if((o=parameters.removeEL(KeyImpl.init("Centre")))!=null)setCentre(ImageFilterUtil.toPoint2D(o,"Centre")); if((o=parameters.removeEL(KeyImpl.init("Wavelength")))!=null)setWavelength(ImageFilterUtil.toFloatValue(o,"Wavelength")); if((o=parameters.removeEL(KeyImpl.init("Amplitude")))!=null)setAmplitude(ImageFilterUtil.toFloatValue(o,"Amplitude")); if((o=parameters.removeEL(KeyImpl.init("Phase")))!=null)setPhase(ImageFilterUtil.toFloatValue(o,"Phase")); diff --git a/railo-java/railo-core/src/railo/runtime/img/math/BinaryFunction.java b/railo-java/railo-core/src/railo/runtime/img/math/BinaryFunction.java index 27071c5241..bed60c5a33 100644 --- a/railo-java/railo-core/src/railo/runtime/img/math/BinaryFunction.java +++ b/railo-java/railo-core/src/railo/runtime/img/math/BinaryFunction.java @@ -1,19 +1,3 @@ -/* -* - -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 railo.runtime.img.math; public interface BinaryFunction { diff --git a/railo-java/railo-core/src/resource/fld/web-cfmfunctionlibrary_1_0 b/railo-java/railo-core/src/resource/fld/web-cfmfunctionlibrary_1_0 index 5f6a01100d..6abf6a31de 100755 --- a/railo-java/railo-core/src/resource/fld/web-cfmfunctionlibrary_1_0 +++ b/railo-java/railo-core/src/resource/fld/web-cfmfunctionlibrary_1_0 @@ -5313,10 +5313,10 @@ Value must be greater than or equal to 3 and less than or equal to 10. The defau <type>void</type> </return> </function> - <!-- ImageColorMap --> + <!-- ImageFilterColorMap --> <function> - <name>ImageColorMap</name> - <class>railo.runtime.functions.image.ImageColorMap</class> + <name>ImageFilterColorMap</name> + <class>railo.runtime.functions.image.ImageFilterColorMap</class> <description>These are passed to the function ImageFilters (see ImageFilter documentation) which convert gray values to colors.</description> <argument> <name>type</name> @@ -5343,6 +5343,81 @@ Value must be greater than or equal to 3 and less than or equal to 10. The defau <type>any</type> </return> </function> + + + <!-- ImageFilterKernel --> + <function> + <name>ImageFilterKernel</name> + <class>railo.runtime.functions.image.ImageFilterKernel</class> + <description>These are passed to the function ImageFilters (see ImageFilter documentation). + The ImageFilterKernel function defines a matrix that describes how a specified pixel and its surrounding pixels affect the value computed for the pixel's position in the output image of a filtering operation. + The X origin and Y origin indicate the kernel matrix element that corresponds to the pixel position for which an output value is being computed. + + </description> + <argument> + <name>width</name> + <type>number</type> + <required>Yes</required> + <description>width of the kernel</description> + </argument> + <argument> + <name>height</name> + <type>number</type> + <required>Yes</required> + <description>height of the kernel</description> + </argument> + <argument> + <name>data</name> + <type>any</type> + <required>Yes</required> + <description>kernel data in row major order</description> + </argument> + <return> + <type>any</type> + </return> + </function> + <!-- ImageFilterWarpGrid --> + <function> + <name>ImageFilterWarpGrid</name> + <class>railo.runtime.functions.image.ImageFilterWarpGrid</class> + <description>A warp grid. These are passed to the function ImageFilters (see ImageFilter documentation).</description> + <argument> + <name>rows</name> + <type>number</type> + <required>Yes</required> + <description>rows of the warp grid</description> + </argument> + <argument> + <name>cols</name> + <type>number</type> + <required>Yes</required> + <description>cols of the warp grid</description> + </argument> + <argument> + <name>width</name> + <type>number</type> + <required>Yes</required> + <description>width of the warp grid</description> + </argument> + <argument> + <name>height</name> + <type>number</type> + <required>Yes</required> + <description>height of the warp grid</description> + </argument> + <return> + <type>any</type> + </return> + </function> + <!-- ImageFilterCurves --> + <function> + <name>ImageFilterCurves</name> + <class>railo.runtime.functions.image.ImageFilterCurves</class> + <description>the curves for the wrap grid</description> + <return> + <type>any</type> + </return> + </function> <!-- ImageCopy --> <function> <name>ImageCopy</name> @@ -6145,7 +6220,7 @@ cellular - f3 (float) - f4 (float) - colormap (Colormap) - The colormap to be used for the filter. Use function ImageColorMap to create. + The colormap to be used for the filter. Use function ImageFilterColorMap to create. - randomness (float) - gridType (int) - distancePower (float) @@ -6303,7 +6378,7 @@ crystallize - f3 (float) - f4 (float) - colormap (Colormap) - The colormap to be used for the filter. Use function ImageColorMap to create. + The colormap to be used for the filter. Use function ImageFilterColorMap to create. - randomness (float) - gridType (int) - distancePower (float) @@ -6367,7 +6442,7 @@ dilate The number of iterations the effect is performed. - min-value: 0 - colormap (Colormap) - The colormap to be used for the filter. Use function ImageColorMap to create. + The colormap to be used for the filter. Use function ImageFilterColorMap to create. - newColor (String) - blackFunction (railo.runtime.img.math.BinaryFunction) displace @@ -6437,7 +6512,7 @@ erode The number of iterations the effect is performed. - min-value: 0 - colormap (Colormap) - The colormap to be used for the filter. Use function ImageColorMap to create. + The colormap to be used for the filter. Use function ImageFilterColorMap to create. - newColor (String) - blackFunction (railo.runtime.img.math.BinaryFunction) exposure @@ -6566,7 +6641,7 @@ glint - min-value: 0 - max-value: 1 - colormap (Colormap) - The colormap to be used for the filter. Use function ImageColorMap to create. + The colormap to be used for the filter. Use function ImageFilterColorMap to create. - blur (float) The blur that is applied before thresholding. - glintOnly (boolean) @@ -6605,7 +6680,7 @@ gradient Specifies the angle of the texture. @angle - colormap (Colormap) - The colormap to be used for the filter. Use function ImageColorMap to create. + The colormap to be used for the filter. Use function ImageFilterColorMap to create. - point1 (java.awt.Point) - point2 (java.awt.Point) - paintMode (int) @@ -6700,7 +6775,7 @@ life The number of iterations the effect is performed. - min-value: 0 - colormap (Colormap) - The colormap to be used for the filter. Use function ImageColorMap to create. + The colormap to be used for the filter. Use function ImageFilterColorMap to create. - newColor (String) - blackFunction (railo.runtime.img.math.BinaryFunction) light @@ -6722,7 +6797,7 @@ lookup Parameters: - colormap (Colormap) - The colormap to be used for the filter. Use function ImageColorMap to create. + The colormap to be used for the filter. Use function ImageFilterColorMap to create. - dimensions (Array) map An abstract superclass for filters which distort images in some way. The subclass only needs to override @@ -6836,7 +6911,7 @@ outline The number of iterations the effect is performed. - min-value: 0 - colormap (Colormap) - The colormap to be used for the filter. Use function ImageColorMap to create. + The colormap to be used for the filter. Use function ImageFilterColorMap to create. - newColor (String) - blackFunction (railo.runtime.img.math.BinaryFunction) perspective @@ -6880,7 +6955,7 @@ plasma - min-value: 0 - max-value: 10 - colormap (Colormap) - The colormap to be used for the filter. Use function ImageColorMap to create. + The colormap to be used for the filter. Use function ImageFilterColorMap to create. - scaling (float) - useColormap (boolean) - useImageColors (boolean) @@ -6915,7 +6990,7 @@ pointillize - f3 (float) - f4 (float) - colormap (Colormap) - The colormap to be used for the filter. Use function ImageColorMap to create. + The colormap to be used for the filter. Use function ImageFilterColorMap to create. - randomness (float) - gridType (int) - distancePower (float) @@ -6971,7 +7046,7 @@ quilt The number of iterations the effect is performed. - min-value: 0 - colormap (Colormap) - The colormap to be used for the filter. Use function ImageColorMap to create. + The colormap to be used for the filter. Use function ImageFilterColorMap to create. - a (float) - b (float) - c (float) @@ -6982,7 +7057,7 @@ rays Parameters: - colormap (Colormap) - The colormap to be used for the filter. Use function ImageColorMap to create. + The colormap to be used for the filter. Use function ImageFilterColorMap to create. - strength (float) The strength of the rays. - opacity (float) @@ -7098,7 +7173,7 @@ shape Parameters: - useAlpha (boolean) - colormap (Colormap) - The colormap to be used for the filter. Use function ImageColorMap to create. + The colormap to be used for the filter. Use function ImageFilterColorMap to create. - invert (boolean) - factor (float) - merge (boolean) @@ -7164,7 +7239,7 @@ skeleton The number of iterations the effect is performed. - min-value: 0 - colormap (Colormap) - The colormap to be used for the filter. Use function ImageColorMap to create. + The colormap to be used for the filter. Use function ImageFilterColorMap to create. - newColor (String) - blackFunction (railo.runtime.img.math.BinaryFunction) smear @@ -7288,7 +7363,7 @@ texture - angle (float) Specifies the angle of the texture. - colormap (Colormap) - The colormap to be used for the filter. Use function ImageColorMap to create. + The colormap to be used for the filter. Use function ImageFilterColorMap to create. - operation (int) - function (railo.runtime.img.math.Function2D) - scale (float) @@ -7425,7 +7500,7 @@ wood - angle (float) Specifies the angle of the texture. - colormap (Colormap) - The colormap to be used for the filter. Use function ImageColorMap to create. + The colormap to be used for the filter. Use function ImageFilterColorMap to create. - gain (float) Specifies the gain of the texture. - min-value: 0
3df7007006114f98fde14577b0f77b560a435743
drools
Added Analysis Result as HTML--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@15004 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
a
https://github.com/kiegroup/drools
diff --git a/experimental/drools-analytics/src/main/java/org/drools/analytics/result/ReportModeller.java b/experimental/drools-analytics/src/main/java/org/drools/analytics/result/ReportModeller.java index c7621b7fbf3..1f7b88cb16d 100644 --- a/experimental/drools-analytics/src/main/java/org/drools/analytics/result/ReportModeller.java +++ b/experimental/drools-analytics/src/main/java/org/drools/analytics/result/ReportModeller.java @@ -3,12 +3,18 @@ import org.drools.analytics.components.LiteralRestriction; import com.thoughtworks.xstream.XStream; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import org.drools.analytics.Analyzer; /** * * @author Toni Rikkola */ public class ReportModeller { + + private static String cssFile = "basic.css"; public static String writeXML(AnalysisResultNormal result) { XStream xstream = new XStream(); @@ -59,5 +65,134 @@ public static String writePlainText(AnalysisResultNormal result) { return str.toString(); } + + public static String writeHTML(AnalysisResultNormal result) { + StringBuffer str = new StringBuffer(""); + str.append("<html>\n"); + str.append("<head>\n"); + str.append("<title>\n"); + str.append("Analysis Result\n"); + str.append("</title>\n"); + //str.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"basic.css\" title=\"default\">\n"); + + str.append("<style type=\"text/css\">\n"); + str.append("<!--\n"); + BufferedReader reader = new BufferedReader(new InputStreamReader(Analyzer.class.getResourceAsStream(cssFile))); + try{ + String cssLine = null; + while((cssLine = reader.readLine()) != null) + { + str.append(cssLine); + str.append("\n"); + } + } + catch(IOException e) + { + e.printStackTrace(); + } + str.append("-->\n"); + str.append("</style>\n"); + + str.append("</head>\n"); + str.append("<body>\n\n"); + + str.append("<br>\n"); + str.append("<h1>\n"); + str.append("Analysis results"); + str.append("</h1>\n"); + str.append("<br>\n"); + + if(result.getErrors().size() > 0) + { + str.append("<table class=\"errors\">\n"); + str.append("<tr>\n"); + str.append("<th>\n"); + str.append("ERRORS ("); + str.append(result.getErrors().size()); + str.append(")\n"); + str.append("</th>\n"); + str.append("</tr>\n"); + for (AnalysisError error : result.getErrors()) { + str.append("<tr>\n"); + str.append("<td>\n"); + str.append(error); + str.append("</td>\n"); + str.append("</tr>\n"); + } + str.append("</table>\n"); + + str.append("<br>\n"); + str.append("<br>\n"); + } + + if(result.getWarnings().size() > 0) + { + str.append("<table class=\"warnings\">\n"); + str.append("<tr>\n"); + str.append("<th>\n"); + str.append("WARNINGS ("); + str.append(result.getWarnings().size()); + str.append(")\n"); + str.append("</th>\n"); + str.append("</tr>\n"); + for (AnalysisWarning warning : result.getWarnings()) { + str.append("<tr>\n"); + str.append("<td>\n"); + + str.append("Warning id = "); + str.append(warning.getId()); + str.append(":<BR>\n"); + + if (warning.getRuleName() != null) { + str.append("in rule "); + str.append(warning.getRuleName()); + str.append(": "); + } + + str.append(warning.getMessage()); + str.append("<BR>\n"); + str.append("&nbsp;&nbsp; Causes are [<BR>\n"); + + for (Cause cause : warning.getCauses()) { + str.append("&nbsp;&nbsp;&nbsp;&nbsp;"); + str.append(cause); + str.append("<BR>\n"); + } + str.append("&nbsp;&nbsp; ]\n"); + + str.append("</td>\n"); + str.append("</tr>\n"); + } + str.append("</table>\n"); + + str.append("<br>\n"); + str.append("<br>\n"); + } + + if(result.getNotes().size() > 0) + { + str.append("<table class=\"notes\">\n"); + str.append("<tr>\n"); + str.append("<th>\n"); + str.append("NOTES ("); + str.append(result.getNotes().size()); + str.append(")\n"); + str.append("</th>\n"); + str.append("</tr>\n"); + for (AnalysisNote note : result.getNotes()) { + str.append("<tr>\n"); + str.append("<td>\n"); + str.append(note); + str.append("</td>\n"); + str.append("</tr>\n"); + } + str.append("</table>\n"); + } + + str.append("</body>\n"); + str.append("</html>"); + + return str.toString(); + } } diff --git a/experimental/drools-analytics/src/test/resources/org/drools/analytics/AnalyticsTest.java b/experimental/drools-analytics/src/test/resources/org/drools/analytics/AnalyticsTest.java new file mode 100644 index 00000000000..c1c8cf911c2 --- /dev/null +++ b/experimental/drools-analytics/src/test/resources/org/drools/analytics/AnalyticsTest.java @@ -0,0 +1,43 @@ +package org.drools.analytics; + +import java.io.InputStreamReader; + +import org.drools.compiler.DrlParser; +import org.drools.lang.descr.PackageDescr; + +/** + * This is a sample file to launch a rule package from a rule source file. + */ +class AnalyticsTest { + + public static final void main(String[] args) { + try { + PackageDescr descr = new DrlParser().parse(new InputStreamReader( + Analyzer.class + .getResourceAsStream("MissingRangesForDates.drl"))); + PackageDescr descr2 = new DrlParser() + .parse(new InputStreamReader(Analyzer.class + .getResourceAsStream("MissingRangesForDoubles.drl"))); + PackageDescr descr3 = new DrlParser().parse(new InputStreamReader( + Analyzer.class + .getResourceAsStream("MissingRangesForInts.drl"))); + PackageDescr descr4 = new DrlParser() + .parse(new InputStreamReader( + Analyzer.class + .getResourceAsStream("MissingRangesForVariables.drl"))); + + Analyzer a = new Analyzer(); + a.addPackageDescr(descr); + // a.addPackageDescr(descr2); + // a.addPackageDescr(descr3); + // a.addPackageDescr(descr4); + a.fireAnalysis(); + // System.out.print(a.getResultAsPlainText()); + // System.out.print(a.getResultAsXML()); + System.out.print(a.getResultAsHTML()); + + } catch (Throwable t) { + t.printStackTrace(); + } + } +} diff --git a/experimental/drools-analytics/src/test/resources/org/drools/analytics/Analyzer.java b/experimental/drools-analytics/src/test/resources/org/drools/analytics/Analyzer.java new file mode 100644 index 00000000000..ef1e3475252 --- /dev/null +++ b/experimental/drools-analytics/src/test/resources/org/drools/analytics/Analyzer.java @@ -0,0 +1,108 @@ +package org.drools.analytics; + +import java.util.Collection; + +import org.drools.RuleBase; +import org.drools.RuleBaseFactory; +import org.drools.WorkingMemory; +import org.drools.analytics.dao.AnalyticsData; +import org.drools.analytics.dao.AnalyticsDataMaps; +import org.drools.analytics.result.AnalysisResultNormal; +import org.drools.analytics.result.ReportModeller; +import org.drools.lang.descr.PackageDescr; +import org.drools.rule.Package; + +/** + * + * @author Toni Rikkola + */ +public class Analyzer { + + private AnalysisResultNormal result = new AnalysisResultNormal(); + + public void addPackageDescr(PackageDescr descr) { + try { + + PackageDescrFlattener ruleFlattener = new PackageDescrFlattener(); + + ruleFlattener.insert(descr); + + } catch (Throwable t) { + t.printStackTrace(); + } + } + + public void fireAnalysis() { + try { + AnalyticsData data = AnalyticsDataMaps.getAnalyticsDataMaps(); + + System.setProperty("drools.accumulate.function.validatePattern", + "org.drools.analytics.accumulateFunction.ValidatePattern"); + + // load up the rulebase + RuleBase ruleBase = createRuleBase(); + + WorkingMemory workingMemory = ruleBase.newStatefulSession(); + + for (Object o : data.getAll()) { + workingMemory.insert(o); + } + + // Object that returns the results. + workingMemory.setGlobal("result", result); + workingMemory.fireAllRules(); + + } catch (Throwable t) { + t.printStackTrace(); + } + } + + /** + * Returns the analysis results as plain text. + * + * @return Analysis results as plain text. + */ + public String getResultAsPlainText() { + return ReportModeller.writePlainText(result); + } + + /** + * Returns the analysis results as XML. + * + * @return Analysis results as XML + */ + public String getResultAsXML() { + return ReportModeller.writeXML(result); + } + + /** + * Returns the analysis results as HTML. + * + * @return Analysis results as HTML + */ + public String getResultAsHTML() { + return ReportModeller.writeHTML(result); + } + + /** + * Returns the analysis results as <code>AnalysisResult</code> object. + * + * @return Analysis result + */ + public AnalysisResultNormal getResult() { + return result; + } + + private static RuleBase createRuleBase() throws Exception { + + RuleBase ruleBase = RuleBaseFactory.newRuleBase(); + + Collection<Package> packages = RuleLoader.loadPackages(); + for (Package pkg : packages) { + + ruleBase.addPackage(pkg); + } + + return ruleBase; + } +} diff --git a/experimental/drools-analytics/src/test/resources/org/drools/analytics/basic.css b/experimental/drools-analytics/src/test/resources/org/drools/analytics/basic.css new file mode 100644 index 00000000000..36257009419 --- /dev/null +++ b/experimental/drools-analytics/src/test/resources/org/drools/analytics/basic.css @@ -0,0 +1,54 @@ +/* JBoss Drools Analytics Style Sheet */ +/* Website: http://labs.jboss.com/jbossrules/ */ + +* +{ + border: 0; + margin: 0; + padding: 0; +} + +table +{ + background-color: #d2d7db; + text-align: left; + border-spacing: 0px; + border: 1px solid #aeb3b6; + border-collapse: collapse; +} + +table a, table, tbody, tfoot, tr, th, td +{ + font-family: georgia, "times new roman", serif; + line-height: 1.5em; + font-size: 13px; + color: #55595c; +} + +table caption +{ + border-top: 1px solid #aeb3b6; + padding: .5em 0; + font-size: 240%; + font-style: italic; + color: #d2d7db; +} + +table th +{ + width: 600px; +} + +tbody th +{ + color: #25c1e2; + font-style: italic; + background-color: #fff; + border-bottom: 1px solid #aeb3b6; +} + +td +{ + border: 1px dotted #fff; + padding: 0 2px; +}
e6897e844505bfdfff46cfc91d9e122002f3e6a5
orientdb
first implementation of binary record serializer- debug info.
a
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializationDebug.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializationDebug.java new file mode 100644 index 00000000000..a90e217af70 --- /dev/null +++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializationDebug.java @@ -0,0 +1,13 @@ +package com.orientechnologies.orient.core.serialization.serializer.record.binary; + +import java.util.ArrayList; + +public class ORecordSerializationDebug { + + public String className; + public ArrayList<ORecordSerializationDebugProperty> properties; + public boolean readingFailure; + public RuntimeException readingException; + public int failPosition; + +} diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializationDebugProperty.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializationDebugProperty.java new file mode 100644 index 00000000000..1e1f671fa95 --- /dev/null +++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializationDebugProperty.java @@ -0,0 +1,15 @@ +package com.orientechnologies.orient.core.serialization.serializer.record.binary; + +import com.orientechnologies.orient.core.metadata.schema.OType; + +public class ORecordSerializationDebugProperty { + + public String name; + public int globalId; + public OType type; + public RuntimeException readingException; + public boolean faildToRead; + public int failPosition; + public Object value; + +} diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializerBinaryDebug.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializerBinaryDebug.java new file mode 100644 index 00000000000..d2b294a2419 --- /dev/null +++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializerBinaryDebug.java @@ -0,0 +1,93 @@ +package com.orientechnologies.orient.core.serialization.serializer.record.binary; + +import java.util.ArrayList; + +import com.orientechnologies.common.exception.OException; +import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; +import com.orientechnologies.orient.core.metadata.OMetadataInternal; +import com.orientechnologies.orient.core.metadata.schema.OGlobalProperty; +import com.orientechnologies.orient.core.metadata.schema.OImmutableSchema; +import com.orientechnologies.orient.core.metadata.schema.OType; +import com.orientechnologies.orient.core.record.impl.ODocument; + +public class ORecordSerializerBinaryDebug extends ORecordSerializerBinaryV0 { + + public ORecordSerializationDebug deserializeDebug(final byte[] iSource, ODatabaseDocumentTx db) { + ORecordSerializationDebug debugInfo = new ORecordSerializationDebug(); + OImmutableSchema schema = ((OMetadataInternal) db.getMetadata()).getImmutableSchemaSnapshot(); + BytesContainer bytes = new BytesContainer(iSource); + if (bytes.bytes[0] != 0) + throw new OException("Unsupported binary serialization version"); + bytes.skip(1); + try { + final String className = readString(bytes); + debugInfo.className = className; + } catch (RuntimeException ex) { + debugInfo.readingFailure = true; + debugInfo.readingException = ex; + debugInfo.failPosition = bytes.offset; + return debugInfo; + } + + debugInfo.properties = new ArrayList<ORecordSerializationDebugProperty>(); + int last = 0; + String fieldName; + int valuePos; + OType type; + while (true) { + ORecordSerializationDebugProperty debugProperty = new ORecordSerializationDebugProperty(); + OGlobalProperty prop = null; + try { + final int len = OVarIntSerializer.readAsInteger(bytes); + if (len != 0) + debugInfo.properties.add(debugProperty); + if (len == 0) { + // SCAN COMPLETED + break; + } else if (len > 0) { + // PARSE FIELD NAME + fieldName = stringFromBytes(bytes.bytes, bytes.offset, len).intern(); + bytes.skip(len); + valuePos = readInteger(bytes); + type = readOType(bytes); + } else { + // LOAD GLOBAL PROPERTY BY ID + final int id = (len * -1) - 1; + debugProperty.globalId = id; + prop = schema.getGlobalPropertyById(id); + fieldName = prop.getName(); + valuePos = readInteger(bytes); + if (prop.getType() != OType.ANY) + type = prop.getType(); + else + type = readOType(bytes); + } + debugProperty.name = fieldName; + debugProperty.type = type; + + if (valuePos != 0) { + int headerCursor = bytes.offset; + bytes.offset = valuePos; + try { + debugProperty.value = readSingleValue(bytes, type, new ODocument()); + } catch (RuntimeException ex) { + debugProperty.faildToRead = true; + debugProperty.readingException = ex; + debugProperty.failPosition = bytes.offset; + } + if (bytes.offset > last) + last = bytes.offset; + bytes.offset = headerCursor; + } else + debugProperty.value = null; + } catch (RuntimeException ex) { + debugInfo.readingFailure = true; + debugInfo.readingException = ex; + debugInfo.failPosition = bytes.offset; + return debugInfo; + } + } + + return debugInfo; + } +} diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializerBinaryV0.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializerBinaryV0.java index 1b8f179c7fb..817eb75926b 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializerBinaryV0.java +++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/binary/ORecordSerializerBinaryV0.java @@ -273,12 +273,12 @@ protected OClass serializeClass(final ODocument document, final BytesContainer b return clazz; } - private OGlobalProperty getGlobalProperty(final ODocument document, final int len) { + protected OGlobalProperty getGlobalProperty(final ODocument document, final int len) { final int id = (len * -1) - 1; return ODocumentInternal.getGlobalPropertyById(document, id); } - private OType readOType(final BytesContainer bytes) { + protected OType readOType(final BytesContainer bytes) { return OType.getById(readByte(bytes)); } @@ -286,7 +286,7 @@ private void writeOType(BytesContainer bytes, int pos, OType type) { bytes.bytes[pos] = (byte) type.getId(); } - private Object readSingleValue(BytesContainer bytes, OType type, ODocument document) { + protected Object readSingleValue(BytesContainer bytes, OType type, ODocument document) { Object value = null; switch (type) { case INTEGER: @@ -748,14 +748,14 @@ private OType getTypeFromValueEmbedded(final Object fieldValue) { return type; } - private String readString(final BytesContainer bytes) { + protected String readString(final BytesContainer bytes) { final int len = OVarIntSerializer.readAsInteger(bytes); final String res = stringFromBytes(bytes.bytes, bytes.offset, len); bytes.skip(len); return res; } - private int readInteger(final BytesContainer container) { + protected int readInteger(final BytesContainer container) { final int value = OIntegerSerializer.INSTANCE.deserializeLiteral(container.bytes, container.offset); container.offset += OIntegerSerializer.INT_SIZE; return value; @@ -791,7 +791,7 @@ private byte[] bytesFromString(final String toWrite) { } } - private String stringFromBytes(final byte[] bytes, final int offset, final int len) { + protected String stringFromBytes(final byte[] bytes, final int offset, final int len) { try { return new String(bytes, offset, len, CHARSET_UTF_8); } catch (UnsupportedEncodingException e) { diff --git a/core/src/test/java/com/orientechnologies/orient/core/serialization/serializer/binary/impl/ORecordSerializerBinaryDebugTest.java b/core/src/test/java/com/orientechnologies/orient/core/serialization/serializer/binary/impl/ORecordSerializerBinaryDebugTest.java new file mode 100644 index 00000000000..dba8275f0a2 --- /dev/null +++ b/core/src/test/java/com/orientechnologies/orient/core/serialization/serializer/binary/impl/ORecordSerializerBinaryDebugTest.java @@ -0,0 +1,163 @@ +package com.orientechnologies.orient.core.serialization.serializer.binary.impl; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; + +import org.testng.annotations.Test; + +import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; +import com.orientechnologies.orient.core.metadata.schema.OClass; +import com.orientechnologies.orient.core.metadata.schema.OType; +import com.orientechnologies.orient.core.record.impl.ODocument; +import com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializationDebug; +import com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerBinaryDebug; + +public class ORecordSerializerBinaryDebugTest { + + @Test + public void testSimpleDocumentDebug() { + ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:" + ORecordSerializerBinaryDebugTest.class.getSimpleName()); + db.create(); + try { + ODocument doc = new ODocument(); + doc.field("test", "test"); + doc.field("anInt", 2); + doc.field("anDouble", 2D); + + byte[] bytes = doc.toStream(); + + ORecordSerializerBinaryDebug debugger = new ORecordSerializerBinaryDebug(); + ORecordSerializationDebug debug = debugger.deserializeDebug(bytes, db); + + assertEquals(debug.properties.size(), 3); + assertEquals(debug.properties.get(0).name, "test"); + assertEquals(debug.properties.get(0).type, OType.STRING); + assertEquals(debug.properties.get(0).value, "test"); + + assertEquals(debug.properties.get(1).name, "anInt"); + assertEquals(debug.properties.get(1).type, OType.INTEGER); + assertEquals(debug.properties.get(1).value, 2); + + assertEquals(debug.properties.get(2).name, "anDouble"); + assertEquals(debug.properties.get(2).type, OType.DOUBLE); + assertEquals(debug.properties.get(2).value, 2D); + } finally { + db.drop(); + } + } + + @Test + public void testSchemaFullDocumentDebug() { + ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:" + ORecordSerializerBinaryDebugTest.class.getSimpleName()); + db.create(); + try { + OClass clazz = db.getMetadata().getSchema().createClass("some"); + clazz.createProperty("testP", OType.STRING); + clazz.createProperty("theInt", OType.INTEGER); + ODocument doc = new ODocument("some"); + doc.field("testP", "test"); + doc.field("theInt", 2); + doc.field("anDouble", 2D); + + byte[] bytes = doc.toStream(); + + ORecordSerializerBinaryDebug debugger = new ORecordSerializerBinaryDebug(); + ORecordSerializationDebug debug = debugger.deserializeDebug(bytes, db); + + assertEquals(debug.properties.size(), 3); + assertEquals(debug.properties.get(0).name, "testP"); + assertEquals(debug.properties.get(0).type, OType.STRING); + assertEquals(debug.properties.get(0).value, "test"); + + assertEquals(debug.properties.get(1).name, "theInt"); + assertEquals(debug.properties.get(1).type, OType.INTEGER); + assertEquals(debug.properties.get(1).value, 2); + + assertEquals(debug.properties.get(2).name, "anDouble"); + assertEquals(debug.properties.get(2).type, OType.DOUBLE); + assertEquals(debug.properties.get(2).value, 2D); + } finally { + db.drop(); + } + + } + + @Test + public void testSimpleBrokenDocumentDebug() { + ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:" + ORecordSerializerBinaryDebugTest.class.getSimpleName()); + db.create(); + try { + ODocument doc = new ODocument(); + doc.field("test", "test"); + doc.field("anInt", 2); + doc.field("anDouble", 2D); + + byte[] bytes = doc.toStream(); + byte[] brokenBytes = new byte[bytes.length - 10]; + System.arraycopy(bytes, 0, brokenBytes, 0, bytes.length - 10); + + ORecordSerializerBinaryDebug debugger = new ORecordSerializerBinaryDebug(); + ORecordSerializationDebug debug = debugger.deserializeDebug(brokenBytes, db); + + assertEquals(debug.properties.size(), 3); + assertEquals(debug.properties.get(0).name, "test"); + assertEquals(debug.properties.get(0).type, OType.STRING); + assertEquals(debug.properties.get(0).faildToRead, true); + assertNotNull(debug.properties.get(0).readingException); + + assertEquals(debug.properties.get(1).name, "anInt"); + assertEquals(debug.properties.get(1).type, OType.INTEGER); + assertEquals(debug.properties.get(1).faildToRead, true); + assertNotNull(debug.properties.get(1).readingException); + + assertEquals(debug.properties.get(2).name, "anDouble"); + assertEquals(debug.properties.get(2).type, OType.DOUBLE); + assertEquals(debug.properties.get(2).faildToRead, true); + assertNotNull(debug.properties.get(2).readingException); + } finally { + db.drop(); + } + } + + @Test + public void testBrokenSchemaFullDocumentDebug() { + ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:" + ORecordSerializerBinaryDebugTest.class.getSimpleName()); + db.create(); + try { + OClass clazz = db.getMetadata().getSchema().createClass("some"); + clazz.createProperty("testP", OType.STRING); + clazz.createProperty("theInt", OType.INTEGER); + ODocument doc = new ODocument("some"); + doc.field("testP", "test"); + doc.field("theInt", 2); + doc.field("anDouble", 2D); + + byte[] bytes = doc.toStream(); + byte[] brokenBytes = new byte[bytes.length - 10]; + System.arraycopy(bytes, 0, brokenBytes, 0, bytes.length - 10); + + ORecordSerializerBinaryDebug debugger = new ORecordSerializerBinaryDebug(); + ORecordSerializationDebug debug = debugger.deserializeDebug(brokenBytes, db); + + assertEquals(debug.properties.size(), 3); + assertEquals(debug.properties.get(0).name, "testP"); + assertEquals(debug.properties.get(0).type, OType.STRING); + assertEquals(debug.properties.get(0).faildToRead, true); + assertNotNull(debug.properties.get(0).readingException); + + assertEquals(debug.properties.get(1).name, "theInt"); + assertEquals(debug.properties.get(1).type, OType.INTEGER); + assertEquals(debug.properties.get(1).faildToRead, true); + assertNotNull(debug.properties.get(1).readingException); + + assertEquals(debug.properties.get(2).name, "anDouble"); + assertEquals(debug.properties.get(2).type, OType.DOUBLE); + assertEquals(debug.properties.get(2).faildToRead, true); + assertNotNull(debug.properties.get(2).readingException); + } finally { + db.drop(); + } + + } + +}
d1c59faff700059d52ef350c3e7741dd5abcb65a
drools
JBRULES-1498 Thead safe partitioning of- WorkingMemory entry points--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@18794 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
p
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/StreamsTest.java b/drools-compiler/src/test/java/org/drools/integrationtests/StreamsTest.java index e05ddcb00c0..75742021cc5 100644 --- a/drools-compiler/src/test/java/org/drools/integrationtests/StreamsTest.java +++ b/drools-compiler/src/test/java/org/drools/integrationtests/StreamsTest.java @@ -24,7 +24,7 @@ import java.util.List; import org.drools.ClockType; -import org.drools.EntryPointInterface; +import org.drools.WorkingMemoryEntryPoint; import org.drools.RuleBase; import org.drools.RuleBaseConfiguration; import org.drools.RuleBaseFactory; @@ -159,7 +159,7 @@ public void testEventAssertion() throws Exception { 50, System.currentTimeMillis() ); - EntryPointInterface entry = wm.getEntryPoint( "StockStream" ); + WorkingMemoryEntryPoint entry = wm.getWorkingMemoryEntryPoint( "StockStream" ); InternalFactHandle handle5 = (InternalFactHandle) entry.insert( tick5 ); InternalFactHandle handle6 = (InternalFactHandle) entry.insert( tick6 ); diff --git a/drools-compiler/src/test/java/org/drools/testframework/MockWorkingMemory.java b/drools-compiler/src/test/java/org/drools/testframework/MockWorkingMemory.java index 127b5829f0c..a3a5e83ff4e 100644 --- a/drools-compiler/src/test/java/org/drools/testframework/MockWorkingMemory.java +++ b/drools-compiler/src/test/java/org/drools/testframework/MockWorkingMemory.java @@ -9,7 +9,7 @@ import java.util.concurrent.locks.Lock; import org.drools.Agenda; -import org.drools.EntryPointInterface; +import org.drools.WorkingMemoryEntryPoint; import org.drools.FactException; import org.drools.FactHandle; import org.drools.ObjectFilter; @@ -458,7 +458,7 @@ public Map<Object, ObjectTypeConf> getObjectTypeConfMap(EntryPoint entryPoint) { return null; } - public EntryPointInterface getEntryPoint(String id) { + public WorkingMemoryEntryPoint getWorkingMemoryEntryPoint(String id) { // TODO Auto-generated method stub return null; }
6de7fd15b7b4f42263d847fe462552110c405bb3
ReactiveX-RxJava
Move last 6 remaining unit tests out.--
p
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/operators/OperationToFuture.java b/rxjava-core/src/main/java/rx/operators/OperationToFuture.java index a3ecc49efe..d4433da9d6 100644 --- a/rxjava-core/src/main/java/rx/operators/OperationToFuture.java +++ b/rxjava-core/src/main/java/rx/operators/OperationToFuture.java @@ -15,9 +15,6 @@ */ package rx.operators; -import static org.junit.Assert.*; - -import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; @@ -25,13 +22,9 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; -import org.junit.Test; - import rx.Observable; -import rx.Observable.OnSubscribeFunc; import rx.Observer; import rx.Subscription; -import rx.subscriptions.Subscriptions; /** * Returns a Future representing the single value emitted by an Observable. @@ -136,52 +129,4 @@ private T getValue() throws ExecutionException { } - @Test - public void testToFuture() throws InterruptedException, ExecutionException { - Observable<String> obs = Observable.from("one"); - Future<String> f = toFuture(obs); - assertEquals("one", f.get()); - } - - @Test - public void testToFutureList() throws InterruptedException, ExecutionException { - Observable<String> obs = Observable.from("one", "two", "three"); - Future<List<String>> f = toFuture(obs.toList()); - assertEquals("one", f.get().get(0)); - assertEquals("two", f.get().get(1)); - assertEquals("three", f.get().get(2)); - } - - @Test(expected = ExecutionException.class) - public void testExceptionWithMoreThanOneElement() throws InterruptedException, ExecutionException { - Observable<String> obs = Observable.from("one", "two"); - Future<String> f = toFuture(obs); - assertEquals("one", f.get()); - // we expect an exception since there are more than 1 element - } - - @Test - public void testToFutureWithException() { - Observable<String> obs = Observable.create(new OnSubscribeFunc<String>() { - - @Override - public Subscription onSubscribe(Observer<? super String> observer) { - observer.onNext("one"); - observer.onError(new TestException()); - return Subscriptions.empty(); - } - }); - - Future<String> f = toFuture(obs); - try { - f.get(); - fail("expected exception"); - } catch (Throwable e) { - assertEquals(TestException.class, e.getCause().getClass()); - } - } - - private static class TestException extends RuntimeException { - private static final long serialVersionUID = 1L; - } } diff --git a/rxjava-core/src/main/java/rx/operators/OperationToIterator.java b/rxjava-core/src/main/java/rx/operators/OperationToIterator.java index 59debafcb9..2fcd51872e 100644 --- a/rxjava-core/src/main/java/rx/operators/OperationToIterator.java +++ b/rxjava-core/src/main/java/rx/operators/OperationToIterator.java @@ -15,20 +15,13 @@ */ package rx.operators; -import static org.junit.Assert.*; - import java.util.Iterator; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; -import org.junit.Test; - import rx.Notification; import rx.Observable; -import rx.Observable.OnSubscribeFunc; import rx.Observer; -import rx.Subscription; -import rx.subscriptions.Subscriptions; import rx.util.Exceptions; /** @@ -108,47 +101,4 @@ public void remove() { }; } - @Test - public void testToIterator() { - Observable<String> obs = Observable.from("one", "two", "three"); - - Iterator<String> it = toIterator(obs); - - assertEquals(true, it.hasNext()); - assertEquals("one", it.next()); - - assertEquals(true, it.hasNext()); - assertEquals("two", it.next()); - - assertEquals(true, it.hasNext()); - assertEquals("three", it.next()); - - assertEquals(false, it.hasNext()); - - } - - @Test(expected = TestException.class) - public void testToIteratorWithException() { - Observable<String> obs = Observable.create(new OnSubscribeFunc<String>() { - - @Override - public Subscription onSubscribe(Observer<? super String> observer) { - observer.onNext("one"); - observer.onError(new TestException()); - return Subscriptions.empty(); - } - }); - - Iterator<String> it = toIterator(obs); - - assertEquals(true, it.hasNext()); - assertEquals("one", it.next()); - - assertEquals(true, it.hasNext()); - it.next(); - } - - private static class TestException extends RuntimeException { - private static final long serialVersionUID = 1L; - } } diff --git a/rxjava-core/src/test/java/rx/operators/OperationToFutureTest.java b/rxjava-core/src/test/java/rx/operators/OperationToFutureTest.java new file mode 100644 index 0000000000..c18131e5c7 --- /dev/null +++ b/rxjava-core/src/test/java/rx/operators/OperationToFutureTest.java @@ -0,0 +1,68 @@ +package rx.operators; + +import static org.junit.Assert.*; +import static rx.operators.OperationToFuture.*; + +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +import org.junit.Test; + +import rx.Observable; +import rx.Observable.OnSubscribeFunc; +import rx.Observer; +import rx.Subscription; +import rx.subscriptions.Subscriptions; + +public class OperationToFutureTest { + + @Test + public void testToFuture() throws InterruptedException, ExecutionException { + Observable<String> obs = Observable.from("one"); + Future<String> f = toFuture(obs); + assertEquals("one", f.get()); + } + + @Test + public void testToFutureList() throws InterruptedException, ExecutionException { + Observable<String> obs = Observable.from("one", "two", "three"); + Future<List<String>> f = toFuture(obs.toList()); + assertEquals("one", f.get().get(0)); + assertEquals("two", f.get().get(1)); + assertEquals("three", f.get().get(2)); + } + + @Test(expected = ExecutionException.class) + public void testExceptionWithMoreThanOneElement() throws InterruptedException, ExecutionException { + Observable<String> obs = Observable.from("one", "two"); + Future<String> f = toFuture(obs); + assertEquals("one", f.get()); + // we expect an exception since there are more than 1 element + } + + @Test + public void testToFutureWithException() { + Observable<String> obs = Observable.create(new OnSubscribeFunc<String>() { + + @Override + public Subscription onSubscribe(Observer<? super String> observer) { + observer.onNext("one"); + observer.onError(new TestException()); + return Subscriptions.empty(); + } + }); + + Future<String> f = toFuture(obs); + try { + f.get(); + fail("expected exception"); + } catch (Throwable e) { + assertEquals(TestException.class, e.getCause().getClass()); + } + } + + private static class TestException extends RuntimeException { + private static final long serialVersionUID = 1L; + } +} diff --git a/rxjava-core/src/test/java/rx/operators/OperationToIteratorTest.java b/rxjava-core/src/test/java/rx/operators/OperationToIteratorTest.java new file mode 100644 index 0000000000..1994bd4a0c --- /dev/null +++ b/rxjava-core/src/test/java/rx/operators/OperationToIteratorTest.java @@ -0,0 +1,62 @@ +package rx.operators; + +import static org.junit.Assert.*; +import static rx.operators.OperationToIterator.*; + +import java.util.Iterator; + +import org.junit.Test; + +import rx.Observable; +import rx.Observable.OnSubscribeFunc; +import rx.Observer; +import rx.Subscription; +import rx.subscriptions.Subscriptions; + +public class OperationToIteratorTest { + + @Test + public void testToIterator() { + Observable<String> obs = Observable.from("one", "two", "three"); + + Iterator<String> it = toIterator(obs); + + assertEquals(true, it.hasNext()); + assertEquals("one", it.next()); + + assertEquals(true, it.hasNext()); + assertEquals("two", it.next()); + + assertEquals(true, it.hasNext()); + assertEquals("three", it.next()); + + assertEquals(false, it.hasNext()); + + } + + @Test(expected = TestException.class) + public void testToIteratorWithException() { + Observable<String> obs = Observable.create(new OnSubscribeFunc<String>() { + + @Override + public Subscription onSubscribe(Observer<? super String> observer) { + observer.onNext("one"); + observer.onError(new TestException()); + return Subscriptions.empty(); + } + }); + + Iterator<String> it = toIterator(obs); + + assertEquals(true, it.hasNext()); + assertEquals("one", it.next()); + + assertEquals(true, it.hasNext()); + it.next(); + } + + private static class TestException extends RuntimeException { + private static final long serialVersionUID = 1L; + } + +}
aa6c377fc4ce99db76db24c9eaf7db493c561b70
Vala
girparser: Support new gir format (deprecated, doc-version, doc-deprecated)
a
https://github.com/GNOME/vala/
diff --git a/vala/valagirparser.vala b/vala/valagirparser.vala index 8413e9ebc8..e6857067e3 100644 --- a/vala/valagirparser.vala +++ b/vala/valagirparser.vala @@ -1041,7 +1041,11 @@ public class Vala.GirParser : CodeVisitor { } else if (girdata["deprecated-version"] != null) { symbol.set_attribute_string ("Deprecated", "since", girdata.get ("deprecated-version")); } - if (metadata.get_bool (ArgumentType.DEPRECATED)) { + if (metadata.has_argument (ArgumentType.DEPRECATED)) { + if (metadata.get_bool (ArgumentType.DEPRECATED)) { + symbol.set_attribute ("Deprecated", true); + } + } else if (girdata["deprecated"] != null) { symbol.set_attribute ("Deprecated", true); } @@ -2025,7 +2029,15 @@ public class Vala.GirParser : CodeVisitor { } } + void skip_other_docs () { + while (current_token == MarkupTokenType.START_ELEMENT && (reader.name == "doc-deprecated" || reader.name == "doc-version")) { + skip_element (); + } + } + GirComment? parse_symbol_doc () { + skip_other_docs (); + if (reader.name != "doc") { return null; } @@ -2041,10 +2053,14 @@ public class Vala.GirParser : CodeVisitor { } end_element ("doc"); + + skip_other_docs (); return comment; } Comment? parse_doc () { + skip_other_docs (); + if (reader.name != "doc") { return null; } @@ -2060,6 +2076,8 @@ public class Vala.GirParser : CodeVisitor { } end_element ("doc"); + + skip_other_docs (); return comment; } diff --git a/vapi/atk.vapi b/vapi/atk.vapi index 4050c03aeb..6614b4b142 100644 --- a/vapi/atk.vapi +++ b/vapi/atk.vapi @@ -23,6 +23,7 @@ namespace Atk { public virtual int get_start_index (); public virtual string get_uri (int i); public bool is_inline (); + [Deprecated] public virtual bool is_selected_link (); public virtual bool is_valid (); [NoWrapper] @@ -30,6 +31,7 @@ namespace Atk { public int end_index { get; } [NoAccessorMethod] public int number_of_anchors { get; } + [Deprecated] [NoAccessorMethod] public bool selected_link { get; } public int start_index { get; } @@ -67,7 +69,9 @@ namespace Atk { public virtual Atk.AttributeSet get_attributes (); public virtual unowned string get_description (); public virtual int get_index_in_parent (); + [Deprecated] public virtual Atk.Layer get_layer (); + [Deprecated] public virtual int get_mdi_zorder (); public int get_n_accessible_children (); [NoWrapper] @@ -119,6 +123,7 @@ namespace Atk { public double accessible_value { get; set; } public virtual signal void active_descendant_changed (void* child); public virtual signal void children_changed (uint change_index, void* changed_child); + [Deprecated] public virtual signal void focus_event (bool focus_in); public signal void property_change (void* arg1); public virtual signal void state_change (string name, bool state_set); @@ -226,14 +231,17 @@ namespace Atk { [CCode (has_construct_function = false)] protected Util (); [CCode (cheader_filename = "atk/atk.h", cname = "atk_add_focus_tracker")] + [Deprecated] public static uint add_focus_tracker (Atk.EventListener focus_tracker); [CCode (cheader_filename = "atk/atk.h", cname = "atk_add_global_event_listener")] public static uint add_global_event_listener ([CCode (type = "GSignalEmissionHook")] Atk.SignalEmissionHook listener, string event_type); [CCode (cheader_filename = "atk/atk.h", cname = "atk_add_key_event_listener")] public static uint add_key_event_listener (Atk.KeySnoopFunc listener); [CCode (cheader_filename = "atk/atk.h", cname = "atk_focus_tracker_init")] + [Deprecated] public static void focus_tracker_init (Atk.EventListenerInit init); [CCode (cheader_filename = "atk/atk.h", cname = "atk_focus_tracker_notify")] + [Deprecated] public static void focus_tracker_notify (Atk.Object object); [CCode (cheader_filename = "atk/atk.h", cname = "atk_get_focus_object")] public static unowned Atk.Object get_focus_object (); @@ -246,6 +254,7 @@ namespace Atk { [CCode (cheader_filename = "atk/atk.h", cname = "atk_get_version")] public static unowned string get_version (); [CCode (cheader_filename = "atk/atk.h", cname = "atk_remove_focus_tracker")] + [Deprecated] public static void remove_focus_tracker (uint tracker_id); [CCode (cheader_filename = "atk/atk.h", cname = "atk_remove_global_event_listener")] public static void remove_global_event_listener (uint listener_id); @@ -264,6 +273,7 @@ namespace Atk { } [CCode (cheader_filename = "atk/atk.h", type_id = "atk_component_get_type ()")] public interface Component : GLib.Object { + [Deprecated] public abstract uint add_focus_handler (Atk.FocusHandler handler); public abstract bool contains (int x, int y, Atk.CoordType coord_type); public abstract double get_alpha (); @@ -274,6 +284,7 @@ namespace Atk { public abstract void get_size (int width, int height); public abstract bool grab_focus (); public abstract Atk.Object ref_accessible_at_point (int x, int y, Atk.CoordType coord_type); + [Deprecated] public abstract void remove_focus_handler (uint handler_id); public abstract bool set_extents (int x, int y, int width, int height, Atk.CoordType coord_type); public abstract bool set_position (int x, int y, Atk.CoordType coord_type); @@ -291,6 +302,7 @@ namespace Atk { public virtual unowned string get_document_locale (); public virtual unowned string get_document_type (); [CCode (vfunc_name = "get_document_locale")] + [Deprecated] public virtual unowned string get_locale (); [CCode (vfunc_name = "set_document_attribute")] public virtual bool set_attribute_value (string attribute_name, string attribute_value); @@ -414,14 +426,18 @@ namespace Atk { public abstract string get_selection (int selection_num, out int start_offset, out int end_offset); public abstract string get_string_at_offset (int offset, Atk.TextGranularity granularity, out int start_offset, out int end_offset); public abstract string get_text (int start_offset, int end_offset); + [Deprecated] public abstract string get_text_after_offset (int offset, Atk.TextBoundary boundary_type, out int start_offset, out int end_offset); + [Deprecated] public abstract string get_text_at_offset (int offset, Atk.TextBoundary boundary_type, out int start_offset, out int end_offset); + [Deprecated] public abstract string get_text_before_offset (int offset, Atk.TextBoundary boundary_type, out int start_offset, out int end_offset); public abstract bool remove_selection (int selection_num); public abstract bool set_caret_offset (int offset); public abstract bool set_selection (int selection_num, int start_offset, int end_offset); public virtual signal void text_attributes_changed (); public virtual signal void text_caret_moved (int location); + [Deprecated] public virtual signal void text_changed (int position, int length); public signal void text_insert (int arg1, int arg2, string arg3); public signal void text_remove (int arg1, int arg2, string arg3); @@ -784,6 +800,7 @@ namespace Atk { [CCode (cheader_filename = "atk/atk.h", has_target = false)] public delegate void EventListenerInit (); [CCode (cheader_filename = "atk/atk.h", has_target = false)] + [Deprecated] public delegate void FocusHandler (Atk.Object object, bool focus_in); [CCode (cheader_filename = "atk/atk.h", instance_pos = 0.9)] public delegate bool Function (); diff --git a/vapi/gdl-3.0.vapi b/vapi/gdl-3.0.vapi index 8488adb725..7fbf9d0628 100644 --- a/vapi/gdl-3.0.vapi +++ b/vapi/gdl-3.0.vapi @@ -241,7 +241,9 @@ namespace Gdl { [CCode (cheader_filename = "gdl/gdl.h", type_id = "gdl_dock_placeholder_get_type ()")] public class DockPlaceholder : Gdl.DockObject, Atk.Implementor, Gtk.Buildable { [CCode (has_construct_function = false, type = "GtkWidget*")] + [Deprecated] public DockPlaceholder (string name, Gdl.DockObject object, Gdl.DockPlacement position, bool sticky); + [Deprecated] public void attach (Gdl.DockObject object); [NoAccessorMethod] public bool floating { get; construct; } @@ -270,7 +272,9 @@ namespace Gdl { [CCode (has_construct_function = false, type = "GtkWidget*")] [Deprecated (since = "3.6")] public DockTablabel (Gdl.DockItem item); + [Deprecated] public void activate (); + [Deprecated] public void deactivate (); [NoAccessorMethod] public Gdl.DockItem item { owned get; set; } diff --git a/vapi/gio-2.0.vapi b/vapi/gio-2.0.vapi index 51581e959c..2846c1c6ad 100644 --- a/vapi/gio-2.0.vapi +++ b/vapi/gio-2.0.vapi @@ -1227,10 +1227,14 @@ namespace GLib { [Compact] public class IOSchedulerJob { [CCode (cheader_filename = "gio/gio.h", cname = "g_io_scheduler_cancel_all_jobs")] + [Deprecated] public static void cancel_all (); [CCode (cheader_filename = "gio/gio.h", cname = "g_io_scheduler_push_job")] + [Deprecated] public static void push ([CCode (delegate_target_pos = 1.33333, destroy_notify_pos = 1.66667)] owned GLib.IOSchedulerJobFunc job_func, int io_priority, GLib.Cancellable? cancellable = null); + [Deprecated] public bool send_to_mainloop (owned GLib.SourceFunc func); + [Deprecated] public void send_to_mainloop_async (owned GLib.SourceFunc func); } [CCode (cheader_filename = "gio/gio.h")] @@ -1734,6 +1738,7 @@ namespace GLib { public bool has_unapplied { get; } [NoAccessorMethod] public string path { owned get; construct; } + [Deprecated] [NoAccessorMethod] public string schema { owned get; construct; } [NoAccessorMethod] diff --git a/vapi/gtk+-3.0.vapi b/vapi/gtk+-3.0.vapi index b49257c78e..b792ccfd36 100644 --- a/vapi/gtk+-3.0.vapi +++ b/vapi/gtk+-3.0.vapi @@ -1,4 +1,4 @@ -/* gtk+-3.0.vapi generated by lt-vapigen, do not modify. */ +/* gtk+-3.0.vapi generated by vapigen, do not modify. */ [CCode (gir_namespace = "Gtk", gir_version = "3.0")] namespace Gtk { diff --git a/vapi/libsoup-2.4.vapi b/vapi/libsoup-2.4.vapi index a0dff08fdd..78c0dbe89d 100644 --- a/vapi/libsoup-2.4.vapi +++ b/vapi/libsoup-2.4.vapi @@ -314,6 +314,7 @@ namespace Soup { public GLib.SList<Soup.Cookie> get_cookie_list (Soup.URI uri, bool for_http); public string get_cookies (Soup.URI uri, bool for_http); public virtual bool is_persistent (); + [Deprecated] public virtual void save (); public void set_accept_policy (Soup.CookieJarAcceptPolicy policy); public void set_cookie (Soup.URI uri, string cookie); @@ -401,6 +402,7 @@ namespace Soup { public unowned Soup.Request get_soup_request (); public unowned Soup.URI get_uri (); public bool is_keepalive (); + [Deprecated] public void set_chunk_allocator (owned Soup.ChunkAllocator allocator); public void set_first_party (Soup.URI first_party); public void set_flags (Soup.MessageFlags flags); @@ -487,6 +489,7 @@ namespace Soup { public void @foreach (Soup.MessageHeadersForeachFunc func); public void free (); public void free_ranges (Soup.Range ranges); + [Deprecated] public unowned string @get (string name); public bool get_content_disposition (out string disposition, out GLib.HashTable<string,string> @params); public int64 get_content_length (); @@ -693,6 +696,7 @@ namespace Soup { public GLib.ProxyResolver proxy_resolver { owned get; set; } [NoAccessorMethod] public Soup.URI proxy_uri { owned get; set; } + [Deprecated] [NoAccessorMethod] public string ssl_ca_file { owned get; set; } [NoAccessorMethod] @@ -703,6 +707,7 @@ namespace Soup { public uint timeout { get; set; } [NoAccessorMethod] public GLib.TlsDatabase tls_database { owned get; set; } + [Deprecated] [NoAccessorMethod] public bool use_ntlm { get; set; } [NoAccessorMethod] @@ -719,15 +724,19 @@ namespace Soup { [CCode (cheader_filename = "libsoup/soup.h", type_id = "soup_session_async_get_type ()")] public class SessionAsync : Soup.Session { [CCode (has_construct_function = false, type = "SoupSession*")] + [Deprecated] public SessionAsync (); [CCode (has_construct_function = false, type = "SoupSession*")] + [Deprecated] public SessionAsync.with_options (string optname1, ...); } [CCode (cheader_filename = "libsoup/soup.h", type_id = "soup_session_sync_get_type ()")] public class SessionSync : Soup.Session { [CCode (has_construct_function = false, type = "SoupSession*")] + [Deprecated] public SessionSync (); [CCode (has_construct_function = false, type = "SoupSession*")] + [Deprecated] public SessionSync.with_options (string optname1, ...); } [CCode (cheader_filename = "libsoup/soup.h", type_id = "soup_socket_get_type ()")] @@ -839,7 +848,9 @@ namespace Soup { } [CCode (cheader_filename = "libsoup/soup.h", type_cname = "SoupProxyURIResolverInterface", type_id = "soup_proxy_uri_resolver_get_type ()")] public interface ProxyURIResolver : Soup.SessionFeature, GLib.Object { + [Deprecated] public abstract void get_proxy_uri_async (Soup.URI uri, GLib.MainContext? async_context, GLib.Cancellable? cancellable, [CCode (scope = "async")] owned Soup.ProxyURIResolverCallback callback); + [Deprecated] public abstract uint get_proxy_uri_sync (Soup.URI uri, GLib.Cancellable? cancellable, out Soup.URI proxy_uri); } [CCode (cheader_filename = "libsoup/soup.h", type_cname = "SoupSessionFeatureInterface", type_id = "soup_session_feature_get_type ()")] @@ -1158,6 +1169,7 @@ namespace Soup { [CCode (cheader_filename = "libsoup/soup.h", instance_pos = 3.9)] public delegate bool AuthDomainGenericAuthCallback (Soup.AuthDomain domain, Soup.Message msg, string username); [CCode (cheader_filename = "libsoup/soup.h", instance_pos = 2.9)] + [Deprecated] public delegate Soup.Buffer ChunkAllocator (Soup.Message msg, size_t max_len); [CCode (cheader_filename = "libsoup/soup.h", instance_pos = 2.9)] public delegate Soup.LoggerLogLevel LoggerFilter (Soup.Logger logger, Soup.Message msg); diff --git a/vapi/libwnck-3.0.vapi b/vapi/libwnck-3.0.vapi index b2cd760a93..286fab1b19 100644 --- a/vapi/libwnck-3.0.vapi +++ b/vapi/libwnck-3.0.vapi @@ -64,9 +64,11 @@ namespace Wnck { public class Screen : GLib.Object { [CCode (has_construct_function = false)] protected Screen (); + [Deprecated] public void calc_workspace_layout (int num_workspaces, int space_index, Wnck.WorkspaceLayout layout); public void change_workspace_count (int count); public void force_update (); + [Deprecated] public static void free_workspace_layout (Wnck.WorkspaceLayout layout); public static unowned Wnck.Screen @get (int index); public unowned Wnck.Window get_active_window (); @@ -254,6 +256,7 @@ namespace Wnck { public static Wnck.ResourceUsage xid_read (Gdk.Display gdk_display, ulong xid); } [CCode (cheader_filename = "libwnck/libwnck.h", has_type_id = false)] + [Deprecated] public struct WorkspaceLayout { public int rows; public int cols; diff --git a/vapi/poppler-glib.vapi b/vapi/poppler-glib.vapi index 48df6db13d..bd7de1b84b 100644 --- a/vapi/poppler-glib.vapi +++ b/vapi/poppler-glib.vapi @@ -425,6 +425,7 @@ namespace Poppler { public void render_for_printing_with_options ([CCode (type = "cairo_t*")] Cairo.Context cairo, Poppler.PrintFlags options); public void render_selection ([CCode (type = "cairo_t*")] Cairo.Context cairo, Poppler.Rectangle selection, Poppler.Rectangle old_selection, Poppler.SelectionStyle style, Poppler.Color glyph_color, Poppler.Color background_color); public void render_to_ps (Poppler.PSFile ps_file); + [Deprecated] public static void selection_region_free (GLib.List<Poppler.Rectangle> region); public string label { owned get; } }
b43b71208e28d02ec1f07b4761195d66ba4337e8
Delta Spike
DELTASPIKE-354 prevent NPE when passing null to a @MessageBundle
c
https://github.com/apache/deltaspike
diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/MessageBundleInvocationHandler.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/MessageBundleInvocationHandler.java index 3bb99f7e9..ae84341df 100644 --- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/MessageBundleInvocationHandler.java +++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/MessageBundleInvocationHandler.java @@ -138,12 +138,16 @@ private List<Serializable> resolveMessageArguments(Object[] args) { Object arg = args[i]; - if (i == 0 && MessageContext.class.isAssignableFrom(args[0].getClass())) + if (i == 0 && arg != null && MessageContext.class.isAssignableFrom(arg.getClass())) { continue; } - if (arg instanceof Serializable) + if (arg == null) + { + arguments.add("'null'"); + } + else if (arg instanceof Serializable) { arguments.add((Serializable) arg); } @@ -160,7 +164,7 @@ private List<Serializable> resolveMessageArguments(Object[] args) private MessageContext resolveMessageContextFromArguments(Object[] args) { - if (args != null && args.length > 0 && + if (args != null && args.length > 0 && args[0] != null && MessageContext.class.isAssignableFrom(args[0].getClass())) { return (MessageContext) args[0]; diff --git a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/message/SimpleMessageTest.java b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/message/SimpleMessageTest.java index ebebbd7c1..e7767e3e9 100644 --- a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/message/SimpleMessageTest.java +++ b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/message/SimpleMessageTest.java @@ -91,4 +91,12 @@ public void testDefaultLocaleInMessage() String result = simpleMessage.welcomeWithFloatVariable(f); assertEquals(expectedResult, result); } + + @Test + public void testNullMessage() + { + String expectedResult = "Welcome to 'null'"; + String result = simpleMessage.welcomeWithStringVariable(null); + assertEquals(expectedResult, result); + } }
6b8123d7265158c62e4be7aaa20d7b70e3703c10
elasticsearch
Don't allow unallocated indexes to be closed.--Closes -3313-
c
https://github.com/elastic/elasticsearch
diff --git a/src/main/java/org/elasticsearch/cluster/metadata/MetaDataStateIndexService.java b/src/main/java/org/elasticsearch/cluster/metadata/MetaDataStateIndexService.java index 403f7c0f3cd96..9c9272ec84237 100644 --- a/src/main/java/org/elasticsearch/cluster/metadata/MetaDataStateIndexService.java +++ b/src/main/java/org/elasticsearch/cluster/metadata/MetaDataStateIndexService.java @@ -27,6 +27,8 @@ import org.elasticsearch.cluster.block.ClusterBlock; import org.elasticsearch.cluster.block.ClusterBlockLevel; import org.elasticsearch.cluster.block.ClusterBlocks; +import org.elasticsearch.cluster.routing.IndexRoutingTable; +import org.elasticsearch.cluster.routing.IndexShardRoutingTable; import org.elasticsearch.cluster.routing.RoutingTable; import org.elasticsearch.cluster.routing.allocation.AllocationService; import org.elasticsearch.cluster.routing.allocation.RoutingAllocation; @@ -37,6 +39,7 @@ import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.Index; import org.elasticsearch.indices.IndexMissingException; +import org.elasticsearch.indices.IndexPrimaryShardNotAllocatedException; import org.elasticsearch.rest.RestStatus; import java.util.ArrayList; @@ -87,6 +90,13 @@ public ClusterState execute(ClusterState currentState) { if (indexMetaData == null) { throw new IndexMissingException(new Index(index)); } + IndexRoutingTable indexRoutingTable = currentState.routingTable().index(index); + for (IndexShardRoutingTable shard : indexRoutingTable) { + if (!shard.primaryAllocatedPostApi()) { + throw new IndexPrimaryShardNotAllocatedException(new Index(index)); + } + } + if (indexMetaData.state() != IndexMetaData.State.CLOSE) { indicesToClose.add(index); } diff --git a/src/main/java/org/elasticsearch/indices/IndexPrimaryShardNotAllocatedException.java b/src/main/java/org/elasticsearch/indices/IndexPrimaryShardNotAllocatedException.java new file mode 100644 index 0000000000000..9523a90a50c4d --- /dev/null +++ b/src/main/java/org/elasticsearch/indices/IndexPrimaryShardNotAllocatedException.java @@ -0,0 +1,40 @@ +/* + * 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.indices; + +import org.elasticsearch.index.Index; +import org.elasticsearch.index.IndexException; +import org.elasticsearch.rest.RestStatus; + +/** + * Thrown when some action cannot be performed because the primary shard of + * some shard group in an index has not been allocated post api action. + */ +public class IndexPrimaryShardNotAllocatedException extends IndexException { + + public IndexPrimaryShardNotAllocatedException(Index index) { + super(index, "primary not allocated post api"); + } + + @Override + public RestStatus status() { + return RestStatus.CONFLICT; + } +} diff --git a/src/test/java/org/elasticsearch/test/integration/indices/settings/UpdateSettingsTests.java b/src/test/java/org/elasticsearch/test/integration/indices/settings/UpdateSettingsTests.java index 6fd838bc9c954..f2e95e6284095 100644 --- a/src/test/java/org/elasticsearch/test/integration/indices/settings/UpdateSettingsTests.java +++ b/src/test/java/org/elasticsearch/test/integration/indices/settings/UpdateSettingsTests.java @@ -20,7 +20,9 @@ package org.elasticsearch.test.integration.indices.settings; import org.elasticsearch.ElasticSearchIllegalArgumentException; +import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.cluster.metadata.IndexMetaData; +import org.elasticsearch.common.Priority; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.test.integration.AbstractSharedClusterTest; import org.junit.Test; @@ -63,6 +65,10 @@ public void testOpenCloseUpdateSettings() throws Exception { // now close the index, change the non dynamic setting, and see that it applies + // Wait for the index to turn green before attempting to close it + ClusterHealthResponse health = client().admin().cluster().prepareHealth().setTimeout("30s").setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet(); + assertThat(health.isTimedOut(), equalTo(false)); + client().admin().indices().prepareClose("test").execute().actionGet(); client().admin().indices().prepareUpdateSettings("test") diff --git a/src/test/java/org/elasticsearch/test/integration/indices/state/SimpleIndexStateTests.java b/src/test/java/org/elasticsearch/test/integration/indices/state/SimpleIndexStateTests.java index ddc36292b0483..752b57fa6100f 100644 --- a/src/test/java/org/elasticsearch/test/integration/indices/state/SimpleIndexStateTests.java +++ b/src/test/java/org/elasticsearch/test/integration/indices/state/SimpleIndexStateTests.java @@ -19,9 +19,13 @@ package org.elasticsearch.test.integration.indices.state; +import junit.framework.Assert; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; +import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; +import org.elasticsearch.action.admin.indices.close.CloseIndexResponse; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; +import org.elasticsearch.action.admin.indices.settings.UpdateSettingsResponse; import org.elasticsearch.action.admin.indices.status.IndicesStatusResponse; import org.elasticsearch.cluster.block.ClusterBlockException; import org.elasticsearch.cluster.metadata.IndexMetaData; @@ -29,8 +33,10 @@ import org.elasticsearch.common.Priority; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; +import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.SettingsException; import org.elasticsearch.indices.IndexMissingException; +import org.elasticsearch.indices.IndexPrimaryShardNotAllocatedException; import org.elasticsearch.test.integration.AbstractNodesTests; import org.junit.After; import org.junit.Test; @@ -107,6 +113,45 @@ public void testSimpleOpenClose() { client("node1").prepareIndex("test", "type1", "1").setSource("field1", "value1").execute().actionGet(); } + @Test + public void testFastCloseAfterCreateDoesNotClose() { + logger.info("--> starting two nodes...."); + startNode("node1"); + startNode("node2"); + + logger.info("--> creating test index that cannot be allocated"); + client("node1").admin().indices().prepareCreate("test").setSettings(ImmutableSettings.settingsBuilder() + .put("index.routing.allocation.include.tag", "no_such_node") + .put("index.number_of_replicas", 1).build()).execute().actionGet(); + + ClusterHealthResponse health = client("node1").admin().cluster().prepareHealth("test").setWaitForNodes("2").execute().actionGet(); + assertThat(health.isTimedOut(), equalTo(false)); + assertThat(health.getStatus(), equalTo(ClusterHealthStatus.RED)); + + try { + client().admin().indices().prepareClose("test").execute().actionGet(); + Assert.fail("Exception should have been thrown"); + } catch(IndexPrimaryShardNotAllocatedException e) { + // expected + } + + logger.info("--> updating test index settings to allow allocation"); + client("node1").admin().indices().prepareUpdateSettings("test").setSettings(ImmutableSettings.settingsBuilder() + .put("index.routing.allocation.include.tag", "").build()).execute().actionGet(); + + logger.info("--> waiting for green status"); + health = client("node1").admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForNodes("2").execute().actionGet(); + assertThat(health.isTimedOut(), equalTo(false)); + + ClusterStateResponse stateResponse = client("node1").admin().cluster().prepareState().execute().actionGet(); + assertThat(stateResponse.getState().metaData().index("test").state(), equalTo(IndexMetaData.State.OPEN)); + assertThat(stateResponse.getState().routingTable().index("test").shards().size(), equalTo(5)); + assertThat(stateResponse.getState().routingTable().index("test").shardsWithState(ShardRoutingState.STARTED).size(), equalTo(10)); + + logger.info("--> indexing a simple document"); + client("node1").prepareIndex("test", "type1", "1").setSource("field1", "value1").execute().actionGet(); + } + @Test public void testConsistencyAfterIndexCreationFailure() { logger.info("--> starting one node....");
0ffe72386589ad6a7f52f95a68929277a31cf719
Vala
Support (unowned type)[] syntax for transfer-container arrays Fixes bug 571486
a
https://github.com/GNOME/vala/
diff --git a/tests/Makefile.am b/tests/Makefile.am index 21da161c7c..4833286d85 100644 --- a/tests/Makefile.am +++ b/tests/Makefile.am @@ -22,6 +22,7 @@ TESTS = \ basic-types/arrays.vala \ basic-types/pointers.vala \ basic-types/sizeof.vala \ + basic-types/bug571486.vala \ basic-types/bug591552.vala \ basic-types/bug595751.vala \ basic-types/bug596637.vala \ diff --git a/tests/basic-types/bug571486.vala b/tests/basic-types/bug571486.vala new file mode 100644 index 0000000000..4ba922ec23 --- /dev/null +++ b/tests/basic-types/bug571486.vala @@ -0,0 +1,29 @@ +public unowned (unowned string)[] var1 = null; +public (unowned string)[] var2 = null; + +class Foo { + public (unowned string)[] var3 = null; + + public (unowned string)[] meth ((unowned string)[] var4) { + var3 = ((unowned string)[]) var4; + return ((unowned string)[]) var3; + } +} + +void main () { + Object o1 = new Object (); + Object o2 = new Object (); + + (unowned Object)[] test = new (unowned Object)[] { o1 }; + assert (o1.ref_count == 1); + test[0] = o2; + assert (o1.ref_count == 1); + assert (o2.ref_count == 1); + + test = null; + assert (o1.ref_count == 1); + assert (o2.ref_count == 1); + + int[] i = new int[42]; + int j = (((int*) i)[4] + 5); +} \ No newline at end of file diff --git a/vala/valaparser.vala b/vala/valaparser.vala index 75ba5a4291..3a478bc0c9 100644 --- a/vala/valaparser.vala +++ b/vala/valaparser.vala @@ -379,14 +379,25 @@ public class Vala.Parser : CodeVisitor { accept (TokenType.OWNED); accept (TokenType.UNOWNED); accept (TokenType.WEAK); - if (accept (TokenType.VOID)) { + + if (is_inner_array_type ()) { + expect (TokenType.OPEN_PARENS); + expect (TokenType.UNOWNED); + skip_type (); + expect (TokenType.CLOSE_PARENS); + expect (TokenType.OPEN_BRACKET); + prev (); } else { - skip_symbol_name (); - skip_type_argument_list (); - } - while (accept (TokenType.STAR)) { + if (accept (TokenType.VOID)) { + } else { + skip_symbol_name (); + skip_type_argument_list (); + } + while (accept (TokenType.STAR)) { + } + accept (TokenType.INTERR); } - accept (TokenType.INTERR); + while (accept (TokenType.OPEN_BRACKET)) { do { // required for decision between expression and declaration statement @@ -401,50 +412,73 @@ public class Vala.Parser : CodeVisitor { accept (TokenType.HASH); } - DataType parse_type (bool owned_by_default, bool can_weak_ref) throws ParseError { + bool is_inner_array_type () { + var begin = get_location (); + + var result = accept (TokenType.OPEN_PARENS) && accept (TokenType.UNOWNED) && current() != TokenType.CLOSE_PARENS; + rollback (begin); + return result; + } + + DataType parse_type (bool owned_by_default, bool can_weak_ref, bool require_unowned = false) throws ParseError { var begin = get_location (); bool is_dynamic = accept (TokenType.DYNAMIC); bool value_owned = owned_by_default; - if (owned_by_default) { - if (accept (TokenType.UNOWNED)) { - value_owned = false; - } else if (accept (TokenType.WEAK)) { - if (!can_weak_ref && !context.deprecated) { - Report.warning (get_last_src (), "deprecated syntax, use `unowned` modifier"); + if (require_unowned) { + expect (TokenType.UNOWNED); + } else { + if (owned_by_default) { + if (accept (TokenType.UNOWNED)) { + value_owned = false; + } else if (accept (TokenType.WEAK)) { + if (!can_weak_ref && !context.deprecated) { + Report.warning (get_last_src (), "deprecated syntax, use `unowned` modifier"); + } + value_owned = false; } - value_owned = false; + } else { + value_owned = accept (TokenType.OWNED); } - } else { - value_owned = accept (TokenType.OWNED); } DataType type; - if (!is_dynamic && value_owned == owned_by_default && accept (TokenType.VOID)) { - type = new VoidType (get_src (begin)); - } else { - var sym = parse_symbol_name (); - List<DataType> type_arg_list = parse_type_argument_list (false); + bool inner_type_owned = true; + if (accept (TokenType.OPEN_PARENS)) { + type = parse_type (false, false, true); + expect (TokenType.CLOSE_PARENS); + + inner_type_owned = false; - type = new UnresolvedType.from_symbol (sym, get_src (begin)); - if (type_arg_list != null) { - foreach (DataType type_arg in type_arg_list) { - type.add_type_argument (type_arg); + expect (TokenType.OPEN_BRACKET); + prev (); + } else { + if (!is_dynamic && value_owned == owned_by_default && accept (TokenType.VOID)) { + type = new VoidType (get_src (begin)); + } else { + var sym = parse_symbol_name (); + List<DataType> type_arg_list = parse_type_argument_list (false); + + type = new UnresolvedType.from_symbol (sym, get_src (begin)); + if (type_arg_list != null) { + foreach (DataType type_arg in type_arg_list) { + type.add_type_argument (type_arg); + } } } - } - - while (accept (TokenType.STAR)) { - type = new PointerType (type, get_src (begin)); - } + + while (accept (TokenType.STAR)) { + type = new PointerType (type, get_src (begin)); + } - if (!(type is PointerType)) { - type.nullable = accept (TokenType.INTERR); + if (!(type is PointerType)) { + type.nullable = accept (TokenType.INTERR); + } } - + // array brackets in types are read from right to left, // this is more logical, especially when nullable arrays // or pointers are involved @@ -462,8 +496,7 @@ public class Vala.Parser : CodeVisitor { } while (accept (TokenType.COMMA)); expect (TokenType.CLOSE_BRACKET); - // arrays contain strong references by default - type.value_owned = true; + type.value_owned = inner_type_owned; var array_type = new ArrayType (type, array_rank, get_src (begin)); array_type.nullable = accept (TokenType.INTERR); @@ -810,6 +843,12 @@ public class Vala.Parser : CodeVisitor { Expression parse_object_or_array_creation_expression () throws ParseError { var begin = get_location (); expect (TokenType.NEW); + + if (is_inner_array_type ()) { + rollback (begin); + return parse_array_creation_expression (); + } + var member = parse_member_name (); if (accept (TokenType.OPEN_PARENS)) { var expr = parse_object_creation_expression (begin, member); @@ -851,6 +890,13 @@ public class Vala.Parser : CodeVisitor { Expression parse_array_creation_expression () throws ParseError { var begin = get_location (); expect (TokenType.NEW); + + bool inner_array_type = is_inner_array_type (); + if (inner_array_type) { + expect (TokenType.OPEN_PARENS); + expect (TokenType.UNOWNED); + } + var member = parse_member_name (); DataType element_type = UnresolvedType.new_from_expression (member); bool is_pointer_type = false; @@ -863,6 +909,14 @@ public class Vala.Parser : CodeVisitor { element_type.nullable = true; } } + + if (inner_array_type) { + expect (TokenType.CLOSE_PARENS); + element_type.value_owned = false; + } else { + element_type.value_owned = true; + } + expect (TokenType.OPEN_BRACKET); bool size_specified = false; @@ -998,6 +1052,9 @@ public class Vala.Parser : CodeVisitor { case TokenType.OPEN_PARENS: next (); switch (current ()) { + case TokenType.UNOWNED: + // inner array type + break; case TokenType.OWNED: // (owned) foo next (); @@ -1008,36 +1065,39 @@ public class Vala.Parser : CodeVisitor { break; case TokenType.VOID: case TokenType.DYNAMIC: + case TokenType.OPEN_PARENS: case TokenType.IDENTIFIER: - var type = parse_type (true, false); - if (accept (TokenType.CLOSE_PARENS)) { - // check follower to decide whether to create cast expression - switch (current ()) { - case TokenType.OP_NEG: - case TokenType.TILDE: - case TokenType.OPEN_PARENS: - case TokenType.TRUE: - case TokenType.FALSE: - case TokenType.INTEGER_LITERAL: - case TokenType.REAL_LITERAL: - case TokenType.CHARACTER_LITERAL: - case TokenType.STRING_LITERAL: - case TokenType.TEMPLATE_STRING_LITERAL: - case TokenType.VERBATIM_STRING_LITERAL: - case TokenType.REGEX_LITERAL: - case TokenType.NULL: - case TokenType.THIS: - case TokenType.BASE: - case TokenType.NEW: - case TokenType.YIELD: - case TokenType.SIZEOF: - case TokenType.TYPEOF: - case TokenType.IDENTIFIER: - case TokenType.PARAMS: - var inner = parse_unary_expression (); - return new CastExpression (inner, type, get_src (begin), false); - default: - break; + if (current () != TokenType.OPEN_PARENS || is_inner_array_type ()) { + var type = parse_type (true, false); + if (accept (TokenType.CLOSE_PARENS)) { + // check follower to decide whether to create cast expression + switch (current ()) { + case TokenType.OP_NEG: + case TokenType.TILDE: + case TokenType.OPEN_PARENS: + case TokenType.TRUE: + case TokenType.FALSE: + case TokenType.INTEGER_LITERAL: + case TokenType.REAL_LITERAL: + case TokenType.CHARACTER_LITERAL: + case TokenType.STRING_LITERAL: + case TokenType.TEMPLATE_STRING_LITERAL: + case TokenType.VERBATIM_STRING_LITERAL: + case TokenType.REGEX_LITERAL: + case TokenType.NULL: + case TokenType.THIS: + case TokenType.BASE: + case TokenType.NEW: + case TokenType.YIELD: + case TokenType.SIZEOF: + case TokenType.TYPEOF: + case TokenType.IDENTIFIER: + case TokenType.PARAMS: + var inner = parse_unary_expression (); + return new CastExpression (inner, type, get_src (begin), false); + default: + break; + } } } break; @@ -1501,7 +1561,6 @@ public class Vala.Parser : CodeVisitor { case TokenType.OP_DEC: case TokenType.BASE: case TokenType.THIS: - case TokenType.OPEN_PARENS: case TokenType.STAR: case TokenType.NEW: stmt = parse_expression_statement (); @@ -1531,6 +1590,10 @@ public class Vala.Parser : CodeVisitor { } bool is_expression () throws ParseError { + if (current () == TokenType.OPEN_PARENS) { + return !is_inner_array_type (); + } + var begin = get_location (); // decide between declaration and expression statement @@ -2169,7 +2232,6 @@ public class Vala.Parser : CodeVisitor { case TokenType.OP_DEC: case TokenType.BASE: case TokenType.THIS: - case TokenType.OPEN_PARENS: case TokenType.STAR: case TokenType.NEW: // statement
188a11bdb925e3a4c1f38f8ff52f0039eb343eaf
spring-framework
Fixed setFavorPathExtension delegation code--
c
https://github.com/spring-projects/spring-framework
diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java index 2d543941af6f..f7b59c3f6c24 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.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. @@ -25,7 +25,6 @@ import java.util.Map; import java.util.Properties; import java.util.Set; - import javax.activation.FileTypeMap; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; @@ -33,6 +32,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.OrderComparator; @@ -95,7 +95,7 @@ public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport private ContentNegotiationManager contentNegotiationManager; - private ContentNegotiationManagerFactoryBean cnManagerFactoryBean = new ContentNegotiationManagerFactoryBean(); + private final ContentNegotiationManagerFactoryBean cnManagerFactoryBean = new ContentNegotiationManagerFactoryBean(); private boolean useNotAcceptableStatusCode = false; @@ -104,10 +104,6 @@ public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport private List<ViewResolver> viewResolvers; - public ContentNegotiatingViewResolver() { - super(); - } - public void setOrder(int order) { this.order = order; } @@ -118,7 +114,9 @@ public int getOrder() { /** * Set the {@link ContentNegotiationManager} to use to determine requested media types. - * If not set, the default constructor is used. + * <p>If not set, ContentNegotiationManager's default constructor will be used, + * applying a {@link org.springframework.web.accept.HeaderContentNegotiationStrategy}. + * @see ContentNegotiationManager#ContentNegotiationManager() */ public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) { this.contentNegotiationManager = contentNegotiationManager; @@ -130,18 +128,16 @@ public void setContentNegotiationManager(ContentNegotiationManager contentNegoti * <p>For instance, when this flag is {@code true} (the default), a request for {@code /hotels.pdf} * will result in an {@code AbstractPdfView} being resolved, while the {@code Accept} header can be the * browser-defined {@code text/html,application/xhtml+xml}. - * * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)} */ @Deprecated public void setFavorPathExtension(boolean favorPathExtension) { - this.cnManagerFactoryBean.setFavorParameter(favorPathExtension); + this.cnManagerFactoryBean.setFavorPathExtension(favorPathExtension); } /** * Indicate whether to use the Java Activation Framework to map from file extensions to media types. * <p>Default is {@code true}, i.e. the Java Activation Framework is used (if available). - * * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)} */ @Deprecated @@ -155,7 +151,6 @@ public void setUseJaf(boolean useJaf) { * <p>For instance, when this flag is {@code true}, a request for {@code /hotels?format=pdf} will result * in an {@code AbstractPdfView} being resolved, while the {@code Accept} header can be the browser-defined * {@code text/html,application/xhtml+xml}. - * * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)} */ @Deprecated @@ -166,7 +161,6 @@ public void setFavorParameter(boolean favorParameter) { /** * Set the parameter name that can be used to determine the requested media type if the {@link * #setFavorParameter} property is {@code true}. The default parameter name is {@code format}. - * * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)} */ @Deprecated @@ -179,7 +173,6 @@ public void setParameterName(String parameterName) { * <p>If set to {@code true}, this view resolver will only refer to the file extension and/or * parameter, as indicated by the {@link #setFavorPathExtension favorPathExtension} and * {@link #setFavorParameter favorParameter} properties. - * * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)} */ @Deprecated @@ -191,7 +184,6 @@ public void setIgnoreAcceptHeader(boolean ignoreAcceptHeader) { * Set the mapping from file extensions to media types. * <p>When this mapping is not set or when an extension is not present, this view resolver * will fall back to using a {@link FileTypeMap} when the Java Action Framework is available. - * * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)} */ @Deprecated @@ -207,7 +199,6 @@ public void setMediaTypes(Map<String, String> mediaTypes) { * Set the default content type. * <p>This content type will be used when file extension, parameter, nor {@code Accept} * header define a content-type, either through being disabled or empty. - * * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)} */ @Deprecated @@ -275,7 +266,7 @@ protected void initServletContext(ServletContext servletContext) { this.cnManagerFactoryBean.setServletContext(servletContext); } - public void afterPropertiesSet() throws Exception { + public void afterPropertiesSet() { if (this.contentNegotiationManager == null) { this.cnManagerFactoryBean.afterPropertiesSet(); this.contentNegotiationManager = this.cnManagerFactoryBean.getObject();
ae360480a9a955030a6621721a649bbf360d3c9a
orientdb
Improved performance by handling begin and end of- offsets in cluster data.--
p
https://github.com/orientechnologies/orientdb
diff --git a/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java b/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java index 94ebc0eea54..035501bda04 100644 --- a/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java +++ b/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java @@ -310,19 +310,19 @@ public long count(final int iClusterId) { return count(new int[] { iClusterId }); } - public long getClusterLastEntryPosition(final int iClusterId) { + public long[] getClusterDataRange(final int iClusterId) { checkConnection(); do { boolean locked = acquireExclusiveLock(); try { - network.writeByte(OChannelBinaryProtocol.CLUSTER_LASTPOS); + network.writeByte(OChannelBinaryProtocol.CLUSTER_DATARANGE); network.writeShort((short) iClusterId); network.flush(); readStatus(); - return network.readLong(); + return new long[]{ network.readLong(), network.readLong()}; } catch (Exception e) { if (handleException("Error on getting last entry position count in cluster: " + iClusterId, e)) break; @@ -331,7 +331,7 @@ public long getClusterLastEntryPosition(final int iClusterId) { releaseExclusiveLock(locked); } } while (true); - return -1; + return null; } public long count(final int[] iClusterIds) { diff --git a/core/src/main/java/com/orientechnologies/orient/core/cache/OCacheRecord.java b/core/src/main/java/com/orientechnologies/orient/core/cache/OCacheRecord.java index 2c05c811838..3eed86bd954 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/cache/OCacheRecord.java +++ b/core/src/main/java/com/orientechnologies/orient/core/cache/OCacheRecord.java @@ -31,140 +31,146 @@ */ @SuppressWarnings("serial") public class OCacheRecord extends OSharedResourceAdaptive { - private final int maxSize; - private LinkedHashMap<String, ORawBuffer> cache; - - /** - * Create the cache of iMaxSize size. - * - * @param iMaxSize - * Maximum number of elements for the cache - */ - public OCacheRecord(final int iMaxSize) { - maxSize = iMaxSize; - - cache = new LinkedHashMap<String, ORawBuffer>(iMaxSize, 0.75f, true) { - @Override - protected boolean removeEldestEntry(java.util.Map.Entry<String, ORawBuffer> iEldest) { - return size() > maxSize; - } - }; - } - - public void pushRecord(final String iRecord, ORawBuffer iContent) { - if (maxSize == 0) - return; - - final boolean locked = acquireExclusiveLock(); - - try { - cache.put(iRecord, iContent); - - } finally { - releaseExclusiveLock(locked); - } - } - - /** - * Find a record in cache by String - * - * @param iRecord - * String instance - * @return The record buffer if found, otherwise null - */ - public ORawBuffer getRecord(final String iRecord) { - if (maxSize == 0) - return null; - - final boolean locked = acquireSharedLock(); - - try { - return cache.get(iRecord); - - } finally { - releaseSharedLock(locked); - } - } - - public ORawBuffer popRecord(final String iRecord) { - if (maxSize == 0) - return null; - - final boolean locked = acquireExclusiveLock(); - - try { - ORawBuffer buffer = cache.remove(iRecord); - - if (buffer != null) - OProfiler.getInstance().updateStatistic("Cache.reused", +1); - - return buffer; - } finally { - releaseExclusiveLock(locked); - } - } - - public void removeRecord(final String iRecord) { - if (maxSize == 0) - return; - - final boolean locked = acquireExclusiveLock(); - - try { - cache.remove(iRecord); - - } finally { - releaseExclusiveLock(locked); - } - } - - /** - * Remove multiple records from the cache in one shot saving the cost of locking for each record. - * - * @param iRecords - * List of Strings - */ - public void removeRecords(final List<String> iRecords) { - if (maxSize == 0) - return; - - final boolean locked = acquireExclusiveLock(); - - try { - for (String id : iRecords) - cache.remove(id); - - } finally { - releaseExclusiveLock(locked); - } - } - - public void clear() { - if (maxSize == 0) - return; - - final boolean locked = acquireExclusiveLock(); - - try { - cache.clear(); - - } finally { - releaseExclusiveLock(locked); - } - } + private final int maxSize; + private LinkedHashMap<String, ORawBuffer> cache; + + /** + * Create the cache of iMaxSize size. + * + * @param iMaxSize + * Maximum number of elements for the cache + */ + public OCacheRecord(final int iMaxSize) { + maxSize = iMaxSize; + + cache = new LinkedHashMap<String, ORawBuffer>(iMaxSize, 0.75f, true) { + @Override + protected boolean removeEldestEntry(java.util.Map.Entry<String, ORawBuffer> iEldest) { + return size() > maxSize; + } + }; + } + + public void pushRecord(final String iRecord, ORawBuffer iContent) { + if (maxSize == 0) + return; + + final boolean locked = acquireExclusiveLock(); + + try { + cache.put(iRecord, iContent); + + } finally { + releaseExclusiveLock(locked); + } + } + + /** + * Find a record in cache by String + * + * @param iRecord + * String instance + * @return The record buffer if found, otherwise null + */ + public ORawBuffer getRecord(final String iRecord) { + if (maxSize == 0) + return null; + + final boolean locked = acquireSharedLock(); + + try { + return cache.get(iRecord); + + } finally { + releaseSharedLock(locked); + } + } + + public ORawBuffer popRecord(final String iRecord) { + if (maxSize == 0) + return null; + + final boolean locked = acquireExclusiveLock(); + + try { + ORawBuffer buffer = cache.remove(iRecord); + + if (buffer != null) + OProfiler.getInstance().updateStatistic("Cache.reused", +1); + + return buffer; + } finally { + releaseExclusiveLock(locked); + } + } + + public void removeRecord(final String iRecord) { + if (maxSize == 0) + return; + + final boolean locked = acquireExclusiveLock(); + + try { + cache.remove(iRecord); + + } finally { + releaseExclusiveLock(locked); + } + } + + /** + * Remove multiple records from the cache in one shot saving the cost of locking for each record. + * + * @param iRecords + * List of Strings + */ + public void removeRecords(final List<String> iRecords) { + if (maxSize == 0) + return; + + final boolean locked = acquireExclusiveLock(); + + try { + for (String id : iRecords) + cache.remove(id); + + } finally { + releaseExclusiveLock(locked); + } + } + + public void clear() { + if (maxSize == 0) + return; - public int getMaxSize() { - return maxSize; - } + final boolean locked = acquireExclusiveLock(); + + try { + cache.clear(); + + } finally { + releaseExclusiveLock(locked); + } + } + + public int getMaxSize() { + return maxSize; + } + + public int size() { + final boolean locked = acquireSharedLock(); + + try { + return cache.size(); + + } finally { + releaseSharedLock(locked); + } + } + + @Override + public String toString() { + return "Cached items=" + cache.size() + ", maxSize=" + maxSize; + } - public int size() { - final boolean locked = acquireSharedLock(); - - try { - return cache.size(); - - } finally { - releaseSharedLock(locked); - } - } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/graph/ODatabaseGraphTx.java b/core/src/main/java/com/orientechnologies/orient/core/db/graph/ODatabaseGraphTx.java index a35381ad97e..07f25a81db7 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/graph/ODatabaseGraphTx.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/graph/ODatabaseGraphTx.java @@ -89,7 +89,7 @@ public OGraphElement load(final OGraphElement iObject) { public OGraphElement load(final ORID iRecordId) { if (iRecordId == null) return null; - + // TRY IN LOCAL CACHE ODocument doc = getRecordById(iRecordId); if (doc == null) { diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphEdge.java b/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphEdge.java index b99c0b8d103..6bf75ecfd91 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphEdge.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/graph/OGraphEdge.java @@ -144,7 +144,7 @@ public static void delete(final ODatabaseGraphTx iDatabase, final ODocument iEdg targetVertex.setDirty(); targetVertex.save(); - if (iDatabase.existsUserObjectByRecord(sourceVertex)) { + if (iDatabase.existsUserObjectByRecord(iEdge)) { final OGraphEdge edge = (OGraphEdge) iDatabase.getUserObjectByRecord(iEdge, null); iDatabase.unregisterPojo(edge, iEdge); } diff --git a/core/src/main/java/com/orientechnologies/orient/core/iterator/OGraphEdgeIterator.java b/core/src/main/java/com/orientechnologies/orient/core/iterator/OGraphEdgeIterator.java index 0c7e5a4381b..c722dffa7b1 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/iterator/OGraphEdgeIterator.java +++ b/core/src/main/java/com/orientechnologies/orient/core/iterator/OGraphEdgeIterator.java @@ -17,6 +17,7 @@ import com.orientechnologies.orient.core.db.graph.ODatabaseGraphTx; import com.orientechnologies.orient.core.db.graph.OGraphEdge; +import com.orientechnologies.orient.core.record.impl.ODocument; /** * Iterator to browse all the edges. @@ -31,7 +32,13 @@ public OGraphEdgeIterator(final ODatabaseGraphTx iDatabase) { } public OGraphEdge next(final String iFetchPlan) { - return new OGraphEdge(database, underlying.next()); + final ODocument doc = underlying.next(); + + OGraphEdge v = (OGraphEdge) database.getUserObjectByRecord(doc, null); + if (v != null) + return v; + + return new OGraphEdge(database, doc); } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/iterator/OGraphVertexIterator.java b/core/src/main/java/com/orientechnologies/orient/core/iterator/OGraphVertexIterator.java index 2d14bd4998c..52d529ac016 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/iterator/OGraphVertexIterator.java +++ b/core/src/main/java/com/orientechnologies/orient/core/iterator/OGraphVertexIterator.java @@ -17,6 +17,7 @@ import com.orientechnologies.orient.core.db.graph.ODatabaseGraphTx; import com.orientechnologies.orient.core.db.graph.OGraphVertex; +import com.orientechnologies.orient.core.record.impl.ODocument; /** * Iterator to browse all the vertexes. @@ -31,6 +32,13 @@ public OGraphVertexIterator(final ODatabaseGraphTx iDatabase) { } public OGraphVertex next(final String iFetchPlan) { - return new OGraphVertex(database, underlying.next()); + final ODocument doc = underlying.next(); + + final OGraphVertex v = (OGraphVertex) database.getUserObjectByRecord(doc, + null); + if (v != null) + return v; + + return new OGraphVertex(database, doc); } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorCluster.java b/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorCluster.java index 815f1cc9077..9f6e7b936ea 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorCluster.java +++ b/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorCluster.java @@ -28,16 +28,19 @@ * @author Luca Garulli * * @param <T> - * Record Type + * Record Type */ -public class ORecordIteratorCluster<REC extends ORecordInternal<?>> extends ORecordIterator<REC> { - protected int currentClusterId; - protected long rangeFrom; - protected long rangeTo; - protected long lastClusterPosition; - protected long totalAvailableRecords; - - public ORecordIteratorCluster(final ODatabaseRecord<REC> iDatabase, final ODatabaseRecordAbstract<REC> iLowLevelDatabase, +public class ORecordIteratorCluster<REC extends ORecordInternal<?>> extends + ORecordIterator<REC> { + protected int currentClusterId; + protected long rangeFrom; + protected long rangeTo; + protected long firstClusterPosition; + protected long lastClusterPosition; + protected long totalAvailableRecords; + + public ORecordIteratorCluster(final ODatabaseRecord<REC> iDatabase, + final ODatabaseRecordAbstract<REC> iLowLevelDatabase, final int iClusterId) { super(iDatabase, iLowLevelDatabase); if (iClusterId == ORID.CLUSTER_ID_INVALID) @@ -47,7 +50,13 @@ public ORecordIteratorCluster(final ODatabaseRecord<REC> iDatabase, final ODatab rangeFrom = -1; rangeTo = -1; - lastClusterPosition = database.getStorage().getClusterLastEntryPosition(currentClusterId); + long[] range = database.getStorage().getClusterDataRange( + currentClusterId); + firstClusterPosition = range[0]; + lastClusterPosition = range[1]; + +// currentClusterPosition = firstClusterPosition - 1; + totalAvailableRecords = database.countClusterElements(currentClusterId); } @@ -72,9 +81,11 @@ public boolean hasNext() { } /** - * Return the element at the current position and move backward the cursor to the previous position available. + * Return the element at the current position and move backward the cursor + * to the previous position available. * - * @return the previous record found, otherwise the NoSuchElementException exception is thrown when no more records are found. + * @return the previous record found, otherwise the NoSuchElementException + * exception is thrown when no more records are found. */ @Override public REC previous() { @@ -91,9 +102,11 @@ public REC previous() { } /** - * Return the element at the current position and move forward the cursor to the next position available. + * Return the element at the current position and move forward the cursor to + * the next position available. * - * @return the next record found, otherwise the NoSuchElementException exception is thrown when no more records are found. + * @return the next record found, otherwise the NoSuchElementException + * exception is thrown when no more records are found. */ public REC next() { // ITERATE UNTIL THE NEXT GOOD RECORD @@ -115,7 +128,8 @@ public REC current() { } /** - * Move the iterator to the begin of the range. If no range was specified move to the first record of the cluster. + * Move the iterator to the begin of the range. If no range was specified + * move to the first record of the cluster. * * @return The object itself */ @@ -126,7 +140,8 @@ public ORecordIterator<REC> begin() { } /** - * Move the iterator to the end of the range. If no range was specified move to the last record of the cluster. + * Move the iterator to the end of the range. If no range was specified move + * to the last record of the cluster. * * @return The object itself */ @@ -140,14 +155,16 @@ public ORecordIterator<REC> last() { * Define the range where move the iterator forward and backward. * * @param iFrom - * Lower bound limit of the range + * Lower bound limit of the range * @param iEnd - * Upper bound limit of the range + * Upper bound limit of the range * @return */ - public ORecordIteratorCluster<REC> setRange(final long iFrom, final long iEnd) { - currentClusterPosition = iFrom; + public ORecordIteratorCluster<REC> setRange(final long iFrom, + final long iEnd) { + firstClusterPosition = iFrom; rangeTo = iEnd; + currentClusterPosition = firstClusterPosition; return this; } @@ -157,11 +174,19 @@ public ORecordIteratorCluster<REC> setRange(final long iFrom, final long iEnd) { * @return */ public long getRangeFrom() { - return Math.max(rangeFrom, -1); + if (!liveUpdated) + return firstClusterPosition - 1; + + final long limit = database.getStorage().getClusterDataRange( + currentClusterId)[0] - 1; + if (rangeFrom > -1) + return Math.max(rangeFrom, limit); + return limit; } /** - * Return the upper bound limit of the range if any, otherwise the last record. + * Return the upper bound limit of the range if any, otherwise the last + * record. * * @return */ @@ -169,33 +194,45 @@ public long getRangeTo() { if (!liveUpdated) return lastClusterPosition + 1; - final long limit = database.getStorage().getClusterLastEntryPosition(currentClusterId) + 1; + final long limit = database.getStorage().getClusterDataRange( + currentClusterId)[1] + 1; if (rangeTo > -1) return Math.min(rangeTo, limit); return limit; } /** - * Tell to the iterator that the upper limit must be checked at every cycle. Useful when concurrent deletes or additions change - * the size of the cluster while you're browsing it. Default is false. + * Tell to the iterator that the upper limit must be checked at every cycle. + * Useful when concurrent deletes or additions change the size of the + * cluster while you're browsing it. Default is false. * * @param iLiveUpdated - * True to activate it, otherwise false (default) + * True to activate it, otherwise false (default) * @see #isLiveUpdated() */ @Override public ORecordIterator<REC> setLiveUpdated(boolean iLiveUpdated) { super.setLiveUpdated(iLiveUpdated); - // SET THE UPPER LIMIT TO -1 IF IT'S ENABLED - lastClusterPosition = iLiveUpdated ? -1 : database.getStorage().getClusterLastEntryPosition(currentClusterId); + // SET THE RANGE LIMITS + if (iLiveUpdated) { + firstClusterPosition = -1; + lastClusterPosition = -1; + } else { + long[] range = database.getStorage().getClusterDataRange( + currentClusterId); + firstClusterPosition = range[0]; + lastClusterPosition = range[1]; + } + totalAvailableRecords = database.countClusterElements(currentClusterId); return this; } /** - * Read the current record and increment the counter if the record was found. + * Read the current record and increment the counter if the record was + * found. * * @param iRecord * @return @@ -207,7 +244,8 @@ private REC readCurrentRecord(REC iRecord, final int iMovement) { currentClusterPosition += iMovement; - iRecord = lowLevelDatabase.executeReadRecord(currentClusterId, currentClusterPosition, iRecord, fetchPlan); + iRecord = lowLevelDatabase.executeReadRecord(currentClusterId, + currentClusterPosition, iRecord, fetchPlan); if (iRecord != null) browsedRecords++; diff --git a/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorMultiCluster.java b/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorMultiCluster.java index 90e5fbe1e53..bbeb67113f1 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorMultiCluster.java +++ b/core/src/main/java/com/orientechnologies/orient/core/iterator/ORecordIteratorMultiCluster.java @@ -33,177 +33,194 @@ * Record Type */ public class ORecordIteratorMultiCluster<REC extends ORecordInternal<?>> extends ORecordIterator<REC> { - protected final int[] clusterIds; - protected int currentClusterIdx; - - protected int lastClusterId; - protected long lastClusterPosition; - protected long totalAvailableRecords; - - public ORecordIteratorMultiCluster(final ODatabaseRecord<REC> iDatabase, final ODatabaseRecordAbstract<REC> iLowLevelDatabase, - final int[] iClusterIds) { - super(iDatabase, iLowLevelDatabase); - - clusterIds = iClusterIds; - - currentClusterIdx = 0; // START FROM THE FIRST CLUSTER - currentClusterPosition = -1; // DEFAULT = START FROM THE BEGIN - - lastClusterId = clusterIds[clusterIds.length - 1]; - lastClusterPosition = database.getStorage().getClusterLastEntryPosition(lastClusterId); - - totalAvailableRecords = database.countClusterElements(iClusterIds); - } - - @Override - public boolean hasPrevious() { - if (limit > -1 && browsedRecords >= limit) - // LIMIT REACHED - return false; - - return currentClusterPosition > 0; - } - - public boolean hasNext() { - if (limit > -1 && browsedRecords >= limit) - // LIMIT REACHED - return false; - - if (browsedRecords >= totalAvailableRecords) - return false; - - if (currentClusterIdx < clusterIds.length - 1) - // PRESUME THAT IF IT'S NOT AT THE LAST CLUSTER THERE COULD BE OTHER ELEMENTS - return true; - - if (liveUpdated) - return currentClusterPosition < database.getStorage().getClusterLastEntryPosition(lastClusterId); - - return currentClusterPosition < lastClusterPosition; - } - - /** - * Return the element at the current position and move backward the cursor to the previous position available. - * - * @return the previous record found, otherwise the NoSuchElementException exception is thrown when no more records are found. - */ - @Override - public REC previous() { - final REC record = getRecord(); - - // ITERATE UNTIL THE PREVIOUS GOOD RECORD - while (currentClusterIdx > -1) { - - // MOVE BACKWARD IN THE CURRENT CLUSTER - while (hasPrevious()) { - if (readCurrentRecord(record, -1) != null) - // FOUND - return record; - } - - // CLUSTER EXHAUSTED, TRY WITH THE PREVIOUS ONE - currentClusterIdx--; - } - - throw new NoSuchElementException(); - } - - /** - * Return the element at the current position and move forward the cursor to the next position available. - * - * @return the next record found, otherwise the NoSuchElementException exception is thrown when no more records are found. - */ - public REC next() { - final REC record = getRecord(); - - // ITERATE UNTIL THE NEXT GOOD RECORD - while (currentClusterIdx < clusterIds.length) { - - // MOVE FORWARD IN THE CURRENT CLUSTER - while (hasNext()) { - if (readCurrentRecord(record, +1) != null) - // FOUND - return record; - } - - // CLUSTER EXHAUSTED, TRY WITH THE NEXT ONE - currentClusterIdx++; - } - - throw new NoSuchElementException(); - } - - public REC current() { - final REC record = getRecord(); - return readCurrentRecord(record, 0); - } - - /** - * Move the iterator to the begin of the range. If no range was specified move to the first record of the cluster. - * - * @return The object itself - */ - @Override - public ORecordIterator<REC> begin() { - currentClusterIdx = 0; - currentClusterPosition = -1; - return this; - } - - /** - * Move the iterator to the end of the range. If no range was specified move to the last record of the cluster. - * - * @return The object itself - */ - @Override - public ORecordIterator<REC> last() { - currentClusterIdx = clusterIds.length - 1; - currentClusterPosition = liveUpdated ? database.countClusterElements(clusterIds[currentClusterIdx]) : lastClusterPosition + 1; - return this; - } - - /** - * Tell to the iterator that the upper limit must be checked at every cycle. Useful when concurrent deletes or additions change - * the size of the cluster while you're browsing it. Default is false. - * - * @param iLiveUpdated - * True to activate it, otherwise false (default) - * @see #isLiveUpdated() - */ - @Override - public ORecordIterator<REC> setLiveUpdated(boolean iLiveUpdated) { - super.setLiveUpdated(iLiveUpdated); - - // SET THE UPPER LIMIT TO -1 IF IT'S ENABLED - lastClusterPosition = iLiveUpdated ? -1 : database.countClusterElements(lastClusterId); - - return this; - } - - /** - * Read the current record and increment the counter if the record was found. - * - * @param iRecord - * @return - */ - private REC readCurrentRecord(REC iRecord, final int iMovement) { - if (limit > -1 && browsedRecords >= limit) - // LIMIT REACHED - return null; - - currentClusterPosition += iMovement; - - iRecord = loadRecord(iRecord); - - if (iRecord != null) { - browsedRecords++; - return iRecord; - } - - return null; - } - - protected REC loadRecord(final REC iRecord) { - return lowLevelDatabase.executeReadRecord(clusterIds[currentClusterIdx], currentClusterPosition, iRecord, fetchPlan); - } + protected final int[] clusterIds; + protected int currentClusterIdx; + + protected int lastClusterId; + protected long firstClusterPosition; + protected long lastClusterPosition; + protected long totalAvailableRecords; + + public ORecordIteratorMultiCluster(final ODatabaseRecord<REC> iDatabase, final ODatabaseRecordAbstract<REC> iLowLevelDatabase, + final int[] iClusterIds) { + super(iDatabase, iLowLevelDatabase); + + clusterIds = iClusterIds; + + currentClusterIdx = 0; // START FROM THE FIRST CLUSTER + + lastClusterId = clusterIds[clusterIds.length - 1]; + + long[] range = database.getStorage().getClusterDataRange(lastClusterId); + firstClusterPosition = range[0]; + lastClusterPosition = range[1]; + + currentClusterPosition = firstClusterPosition - 1; + + totalAvailableRecords = database.countClusterElements(iClusterIds); + } + + @Override + public boolean hasPrevious() { + if (limit > -1 && browsedRecords >= limit) + // LIMIT REACHED + return false; + + if (liveUpdated) + return currentClusterPosition > database.getStorage().getClusterDataRange(lastClusterId)[0]; + + return currentClusterPosition > firstClusterPosition; + } + + public boolean hasNext() { + if (limit > -1 && browsedRecords >= limit) + // LIMIT REACHED + return false; + + if (browsedRecords >= totalAvailableRecords) + return false; + + if (currentClusterIdx < clusterIds.length - 1) + // PRESUME THAT IF IT'S NOT AT THE LAST CLUSTER THERE COULD BE OTHER ELEMENTS + return true; + + if (liveUpdated) + return currentClusterPosition < database.getStorage().getClusterDataRange(lastClusterId)[1]; + + return currentClusterPosition < lastClusterPosition; + } + + /** + * Return the element at the current position and move backward the cursor to the previous position available. + * + * @return the previous record found, otherwise the NoSuchElementException exception is thrown when no more records are found. + */ + @Override + public REC previous() { + final REC record = getRecord(); + + // ITERATE UNTIL THE PREVIOUS GOOD RECORD + while (currentClusterIdx > -1) { + + // MOVE BACKWARD IN THE CURRENT CLUSTER + while (hasPrevious()) { + if (readCurrentRecord(record, -1) != null) + // FOUND + return record; + } + + // CLUSTER EXHAUSTED, TRY WITH THE PREVIOUS ONE + currentClusterIdx--; + } + + throw new NoSuchElementException(); + } + + /** + * Return the element at the current position and move forward the cursor to the next position available. + * + * @return the next record found, otherwise the NoSuchElementException exception is thrown when no more records are found. + */ + public REC next() { + final REC record = getRecord(); + + // ITERATE UNTIL THE NEXT GOOD RECORD + while (currentClusterIdx < clusterIds.length) { + + // MOVE FORWARD IN THE CURRENT CLUSTER + while (hasNext()) { + if (readCurrentRecord(record, +1) != null) + // FOUND + return record; + } + + // CLUSTER EXHAUSTED, TRY WITH THE NEXT ONE + currentClusterIdx++; + } + + throw new NoSuchElementException(); + } + + public REC current() { + final REC record = getRecord(); + return readCurrentRecord(record, 0); + } + + /** + * Move the iterator to the begin of the range. If no range was specified move to the first record of the cluster. + * + * @return The object itself + */ + @Override + public ORecordIterator<REC> begin() { + currentClusterIdx = 0; + currentClusterPosition = -1; + return this; + } + + /** + * Move the iterator to the end of the range. If no range was specified move to the last record of the cluster. + * + * @return The object itself + */ + @Override + public ORecordIterator<REC> last() { + currentClusterIdx = clusterIds.length - 1; + currentClusterPosition = liveUpdated ? database.countClusterElements(clusterIds[currentClusterIdx]) : lastClusterPosition + 1; + return this; + } + + /** + * Tell to the iterator that the upper limit must be checked at every cycle. Useful when concurrent deletes or additions change + * the size of the cluster while you're browsing it. Default is false. + * + * @param iLiveUpdated + * True to activate it, otherwise false (default) + * @see #isLiveUpdated() + */ + @Override + public ORecordIterator<REC> setLiveUpdated(boolean iLiveUpdated) { + super.setLiveUpdated(iLiveUpdated); + + // SET THE UPPER LIMIT TO -1 IF IT'S ENABLED + lastClusterPosition = iLiveUpdated ? -1 : database.countClusterElements(lastClusterId); + + if (iLiveUpdated) { + firstClusterPosition = -1; + lastClusterPosition = -1; + } else { + long[] range = database.getStorage().getClusterDataRange(lastClusterId); + firstClusterPosition = range[0]; + lastClusterPosition = range[1]; + } + + return this; + } + + /** + * Read the current record and increment the counter if the record was found. + * + * @param iRecord + * @return + */ + private REC readCurrentRecord(REC iRecord, final int iMovement) { + if (limit > -1 && browsedRecords >= limit) + // LIMIT REACHED + return null; + + currentClusterPosition += iMovement; + + iRecord = loadRecord(iRecord); + + if (iRecord != null) { + browsedRecords++; + return iRecord; + } + + return null; + } + + protected REC loadRecord(final REC iRecord) { + return lowLevelDatabase.executeReadRecord(clusterIds[currentClusterIdx], currentClusterPosition, iRecord, fetchPlan); + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/OCluster.java b/core/src/main/java/com/orientechnologies/orient/core/storage/OCluster.java index 8d15f48b4d9..7735ecbc05d 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/OCluster.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/OCluster.java @@ -68,6 +68,8 @@ public interface OCluster { public long getEntries() throws IOException; + public long getFirstEntryPosition() throws IOException; + public long getLastEntryPosition() throws IOException; /** diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/OClusterPositionIterator.java b/core/src/main/java/com/orientechnologies/orient/core/storage/OClusterPositionIterator.java index 4708ba92f51..221ffc997d7 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/OClusterPositionIterator.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/OClusterPositionIterator.java @@ -19,17 +19,18 @@ import java.util.Iterator; public class OClusterPositionIterator implements Iterator<Long> { - private final OCluster cluster; - private long current = 0; - private final long max; + private final OCluster cluster; + private long current; + private final long max; public OClusterPositionIterator(final OCluster iCluster) throws IOException { cluster = iCluster; + current = cluster.getFirstEntryPosition(); max = cluster.getLastEntryPosition(); } public boolean hasNext() { - return current <= max; + return max > -1 && current <= max; } public Long next() { diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorage.java b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorage.java index 1ba05194a04..a737fee6d10 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorage.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorage.java @@ -142,10 +142,10 @@ public int updateRecord(int iRequesterId, int iClusterId, long iPosition, byte[] public Object command(OCommandRequestText iCommand); /** - * Returns the last entry position in the requested cluster. Useful to know the range of the records. + * Returns a pair of long values telling the begin and end positions of data in the requested cluster. Useful to know the range of the records. * * @param iCurrentClusterId * Cluster id */ - public long getClusterLastEntryPosition(int currentClusterId); + public long[] getClusterDataRange(int currentClusterId); } diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageAbstract.java index 615963520bd..5ed13ce0378 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/OStorageAbstract.java @@ -26,7 +26,7 @@ public abstract class OStorageAbstract extends OSharedResourceAdaptive implement protected String name; protected String url; protected String mode; - protected OCacheRecord cache = new OCacheRecord(2000); + protected OCacheRecord cache = new OCacheRecord(20000); protected boolean open = false; diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFile.java b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFile.java index 6316e93582a..00840b32fc0 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFile.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFile.java @@ -56,6 +56,7 @@ public abstract class OFile { protected String mode; protected static final int HEADER_SIZE = 1024; + protected static final int HEADER_DATA_OFFSET = 128; protected static final int DEFAULT_SIZE = 15000000; protected static final int DEFAULT_INCREMENT_SIZE = -50; // NEGATIVE NUMBER MEANS AS PERCENT OF CURRENT SIZE @@ -67,6 +68,10 @@ public OFile(final String iFileName, final String iMode) throws IOException { protected abstract void readHeader() throws IOException; + public abstract void writeHeaderLong(int iPosition, long iValue) throws IOException; + + public abstract long readHeaderLong(int iPosition) throws IOException; + protected abstract void setSoftlyClosed(boolean b) throws IOException; protected abstract boolean isSoftlyClosed() throws IOException; diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileClassic.java b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileClassic.java index 0b4936b6be0..231949d77ae 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileClassic.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileClassic.java @@ -34,7 +34,7 @@ * <br/> */ public class OFileClassic extends OFile { - protected ByteBuffer internalWriteBuffer = getBuffer(OConstants.SIZE_LONG); + protected ByteBuffer internalWriteBuffer = getBuffer(OConstants.SIZE_LONG); public OFileClassic(String iFileName, String iMode) throws IOException { super(iFileName, iMode); @@ -50,7 +50,8 @@ public void close() throws IOException { } @Override - public void read(int iOffset, byte[] iDestBuffer, int iLenght) throws IOException { + public void read(int iOffset, byte[] iDestBuffer, int iLenght) + throws IOException { iOffset = checkRegions(iOffset, iLenght); ByteBuffer buffer = ByteBuffer.wrap(iDestBuffer); @@ -129,7 +130,9 @@ public void changeSize(int iSize) { openChannel(iSize); } catch (IOException e) { - OLogManager.instance().error(this, "Error on changing the file size to " + iSize + " bytes", e, OIOException.class); + OLogManager.instance().error(this, + "Error on changing the file size to " + iSize + " bytes", + e, OIOException.class); } } @@ -145,7 +148,8 @@ public void synch() { @Override protected void readHeader() throws IOException { size = readData(0, OConstants.SIZE_INT).getInt(); - filledUpTo = readData(OConstants.SIZE_INT, OConstants.SIZE_INT).getInt(); + filledUpTo = readData(OConstants.SIZE_INT, OConstants.SIZE_INT) + .getInt(); } @Override @@ -156,6 +160,19 @@ protected void writeHeader() throws IOException { writeData(buffer, 0); } + @Override + public void writeHeaderLong(int iPosition, long iValue) + throws IOException { + ByteBuffer buffer = getWriteBuffer(OConstants.SIZE_LONG); + buffer.putLong(iValue); + writeData(buffer, HEADER_DATA_OFFSET + iPosition); + } + + @Override + public long readHeaderLong(int iPosition) throws IOException { + return readData(HEADER_DATA_OFFSET + iPosition, OConstants.SIZE_LONG).getLong(); + } + @Override public boolean isSoftlyClosed() throws IOException { return readData(SOFTLY_CLOSED_OFFSET, OConstants.SIZE_BYTE).get() == 1; diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileMMap.java b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileMMap.java index bc658c21bf9..def18923117 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileMMap.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/fs/OFileMMap.java @@ -36,9 +36,9 @@ * <br/> */ public class OFileMMap extends OFile { - protected MappedByteBuffer headerBuffer; - protected int bufferBeginOffset = -1; - protected int bufferSize = 0; + protected MappedByteBuffer headerBuffer; + protected int bufferBeginOffset = -1; + protected int bufferSize = 0; public OFileMMap(String iFileName, String iMode) throws IOException { super(iFileName, iMode); @@ -48,7 +48,8 @@ public OFileMMap(String iFileName, String iMode) throws IOException { public void read(int iOffset, final byte[] iDestBuffer, final int iLenght) { iOffset = checkRegions(iOffset, iLenght); - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, iLenght); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + iLenght); entry.buffer.position(iOffset - entry.beginOffset); entry.buffer.get(iDestBuffer, 0, iLenght); } @@ -56,56 +57,64 @@ public void read(int iOffset, final byte[] iDestBuffer, final int iLenght) { @Override public int readInt(int iOffset) { iOffset = checkRegions(iOffset, OConstants.SIZE_INT); - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, OConstants.SIZE_INT); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + OConstants.SIZE_INT); return entry.buffer.getInt(iOffset - entry.beginOffset); } @Override public long readLong(int iOffset) { iOffset = checkRegions(iOffset, OConstants.SIZE_LONG); - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, OConstants.SIZE_LONG); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + OConstants.SIZE_LONG); return entry.buffer.getLong(iOffset - entry.beginOffset); } @Override public short readShort(int iOffset) { iOffset = checkRegions(iOffset, OConstants.SIZE_SHORT); - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, OConstants.SIZE_SHORT); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + OConstants.SIZE_SHORT); return entry.buffer.getShort(iOffset - entry.beginOffset); } @Override public byte readByte(int iOffset) { iOffset = checkRegions(iOffset, OConstants.SIZE_BYTE); - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, OConstants.SIZE_BYTE); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + OConstants.SIZE_BYTE); return entry.buffer.get(iOffset - entry.beginOffset); } @Override public void writeInt(int iOffset, final int iValue) { iOffset = checkRegions(iOffset, OConstants.SIZE_INT); - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, OConstants.SIZE_INT); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + OConstants.SIZE_INT); entry.buffer.putInt(iOffset - entry.beginOffset, iValue); } @Override public void writeLong(int iOffset, final long iValue) { iOffset = checkRegions(iOffset, OConstants.SIZE_LONG); - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, OConstants.SIZE_LONG); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + OConstants.SIZE_LONG); entry.buffer.putLong(iOffset - entry.beginOffset, iValue); } @Override public void writeShort(int iOffset, final short iValue) { iOffset = checkRegions(iOffset, OConstants.SIZE_SHORT); - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, OConstants.SIZE_SHORT); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + OConstants.SIZE_SHORT); entry.buffer.putShort(iOffset - entry.beginOffset, iValue); } @Override public void writeByte(int iOffset, final byte iValue) { iOffset = checkRegions(iOffset, OConstants.SIZE_BYTE); - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, OConstants.SIZE_BYTE); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + OConstants.SIZE_BYTE); entry.buffer.put(iOffset - entry.beginOffset, iValue); } @@ -114,13 +123,16 @@ public void write(int iOffset, final byte[] iSourceBuffer) { iOffset = checkRegions(iOffset, iSourceBuffer.length); try { - final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, OConstants.SIZE_INT + iSourceBuffer.length); + final OMMapBufferEntry entry = OMMapManager.request(this, iOffset, + OConstants.SIZE_INT + iSourceBuffer.length); entry.buffer.position(iOffset - entry.beginOffset); entry.buffer.put(iSourceBuffer); } catch (BufferOverflowException e) { - OLogManager.instance() - .error(this, "Error on write in the range " + iOffset + "-" + iOffset + iSourceBuffer.length + "." + toString(), e, - OIOException.class); + OLogManager.instance().error( + this, + "Error on write in the range " + iOffset + "-" + iOffset + + iSourceBuffer.length + "." + toString(), e, + OIOException.class); } } @@ -131,7 +143,7 @@ public void changeSize(final int iSize) { } /** - * Do nothing. Use OFileSecure to be sure the file is saved + * Synchronize buffered changes to the file. * * @see OFileMMapSecure */ @@ -160,7 +172,8 @@ protected void readHeader() { // check.append('R'); // check.append('<'); // - // OIntegrityFileManager.instance().check(check.toString(), securityCode); + // OIntegrityFileManager.instance().check(check.toString(), + // securityCode); } @Override @@ -181,11 +194,22 @@ protected void writeHeader() { // check.append('R'); // check.append('<'); // - // securityCode = OIntegrityFileManager.instance().digest(check.toString()); + // securityCode = + // OIntegrityFileManager.instance().digest(check.toString()); // for (int i = 0; i < securityCode.length; ++i) // buffer.put(securityCode[i]); } + @Override + public void writeHeaderLong(final int iPosition, final long iValue) { + headerBuffer.putLong(HEADER_DATA_OFFSET + iPosition, iValue); + } + + @Override + public long readHeaderLong(final int iPosition) { + return headerBuffer.getLong(HEADER_DATA_OFFSET + iPosition); + } + @Override public void close() throws IOException { if (headerBuffer != null) { @@ -210,14 +234,18 @@ protected void setSoftlyClosed(final boolean iValue) { synch(); } - MappedByteBuffer map(final int iBeginOffset, final int iSize) throws IOException { - return channel.map(mode.equals("r") ? FileChannel.MapMode.READ_ONLY : FileChannel.MapMode.READ_WRITE, iBeginOffset - + HEADER_SIZE, iSize); + MappedByteBuffer map(final int iBeginOffset, final int iSize) + throws IOException { + return channel.map(mode.equals("r") ? FileChannel.MapMode.READ_ONLY + : FileChannel.MapMode.READ_WRITE, iBeginOffset + HEADER_SIZE, + iSize); } @Override protected void openChannel(final int iNewSize) throws IOException { super.openChannel(iNewSize); - headerBuffer = channel.map(mode.equals("r") ? FileChannel.MapMode.READ_ONLY : FileChannel.MapMode.READ_WRITE, 0, HEADER_SIZE); + headerBuffer = channel.map( + mode.equals("r") ? FileChannel.MapMode.READ_ONLY + : FileChannel.MapMode.READ_WRITE, 0, HEADER_SIZE); } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocal.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocal.java index b2cd4216694..d8df65005fa 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocal.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocal.java @@ -30,260 +30,342 @@ * <br/> * Record structure:<br/> * <br/> - * +----------------------+----------------------+-------------+----------------------+<br/> + * +----------------------+----------------------+-------------+---------------- ------+<br/> * | DATA SEGMENT........ | DATA OFFSET......... | RECORD TYPE | VERSION............. |<br/> * | 2 bytes = max 2^15-1 | 8 bytes = max 2^63-1 | 1 byte..... | 4 bytes = max 2^31-1 |<br/> - * +----------------------+----------------------+-------------+----------------------+<br/> + * +----------------------+----------------------+-------------+---------------- ------+<br/> * = 15 bytes<br/> */ public class OClusterLocal extends OMultiFileSegment implements OCluster { - private static final String DEF_EXTENSION = ".ocl"; - private static final int RECORD_SIZE = 15; - private static final int DEF_SIZE = 1000000; - public static final String TYPE = "PHYSICAL"; + private static final String DEF_EXTENSION = ".ocl"; + private static final int RECORD_SIZE = 15; + private static final int DEF_SIZE = 1000000; + public static final String TYPE = "PHYSICAL"; - private int id; + private int id; + private long beginOffsetData = -1; + private long endOffsetData = -1; // end of data offset. -1 = latest - protected final OClusterLocalHole holeSegment; + protected final OClusterLocalHole holeSegment; - public OClusterLocal(final OStorageLocal iStorage, final OStoragePhysicalClusterConfiguration iConfig) throws IOException { - super(iStorage, iConfig, DEF_EXTENSION, RECORD_SIZE); - id = iConfig.getId(); + public OClusterLocal(final OStorageLocal iStorage, final OStoragePhysicalClusterConfiguration iConfig) throws IOException { + super(iStorage, iConfig, DEF_EXTENSION, RECORD_SIZE); + id = iConfig.getId(); - iConfig.holeFile = new OStorageClusterHoleConfiguration(iConfig, OStorageVariableParser.DB_PATH_VARIABLE + "/" + iConfig.name, - iConfig.fileType, iConfig.fileMaxSize); + iConfig.holeFile = new OStorageClusterHoleConfiguration(iConfig, OStorageVariableParser.DB_PATH_VARIABLE + "/" + iConfig.name, + iConfig.fileType, iConfig.fileMaxSize); - holeSegment = new OClusterLocalHole(this, iStorage, iConfig.holeFile); - } + holeSegment = new OClusterLocalHole(this, iStorage, iConfig.holeFile); + } - @Override - public void create(int iStartSize) throws IOException { - if (iStartSize == -1) - iStartSize = DEF_SIZE; + @Override + public void create(int iStartSize) throws IOException { + if (iStartSize == -1) + iStartSize = DEF_SIZE; - super.create(iStartSize); - holeSegment.create(); - } + super.create(iStartSize); + holeSegment.create(); - @Override - public void open() throws IOException { - try { - acquireExclusiveLock(); + files[0].writeHeaderLong(0, beginOffsetData); + files[0].writeHeaderLong(OConstants.SIZE_LONG, beginOffsetData); - super.open(); - holeSegment.open(); + } - } finally { + @Override + public void open() throws IOException { + try { + acquireExclusiveLock(); - releaseExclusiveLock(); - } - } + super.open(); + holeSegment.open(); - @Override - public void close() throws IOException { - super.close(); - holeSegment.close(); - } + beginOffsetData = files[0].readHeaderLong(0); + endOffsetData = files[0].readHeaderLong(OConstants.SIZE_LONG); - public void delete() throws IOException { - super.delete(); - holeSegment.delete(); - } + } finally { - /** - * Fill and return the PhysicalPosition object received as parameter with the physical position of logical record iPosition - * - * @throws IOException - */ - public OPhysicalPosition getPhysicalPosition(long iPosition, final OPhysicalPosition iPPosition) throws IOException { - iPosition = iPosition * RECORD_SIZE; + releaseExclusiveLock(); + } + } - try { - acquireSharedLock(); + @Override + public void close() throws IOException { + super.close(); + holeSegment.close(); + } - int[] pos = getRelativePosition(iPosition); + public void delete() throws IOException { + super.delete(); + holeSegment.delete(); + } - int p = pos[1]; + /** + * Fill and return the PhysicalPosition object received as parameter with the physical position of logical record iPosition + * + * @throws IOException + */ + public OPhysicalPosition getPhysicalPosition(long iPosition, final OPhysicalPosition iPPosition) throws IOException { + iPosition = iPosition * RECORD_SIZE; - iPPosition.dataSegment = files[pos[0]].readShort(p); - iPPosition.dataPosition = files[pos[0]].readLong(p += OConstants.SIZE_SHORT); - iPPosition.type = files[pos[0]].readByte(p += OConstants.SIZE_LONG); - iPPosition.version = files[pos[0]].readInt(p += OConstants.SIZE_BYTE); - return iPPosition; + try { + acquireSharedLock(); - } finally { - releaseSharedLock(); - } - } + int[] pos = getRelativePosition(iPosition); - /** - * Change the PhysicalPosition of the logical record iPosition. - * - * @throws IOException - */ - public void setPhysicalPosition(long iPosition, final int iDataId, final long iDataPosition, final byte iRecordType) - throws IOException { - iPosition = iPosition * RECORD_SIZE; - - try { - acquireExclusiveLock(); + int p = pos[1]; - int[] pos = getRelativePosition(iPosition); - - int p = pos[1]; - - files[pos[0]].writeShort(p, (short) iDataId); - files[pos[0]].writeLong(p += OConstants.SIZE_SHORT, iDataPosition); - files[pos[0]].writeByte(p += OConstants.SIZE_LONG, iRecordType); + iPPosition.dataSegment = files[pos[0]].readShort(p); + iPPosition.dataPosition = files[pos[0]].readLong(p += OConstants.SIZE_SHORT); + iPPosition.type = files[pos[0]].readByte(p += OConstants.SIZE_LONG); + iPPosition.version = files[pos[0]].readInt(p += OConstants.SIZE_BYTE); + return iPPosition; - } finally { - releaseExclusiveLock(); - } - } + } finally { + releaseSharedLock(); + } + } - public void updateVersion(long iPosition, final int iVersion) throws IOException { - iPosition = iPosition * RECORD_SIZE; + /** + * Change the PhysicalPosition of the logical record iPosition. + * + * @throws IOException + */ + public void setPhysicalPosition(long iPosition, final int iDataId, final long iDataPosition, final byte iRecordType) + throws IOException { + iPosition = iPosition * RECORD_SIZE; - try { - acquireExclusiveLock(); - - int[] pos = getRelativePosition(iPosition); - - files[pos[0]].writeInt(pos[1] + OConstants.SIZE_SHORT + OConstants.SIZE_LONG + OConstants.SIZE_BYTE, iVersion); - - } finally { - releaseExclusiveLock(); - } - } - - public void updateRecordType(long iPosition, final byte iRecordType) throws IOException { - iPosition = iPosition * RECORD_SIZE; - - try { - acquireExclusiveLock(); - - int[] pos = getRelativePosition(iPosition); - - files[pos[0]].writeByte(pos[1] + OConstants.SIZE_SHORT + OConstants.SIZE_LONG, iRecordType); - - } finally { - releaseExclusiveLock(); - } - } - - /** - * Remove the Logical position entry. Add to the hole segment and change the version to -1. - * - * @throws IOException - */ - public void removePhysicalPosition(long iPosition, final OPhysicalPosition iPPosition) throws IOException { - iPosition = iPosition * RECORD_SIZE; - - try { - acquireExclusiveLock(); - - int[] pos = getRelativePosition(iPosition); - OFile file = files[pos[0]]; - int p = pos[1]; - - // SAVE THE OLD DATA AND RETRIEVE THEM TO THE CALLER - iPPosition.dataSegment = file.readShort(p); - iPPosition.dataPosition = file.readLong(p += OConstants.SIZE_SHORT); - iPPosition.type = file.readByte(p += OConstants.SIZE_LONG); - iPPosition.version = file.readInt(p += OConstants.SIZE_BYTE); - - holeSegment.pushPosition(iPosition); - - file.writeInt(p, -1); - } finally { - releaseExclusiveLock(); - } - } + try { + acquireExclusiveLock(); - public boolean removeHole(long iPosition) throws IOException { - return holeSegment.removeEntryWithPosition(iPosition); - } - - /** - * Add a new entry. - * - * @throws IOException - */ - public long addPhysicalPosition(final int iDataSegmentId, final long iPosition, final byte iRecordType) throws IOException { - try { - acquireExclusiveLock(); - - long offset = holeSegment.popLastEntryPosition(); - - final int[] pos; - if (offset > -1) - // REUSE THE HOLE - pos = getRelativePosition(offset); - else { - // NO HOLES FOUND: ALLOCATE MORE SPACE - pos = allocateSpace(RECORD_SIZE); - offset = getAbsolutePosition(pos); - } + int[] pos = getRelativePosition(iPosition); - OFile file = files[pos[0]]; - int p = pos[1]; + int p = pos[1]; - file.writeShort(p, (short) iDataSegmentId); - file.writeLong(p += OConstants.SIZE_SHORT, iPosition); - file.writeByte(p += OConstants.SIZE_LONG, iRecordType); - file.writeInt(p += OConstants.SIZE_BYTE, 0); - - return offset / RECORD_SIZE; - - } finally { - releaseExclusiveLock(); - } - } + files[pos[0]].writeShort(p, (short) iDataId); + files[pos[0]].writeLong(p += OConstants.SIZE_SHORT, iDataPosition); + files[pos[0]].writeByte(p += OConstants.SIZE_LONG, iRecordType); - public long getLastEntryPosition() throws IOException { - try { - acquireSharedLock(); + } finally { + releaseExclusiveLock(); + } + } - return getFilledUpTo() / RECORD_SIZE - 1; - - } finally { - releaseSharedLock(); - } - } - - public long getEntries() { - try { - acquireSharedLock(); - - return getFilledUpTo() / RECORD_SIZE - holeSegment.getHoles(); - - } finally { - releaseSharedLock(); - } - } - - public int getId() { - return id; - } - - public OClusterPositionIterator absoluteIterator() throws IOException { - return new OClusterPositionIterator(this); - } - - @Override - public String toString() { - return name + " (id=" + id + ")"; - } - - public void lock() { - acquireSharedLock(); - } - - public void unlock() { - releaseSharedLock(); - } - - public String getType() { - return TYPE; - } + public void updateVersion(long iPosition, final int iVersion) throws IOException { + iPosition = iPosition * RECORD_SIZE; + + try { + acquireExclusiveLock(); + + int[] pos = getRelativePosition(iPosition); + + files[pos[0]].writeInt(pos[1] + OConstants.SIZE_SHORT + OConstants.SIZE_LONG + OConstants.SIZE_BYTE, iVersion); + + } finally { + releaseExclusiveLock(); + } + } + + public void updateRecordType(long iPosition, final byte iRecordType) throws IOException { + iPosition = iPosition * RECORD_SIZE; + + try { + acquireExclusiveLock(); + + int[] pos = getRelativePosition(iPosition); + + files[pos[0]].writeByte(pos[1] + OConstants.SIZE_SHORT + OConstants.SIZE_LONG, iRecordType); + + } finally { + releaseExclusiveLock(); + } + } + + /** + * Remove the Logical position entry. Add to the hole segment and change the version to -1. + * + * @throws IOException + */ + public void removePhysicalPosition(long iPosition, final OPhysicalPosition iPPosition) throws IOException { + final long position = iPosition * RECORD_SIZE; + try { + acquireExclusiveLock(); + + int[] pos = getRelativePosition(position); + OFile file = files[pos[0]]; + int p = pos[1]; + + // SAVE THE OLD DATA AND RETRIEVE THEM TO THE CALLER + iPPosition.dataSegment = file.readShort(p); + iPPosition.dataPosition = file.readLong(p += OConstants.SIZE_SHORT); + iPPosition.type = file.readByte(p += OConstants.SIZE_LONG); + iPPosition.version = file.readInt(p += OConstants.SIZE_BYTE); + + holeSegment.pushPosition(position); + + // SET VERSION = -1 + file.writeInt(p, -1); + + if (iPosition == beginOffsetData) { + if (getEntries() == 0) + beginOffsetData = -1; + else { + // DISCOVER THE BEGIN OF DATA + beginOffsetData++; + + int[] fetchPos; + for (long currentPos = position + RECORD_SIZE; currentPos < getFilledUpTo(); currentPos += RECORD_SIZE) { + fetchPos = getRelativePosition(currentPos); + + if (files[fetchPos[0]].readShort(fetchPos[1]) != -1) + // GOOD RECORD: SET IT AS BEGIN + break; + + beginOffsetData++; + } + } + + files[0].writeHeaderLong(0, beginOffsetData); + } + + if (iPosition == endOffsetData) { + if (getEntries() == 0) + endOffsetData = -1; + else { + // DISCOVER THE END OF DATA + endOffsetData--; + + int[] fetchPos; + for (long currentPos = position - RECORD_SIZE; currentPos >= beginOffsetData; currentPos -= RECORD_SIZE) { + + fetchPos = getRelativePosition(currentPos); + + if (files[fetchPos[0]].readShort(fetchPos[1]) != -1) + // GOOD RECORD: SET IT AS BEGIN + break; + endOffsetData--; + } + } + + files[0].writeHeaderLong(OConstants.SIZE_LONG, endOffsetData); + } + + } finally { + releaseExclusiveLock(); + } + } + + public boolean removeHole(long iPosition) throws IOException { + return holeSegment.removeEntryWithPosition(iPosition); + } + + /** + * Add a new entry. + * + * @throws IOException + */ + public long addPhysicalPosition(final int iDataSegmentId, final long iPosition, final byte iRecordType) throws IOException { + try { + acquireExclusiveLock(); + + long offset = holeSegment.popLastEntryPosition(); + + final int[] pos; + if (offset > -1) + // REUSE THE HOLE + pos = getRelativePosition(offset); + else { + // NO HOLES FOUND: ALLOCATE MORE SPACE + pos = allocateSpace(RECORD_SIZE); + offset = getAbsolutePosition(pos); + } + + OFile file = files[pos[0]]; + int p = pos[1]; + + file.writeShort(p, (short) iDataSegmentId); + file.writeLong(p += OConstants.SIZE_SHORT, iPosition); + file.writeByte(p += OConstants.SIZE_LONG, iRecordType); + file.writeInt(p += OConstants.SIZE_BYTE, 0); + + final long returnedPosition = offset / RECORD_SIZE; + + if (returnedPosition < beginOffsetData || beginOffsetData == -1) { + // UPDATE END OF DATA + beginOffsetData = returnedPosition; + files[0].writeHeaderLong(0, beginOffsetData); + } + + if (endOffsetData > -1 && returnedPosition > endOffsetData) { + // UPDATE END OF DATA + endOffsetData = returnedPosition; + files[0].writeHeaderLong(OConstants.SIZE_LONG, endOffsetData); + } + + return returnedPosition; + + } finally { + releaseExclusiveLock(); + } + } + + public long getFirstEntryPosition() throws IOException { + try { + acquireSharedLock(); + + return beginOffsetData; + + } finally { + releaseSharedLock(); + } + } + + /** + * Returns the endOffsetData value if it's not equals to the last one, otherwise the total entries. + */ + public long getLastEntryPosition() throws IOException { + try { + acquireSharedLock(); + + return endOffsetData > -1 ? endOffsetData : getFilledUpTo() / RECORD_SIZE - 1; + + } finally { + releaseSharedLock(); + } + } + + public long getEntries() { + try { + acquireSharedLock(); + + return getFilledUpTo() / RECORD_SIZE - holeSegment.getHoles(); + + } finally { + releaseSharedLock(); + } + } + + public int getId() { + return id; + } + + public OClusterPositionIterator absoluteIterator() throws IOException { + return new OClusterPositionIterator(this); + } + + @Override + public String toString() { + return name + " (id=" + id + ")"; + } + + public void lock() { + acquireSharedLock(); + } + + public void unlock() { + releaseSharedLock(); + } + + public String getType() { + return TYPE; + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocalHole.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocalHole.java index bd02ee333b2..5e56ddcd0de 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocalHole.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLocalHole.java @@ -21,7 +21,8 @@ import com.orientechnologies.orient.core.config.OStorageFileConfiguration; /** - * Handle the holes inside cluster segments. The synchronization is in charge to the OClusterLocal instance.<br/> + * Handle the holes inside cluster segments. The synchronization is in charge to + * the OClusterLocal instance.<br/> * <br/> * Record structure:<br/> * <br/> @@ -32,13 +33,14 @@ * = 8 bytes<br/> */ public class OClusterLocalHole extends OSingleFileSegment { - private static final int DEF_START_SIZE = 262144; - private static final int RECORD_SIZE = 8; + private static final int DEF_START_SIZE = 262144; + private static final int RECORD_SIZE = 8; - private OClusterLocal owner; + private OClusterLocal owner; - public OClusterLocalHole(final OClusterLocal iClusterLocal, final OStorageLocal iStorage, final OStorageFileConfiguration iConfig) - throws IOException { + public OClusterLocalHole(final OClusterLocal iClusterLocal, + final OStorageLocal iStorage, + final OStorageFileConfiguration iConfig) throws IOException { super(iStorage, iConfig); owner = iClusterLocal; } @@ -47,11 +49,17 @@ public OClusterLocalHole(final OClusterLocal iClusterLocal, final OStorageLocal * TODO Check values removing dirty entries (equals to -1) */ public void defrag() throws IOException { - OLogManager.instance().debug(this, "Starting to defragment the segment %s of size=%d and filled=%d", file, file.getFileSize(), - file.getFilledUpTo()); - - OLogManager.instance().debug(this, "Defragmentation ended for segment %s. Current size=%d and filled=%d", file, - file.getFileSize(), file.getFilledUpTo()); + OLogManager + .instance() + .debug(this, + "Starting to defragment the segment %s of size=%d and filled=%d", + file, file.getFileSize(), file.getFilledUpTo()); + + OLogManager + .instance() + .debug(this, + "Defragmentation ended for segment %s. Current size=%d and filled=%d", + file, file.getFileSize(), file.getFilledUpTo()); } public void create() throws IOException { @@ -70,8 +78,9 @@ public long pushPosition(final long iPosition) throws IOException { file.writeLong(position, iPosition); if (OLogManager.instance().isDebugEnabled()) - OLogManager.instance().debug(this, "Pushed new hole at #%d containing the position #%d:%d", position / RECORD_SIZE, - owner.getId(), iPosition); + OLogManager.instance().debug(this, + "Pushed new hole at #%d containing the position #%d:%d", + position / RECORD_SIZE, owner.getId(), iPosition); return position; } @@ -79,7 +88,8 @@ public long pushPosition(final long iPosition) throws IOException { /** * Return the recycled position if any. * - * @return the recycled position if found, otherwise -1 that usually means to request more space. + * @return the recycled position if found, otherwise -1 that usually means + * to request more space. * @throws IOException */ public long popLastEntryPosition() throws IOException { @@ -89,8 +99,11 @@ public long popLastEntryPosition() throws IOException { if (recycledPosition > -1) { if (OLogManager.instance().isDebugEnabled()) - OLogManager.instance().debug(this, "Recycling hole #%d containing the position #%d:%d", pos, owner.getId(), - recycledPosition); + OLogManager + .instance() + .debug(this, + "Recycling hole #%d containing the position #%d:%d", + pos, owner.getId(), recycledPosition); // SHRINK THE FILE file.removeTail((getHoles() - pos) * RECORD_SIZE); @@ -103,11 +116,12 @@ public long popLastEntryPosition() throws IOException { } /** - * Remove a hole. Called on transaction recover to invalidate a delete for a record. Try to shrink the file if the invalidated - * entry is not in the middle of valid entries. + * Remove a hole. Called on transaction recover to invalidate a delete for a + * record. Try to shrink the file if the invalidated entry is not in the + * middle of valid entries. * * @param iPosition - * Record position to find and invalidate + * Record position to find and invalidate * @return * @throws IOException */ @@ -119,8 +133,9 @@ public boolean removeEntryWithPosition(long iPosition) throws IOException { if (recycledPosition == iPosition) { if (OLogManager.instance().isDebugEnabled()) - OLogManager.instance().debug(this, "Removing hole #%d containing the position #%d:%d", pos, owner.getId(), - recycledPosition); + OLogManager.instance().debug(this, + "Removing hole #%d containing the position #%d:%d", + pos, owner.getId(), recycledPosition); file.writeLong(pos * RECORD_SIZE, -1); if (canShrink) diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLogical.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLogical.java index 2962939dc1e..d83295720ac 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLogical.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OClusterLogical.java @@ -194,6 +194,10 @@ public long getEntries() { return map.size() - 1; } + public long getFirstEntryPosition() { + return 0; + } + public long getLastEntryPosition() { return total.dataPosition; } diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java index dcc57c1bd4c..3db5f7a5c73 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/local/OStorageLocal.java @@ -59,1007 +59,1019 @@ import com.orientechnologies.orient.core.tx.OTransaction; public class OStorageLocal extends OStorageAbstract { - public static final String[] TYPES = { OClusterLocal.TYPE, OClusterLogical.TYPE }; + public static final String[] TYPES = { OClusterLocal.TYPE, OClusterLogical.TYPE }; + + // private final OLockManager<String, String> lockManager = new + // OLockManager<String, String>(); + protected final Map<String, OCluster> clusterMap = new LinkedHashMap<String, OCluster>(); + protected OCluster[] clusters = new OCluster[0]; + protected ODataLocal[] dataSegments = new ODataLocal[0]; + + private OStorageLocalTxExecuter txManager; + private String storagePath; + private OStorageVariableParser variableParser; + private int defaultClusterId = -1; + + public OStorageLocal(final String iName, final String iFilePath, final String iMode) throws IOException { + super(iName, iFilePath, iMode); + + storagePath = OSystemVariableResolver.resolveSystemVariables(OFileUtils.getPath(new File(url).getParent())); + + configuration = new OStorageConfiguration(this); + variableParser = new OStorageVariableParser(storagePath); + txManager = new OStorageLocalTxExecuter(this, configuration.txSegment); + } + + public synchronized void open(final int iRequesterId, final String iUserName, final String iUserPassword) { + final long timer = OProfiler.getInstance().startChrono(); + + addUser(); + cache.addUser(); + + final boolean locked = acquireExclusiveLock(); + + try { + if (open) + // ALREADY OPENED: THIS IS THE CASE WHEN A STORAGE INSTANCE IS + // REUSED + return; - // private final OLockManager<String, String> lockManager = new OLockManager<String, String>(); - protected final Map<String, OCluster> clusterMap = new LinkedHashMap<String, OCluster>(); - protected OCluster[] clusters = new OCluster[0]; - protected ODataLocal[] dataSegments = new ODataLocal[0]; - - private OStorageLocalTxExecuter txManager; - private String storagePath; - private OStorageVariableParser variableParser; - private int defaultClusterId = -1; - - public OStorageLocal(final String iName, final String iFilePath, final String iMode) throws IOException { - super(iName, iFilePath, iMode); + if (!exists()) + throw new OStorageException("Can't open the storage " + name + " because it not exists"); - storagePath = OSystemVariableResolver.resolveSystemVariables(OFileUtils.getPath(new File(url).getParent())); - - configuration = new OStorageConfiguration(this); - variableParser = new OStorageVariableParser(storagePath); - txManager = new OStorageLocalTxExecuter(this, configuration.txSegment); - } + open = true; - public synchronized void open(final int iRequesterId, final String iUserName, final String iUserPassword) { - final long timer = OProfiler.getInstance().startChrono(); + // OPEN BASIC SEGMENTS + int pos; + pos = registerDataSegment(new OStorageDataConfiguration(configuration, OStorage.DATA_DEFAULT_NAME)); + dataSegments[pos].open(); - addUser(); - cache.addUser(); + pos = createClusterFromConfig(new OStoragePhysicalClusterConfiguration(configuration, OStorage.CLUSTER_INTERNAL_NAME, + clusters.length)); + clusters[pos].open(); - final boolean locked = acquireExclusiveLock(); + pos = createClusterFromConfig(new OStoragePhysicalClusterConfiguration(configuration, OStorage.CLUSTER_INDEX_NAME, + clusters.length)); + clusters[pos].open(); - try { - if (open) - // ALREADY OPENED: THIS IS THE CASE WHEN A STORAGE INSTANCE IS REUSED - return; + defaultClusterId = createClusterFromConfig(new OStoragePhysicalClusterConfiguration(configuration, + OStorage.CLUSTER_DEFAULT_NAME, clusters.length)); + clusters[defaultClusterId].open(); - if (!exists()) - throw new OStorageException("Can't open the storage " + name + " because it not exists"); + configuration.load(); - open = true; + if (configuration.isEmpty()) + throw new OStorageException("Can't open storage because it not exists. Storage path: " + url); - // OPEN BASIC SEGMENTS - int pos; - pos = registerDataSegment(new OStorageDataConfiguration(configuration, OStorage.DATA_DEFAULT_NAME)); - dataSegments[pos].open(); + // REGISTER DATA SEGMENT + OStorageDataConfiguration dataConfig; + for (int i = 0; i < configuration.dataSegments.size(); ++i) { + dataConfig = configuration.dataSegments.get(i); - pos = createClusterFromConfig(new OStoragePhysicalClusterConfiguration(configuration, OStorage.CLUSTER_INTERNAL_NAME, - clusters.length)); - clusters[pos].open(); + pos = registerDataSegment(dataConfig); + if (pos == -1) { + // CLOSE AND REOPEN TO BE SURE ALL THE FILE SEGMENTS ARE + // OPENED + dataSegments[i].close(); + dataSegments[i] = new ODataLocal(this, dataConfig, pos); + dataSegments[i].open(); + } else + dataSegments[pos].open(); + } - pos = createClusterFromConfig(new OStoragePhysicalClusterConfiguration(configuration, OStorage.CLUSTER_INDEX_NAME, - clusters.length)); - clusters[pos].open(); + // REGISTER CLUSTER + OStorageClusterConfiguration clusterConfig; + for (int i = 0; i < configuration.clusters.size(); ++i) { + clusterConfig = configuration.clusters.get(i); - defaultClusterId = createClusterFromConfig(new OStoragePhysicalClusterConfiguration(configuration, - OStorage.CLUSTER_DEFAULT_NAME, clusters.length)); - clusters[defaultClusterId].open(); + pos = createClusterFromConfig(clusterConfig); - configuration.load(); + if (pos == -1) { + // CLOSE AND REOPEN TO BE SURE ALL THE FILE SEGMENTS ARE + // OPENED + clusters[i].close(); + clusters[i] = new OClusterLocal(this, (OStoragePhysicalClusterConfiguration) clusterConfig); + clusters[i].open(); + } else { + if (clusterConfig.getName().equals(OStorage.CLUSTER_DEFAULT_NAME)) + defaultClusterId = pos; - if (configuration.isEmpty()) - throw new OStorageException("Can't open storage because it not exists. Storage path: " + url); + clusters[pos].open(); + } + } - // REGISTER DATA SEGMENT - OStorageDataConfiguration dataConfig; - for (int i = 0; i < configuration.dataSegments.size(); ++i) { - dataConfig = configuration.dataSegments.get(i); + txManager.open(); - pos = registerDataSegment(dataConfig); - if (pos == -1) { - // CLOSE AND REOPEN TO BE SURE ALL THE FILE SEGMENTS ARE OPENED - dataSegments[i].close(); - dataSegments[i] = new ODataLocal(this, dataConfig, pos); - dataSegments[i].open(); - } else - dataSegments[pos].open(); - } + } catch (IOException e) { + open = false; + dataSegments = new ODataLocal[0]; + clusters = new OCluster[0]; + clusterMap.clear(); + throw new OStorageException("Can't open local storage: " + url + ", with mode=" + mode, e); + } finally { + releaseExclusiveLock(locked); - // REGISTER CLUSTER - OStorageClusterConfiguration clusterConfig; - for (int i = 0; i < configuration.clusters.size(); ++i) { - clusterConfig = configuration.clusters.get(i); + OProfiler.getInstance().stopChrono("OStorageLocal.open", timer); + } + } - pos = createClusterFromConfig(clusterConfig); + public void create() { + final long timer = OProfiler.getInstance().startChrono(); - if (pos == -1) { - // CLOSE AND REOPEN TO BE SURE ALL THE FILE SEGMENTS ARE OPENED - clusters[i].close(); - clusters[i] = new OClusterLocal(this, (OStoragePhysicalClusterConfiguration) clusterConfig); - clusters[i].open(); - } else { - if (clusterConfig.getName().equals(OStorage.CLUSTER_DEFAULT_NAME)) - defaultClusterId = pos; + addUser(); + cache.addUser(); - clusters[pos].open(); - } - } + final boolean locked = acquireExclusiveLock(); - txManager.open(); + try { + File storageFolder = new File(storagePath); + if (!storageFolder.exists()) + storageFolder.mkdir(); - } catch (IOException e) { - open = false; - dataSegments = new ODataLocal[0]; - clusters = new OCluster[0]; - clusterMap.clear(); - throw new OStorageException("Can't open local storage: " + url + ", with mode=" + mode, e); - } finally { - releaseExclusiveLock(locked); + if (exists()) + throw new OStorageException("Can't create new storage " + name + " because it already exists"); - OProfiler.getInstance().stopChrono("OStorageLocal.open", timer); - } - } + open = true; - public void create() { - final long timer = OProfiler.getInstance().startChrono(); + addDataSegment(OStorage.DATA_DEFAULT_NAME); - addUser(); - cache.addUser(); + // ADD THE METADATA CLUSTER TO STORE INTERNAL STUFF + addCluster(OStorage.CLUSTER_INTERNAL_NAME, OClusterLocal.TYPE); - final boolean locked = acquireExclusiveLock(); + // ADD THE INDEX CLUSTER TO STORE, BY DEFAULT, ALL THE RECORDS OF + // INDEXING + addCluster(OStorage.CLUSTER_INDEX_NAME, OClusterLocal.TYPE); - try { - File storageFolder = new File(storagePath); - if (!storageFolder.exists()) - storageFolder.mkdir(); + // ADD THE DEFAULT CLUSTER + defaultClusterId = addCluster(OStorage.CLUSTER_DEFAULT_NAME, OClusterLocal.TYPE); - if (exists()) - throw new OStorageException("Can't create new storage " + name + " because it already exists"); + configuration.create(); - open = true; + txManager.create(); + } catch (OStorageException e) { + close(); + throw e; + } catch (IOException e) { + close(); + throw new OStorageException("Error on creation of storage: " + name, e); - addDataSegment(OStorage.DATA_DEFAULT_NAME); + } finally { + releaseExclusiveLock(locked); - // ADD THE METADATA CLUSTER TO STORE INTERNAL STUFF - addCluster(OStorage.CLUSTER_INTERNAL_NAME, OClusterLocal.TYPE); + OProfiler.getInstance().stopChrono("OStorageLocal.create", timer); + } + } - // ADD THE INDEX CLUSTER TO STORE, BY DEFAULT, ALL THE RECORDS OF INDEXING - addCluster(OStorage.CLUSTER_INDEX_NAME, OClusterLocal.TYPE); + public boolean exists() { + return new File(storagePath + "/" + OStorage.DATA_DEFAULT_NAME + ".0" + ODataLocal.DEF_EXTENSION).exists(); + } - // ADD THE DEFAULT CLUSTER - defaultClusterId = addCluster(OStorage.CLUSTER_DEFAULT_NAME, OClusterLocal.TYPE); + public void close() { + final long timer = OProfiler.getInstance().startChrono(); - configuration.create(); + final boolean locked = acquireExclusiveLock(); - txManager.create(); - } catch (OStorageException e) { - close(); - throw e; - } catch (IOException e) { - close(); - throw new OStorageException("Error on creation of storage: " + name, e); + if (!open) + return; - } finally { - releaseExclusiveLock(locked); + try { + for (OCluster cluster : clusters) + if (cluster != null) + cluster.close(); + clusters = new OCluster[0]; + clusterMap.clear(); - OProfiler.getInstance().stopChrono("OStorageLocal.create", timer); - } - } + for (ODataLocal data : dataSegments) + data.close(); + dataSegments = new ODataLocal[0]; - public boolean exists() { - return new File(storagePath + "/" + OStorage.DATA_DEFAULT_NAME + ".0" + ODataLocal.DEF_EXTENSION).exists(); - } + txManager.close(); - public void close() { - final long timer = OProfiler.getInstance().startChrono(); + cache.removeUser(); + cache.clear(); + configuration = new OStorageConfiguration(this); - final boolean locked = acquireExclusiveLock(); + open = false; + } catch (IOException e) { + OLogManager.instance().error(this, "Error on closing of the storage '" + name, e, OStorageException.class); - if (!open) - return; + } finally { + releaseExclusiveLock(locked); - try { - for (OCluster cluster : clusters) - if (cluster != null) - cluster.close(); - clusters = new OCluster[0]; - clusterMap.clear(); + OProfiler.getInstance().stopChrono("OStorageLocal.close", timer); + } + } - for (ODataLocal data : dataSegments) - data.close(); - dataSegments = new ODataLocal[0]; + public ODataLocal getDataSegment(final int iDataSegmentId) { + checkOpeness(); + if (iDataSegmentId >= dataSegments.length) + throw new IllegalArgumentException("Data segment #" + iDataSegmentId + " doesn't exist in current storage"); - txManager.close(); + final boolean locked = acquireSharedLock(); - cache.removeUser(); - cache.clear(); - configuration = new OStorageConfiguration(this); + try { + return dataSegments[iDataSegmentId]; - open = false; - } catch (IOException e) { - OLogManager.instance().error(this, "Error on closing of the storage '" + name, e, OStorageException.class); + } finally { + releaseSharedLock(locked); + } + } - } finally { - releaseExclusiveLock(locked); + /** + * Add a new data segment in the default segment directory and with filename equals to the cluster name. + */ + public int addDataSegment(final String iDataSegmentName) { + String segmentFileName = storagePath + "/" + iDataSegmentName; + return addDataSegment(iDataSegmentName, segmentFileName); + } - OProfiler.getInstance().stopChrono("OStorageLocal.close", timer); - } - } + public int addDataSegment(String iSegmentName, final String iSegmentFileName) { + checkOpeness(); - public ODataLocal getDataSegment(final int iDataSegmentId) { - checkOpeness(); - if (iDataSegmentId >= dataSegments.length) - throw new IllegalArgumentException("Data segment #" + iDataSegmentId + " doesn't exist in current storage"); + iSegmentName = iSegmentName.toLowerCase(); - final boolean locked = acquireSharedLock(); + final boolean locked = acquireExclusiveLock(); - try { - return dataSegments[iDataSegmentId]; + try { + OStorageDataConfiguration conf = new OStorageDataConfiguration(configuration, iSegmentName); + configuration.dataSegments.add(conf); - } finally { - releaseSharedLock(locked); - } - } + final int pos = registerDataSegment(conf); - /** - * Add a new data segment in the default segment directory and with filename equals to the cluster name. - */ - public int addDataSegment(final String iDataSegmentName) { - String segmentFileName = storagePath + "/" + iDataSegmentName; - return addDataSegment(iDataSegmentName, segmentFileName); - } + if (pos == -1) + throw new OConfigurationException("Can't add segment " + conf.name + " because it's already part of current storage"); - public int addDataSegment(String iSegmentName, final String iSegmentFileName) { - checkOpeness(); + dataSegments[pos].create(-1); + configuration.update(); - iSegmentName = iSegmentName.toLowerCase(); + return pos; + } catch (Throwable e) { + OLogManager.instance().error(this, "Error on creation of new data segment '" + iSegmentName + "' in: " + iSegmentFileName, e, + OStorageException.class); + return -1; - final boolean locked = acquireExclusiveLock(); + } finally { + releaseExclusiveLock(locked); + } + } - try { - OStorageDataConfiguration conf = new OStorageDataConfiguration(configuration, iSegmentName); - configuration.dataSegments.add(conf); + /** + * Add a new cluster into the storage. Type can be: "physical" or "logical". + */ + public int addCluster(String iClusterName, final String iClusterType, final Object... iParameters) { + checkOpeness(); - final int pos = registerDataSegment(conf); + final boolean locked = acquireExclusiveLock(); - if (pos == -1) - throw new OConfigurationException("Can't add segment " + conf.name + " because it's already part of current storage"); + try { + iClusterName = iClusterName.toLowerCase(); - dataSegments[pos].create(-1); - configuration.update(); + if (OClusterLocal.TYPE.equalsIgnoreCase(iClusterType)) { + // GET PARAMETERS + final String clusterFileName = (String) (iParameters.length < 1 ? storagePath + "/" + iClusterName : iParameters[0]); + final int startSize = (iParameters.length < 2 ? -1 : (Integer) iParameters[1]); - return pos; - } catch (Throwable e) { - OLogManager.instance().error(this, "Error on creation of new data segment '" + iSegmentName + "' in: " + iSegmentFileName, e, - OStorageException.class); - return -1; + return addPhysicalCluster(iClusterName, clusterFileName, startSize); + } else if (OClusterLogical.TYPE.equalsIgnoreCase(iClusterType)) { + // GET PARAMETERS + final int physicalClusterId = (iParameters.length < 1 ? getClusterIdByName(OStorage.CLUSTER_INTERNAL_NAME) + : (Integer) iParameters[0]); - } finally { - releaseExclusiveLock(locked); - } - } + return addLogicalCluster(iClusterName, physicalClusterId); + } else + OLogManager.instance().exception( + "Cluster type '" + iClusterType + "' is not supported. Supported types are: " + Arrays.toString(TYPES), null, + OStorageException.class); - /** - * Add a new cluster into the storage. Type can be: "physical" or "logical". - */ - public int addCluster(String iClusterName, final String iClusterType, final Object... iParameters) { - checkOpeness(); + } catch (Exception e) { + OLogManager.instance().exception("Error in creation of new cluster '" + iClusterName + "' of type: " + iClusterType, e, + OStorageException.class); - final boolean locked = acquireExclusiveLock(); + } finally { - try { - iClusterName = iClusterName.toLowerCase(); + releaseExclusiveLock(locked); + } + return -1; + } - if (OClusterLocal.TYPE.equalsIgnoreCase(iClusterType)) { - // GET PARAMETERS - final String clusterFileName = (String) (iParameters.length < 1 ? storagePath + "/" + iClusterName : iParameters[0]); - final int startSize = (iParameters.length < 2 ? -1 : (Integer) iParameters[1]); + public boolean removeCluster(final int iClusterId) { + final boolean locked = acquireExclusiveLock(); - return addPhysicalCluster(iClusterName, clusterFileName, startSize); - } else if (OClusterLogical.TYPE.equalsIgnoreCase(iClusterType)) { - // GET PARAMETERS - final int physicalClusterId = (iParameters.length < 1 ? getClusterIdByName(OStorage.CLUSTER_INTERNAL_NAME) - : (Integer) iParameters[0]); + try { + if (iClusterId < 0 || iClusterId >= clusters.length) + throw new IllegalArgumentException("Cluster id '" + iClusterId + "' is out of range of configured clusters (0-" + + (clusters.length - 1) + ")"); - return addLogicalCluster(iClusterName, physicalClusterId); - } else - OLogManager.instance().exception( - "Cluster type '" + iClusterType + "' is not supported. Supported types are: " + Arrays.toString(TYPES), null, - OStorageException.class); + final OCluster cluster = clusters[iClusterId]; + if (cluster == null) + return false; - } catch (Exception e) { - OLogManager.instance().exception("Error in creation of new cluster '" + iClusterName + "' of type: " + iClusterType, e, - OStorageException.class); + cluster.delete(); - } finally { + clusterMap.remove(cluster.getName()); + clusters[iClusterId] = null; - releaseExclusiveLock(locked); - } - return -1; - } + // UPDATE CONFIGURATION + configuration.clusters.set(iClusterId, null); + configuration.update(); - public boolean removeCluster(final int iClusterId) { - final boolean locked = acquireExclusiveLock(); + return true; + } catch (Exception e) { + OLogManager.instance().exception("Error while removing cluster '" + iClusterId + "'", e, OStorageException.class); - try { - if (iClusterId < 0 || iClusterId >= clusters.length) - throw new IllegalArgumentException("Cluster id '" + iClusterId + "' is out of range of configured clusters (0-" - + (clusters.length - 1) + ")"); + } finally { + releaseExclusiveLock(locked); + } - final OCluster cluster = clusters[iClusterId]; - if (cluster == null) - return false; + return false; + } - cluster.delete(); + public long count(final int[] iClusterIds) { + checkOpeness(); - clusterMap.remove(cluster.getName()); - clusters[iClusterId] = null; + final long timer = OProfiler.getInstance().startChrono(); - // UPDATE CONFIGURATION - configuration.clusters.set(iClusterId, null); - configuration.update(); + final boolean locked = acquireSharedLock(); - return true; - } catch (Exception e) { - OLogManager.instance().exception("Error while removing cluster '" + iClusterId + "'", e, OStorageException.class); + try { + long tot = 0; - } finally { - releaseExclusiveLock(locked); - } + OCluster c; + for (int i = 0; i < iClusterIds.length; ++i) { + if (iClusterIds[i] >= clusters.length) + throw new OConfigurationException("Cluster id " + iClusterIds[i] + "was not found"); - return false; - } + c = clusters[iClusterIds[i]]; + if (c != null) + tot += c.getEntries(); + } - public long count(final int[] iClusterIds) { - checkOpeness(); + return tot; - final long timer = OProfiler.getInstance().startChrono(); + } catch (IOException e) { - final boolean locked = acquireSharedLock(); + OLogManager.instance().error(this, "Error on getting element counts", e); + return -1; - try { - long tot = 0; + } finally { + releaseSharedLock(locked); - OCluster c; - for (int i = 0; i < iClusterIds.length; ++i) { - if (iClusterIds[i] >= clusters.length) - throw new OConfigurationException("Cluster id " + iClusterIds[i] + "was not found"); + OProfiler.getInstance().stopChrono("OStorageLocal.getClusterElementCounts", timer); + } + } - c = clusters[iClusterIds[i]]; - if (c != null) - tot += c.getEntries(); - } + public long[] getClusterDataRange(final int iClusterId) { + if (iClusterId == -1) + throw new OStorageException("Cluster Id is invalid: " + iClusterId); - return tot; + checkOpeness(); - } catch (IOException e) { + final long timer = OProfiler.getInstance().startChrono(); - OLogManager.instance().error(this, "Error on getting element counts", e); - return -1; + final boolean locked = acquireSharedLock(); - } finally { - releaseSharedLock(locked); + try { + return new long[] { clusters[iClusterId].getFirstEntryPosition(), clusters[iClusterId].getLastEntryPosition() }; - OProfiler.getInstance().stopChrono("OStorageLocal.getClusterElementCounts", timer); - } - } + } catch (IOException e) { - public long getClusterLastEntryPosition(final int iClusterId) { - if (iClusterId == -1) - throw new OStorageException("Cluster Id is invalid: " + iClusterId); + OLogManager.instance().error(this, "Error on getting last entry position", e); + return null; - checkOpeness(); + } finally { + releaseSharedLock(locked); - final long timer = OProfiler.getInstance().startChrono(); + OProfiler.getInstance().stopChrono("OStorageLocal.getClusterLastEntryPosition", timer); + } + } - final boolean locked = acquireSharedLock(); + public long count(final int iClusterId) { + if (iClusterId == -1) + throw new OStorageException("Cluster Id is invalid: " + iClusterId); - try { - return clusters[iClusterId].getLastEntryPosition(); + // COUNT PHYSICAL CLUSTER IF ANY + checkOpeness(); - } catch (IOException e) { + final long timer = OProfiler.getInstance().startChrono(); - OLogManager.instance().error(this, "Error on getting last entry position", e); - return -1; + final boolean locked = acquireSharedLock(); - } finally { - releaseSharedLock(locked); + try { + return clusters[iClusterId].getEntries(); - OProfiler.getInstance().stopChrono("OStorageLocal.getClusterLastEntryPosition", timer); - } - } + } catch (IOException e) { - public long count(final int iClusterId) { - if (iClusterId == -1) - throw new OStorageException("Cluster Id is invalid: " + iClusterId); + OLogManager.instance().error(this, "Error on getting element counts", e); + return -1; - // COUNT PHYSICAL CLUSTER IF ANY - checkOpeness(); + } finally { + releaseSharedLock(locked); - final long timer = OProfiler.getInstance().startChrono(); + OProfiler.getInstance().stopChrono("OStorageLocal.getClusterElementCounts", timer); + } + } - final boolean locked = acquireSharedLock(); + public long createRecord(final int iClusterId, final byte[] iContent, final byte iRecordType) { + checkOpeness(); + return createRecord(getClusterById(iClusterId), iContent, iRecordType); + } - try { - return clusters[iClusterId].getEntries(); + public ORawBuffer readRecord(final ODatabaseRecord<?> iDatabase, final int iRequesterId, final int iClusterId, + final long iPosition, final String iFetchPlan) { + checkOpeness(); + return readRecord(iRequesterId, getClusterById(iClusterId), iPosition, true); + } - } catch (IOException e) { + public int updateRecord(final int iRequesterId, final int iClusterId, final long iPosition, final byte[] iContent, + final int iVersion, final byte iRecordType) { + checkOpeness(); + return updateRecord(iRequesterId, getClusterById(iClusterId), iPosition, iContent, iVersion, iRecordType); + } - OLogManager.instance().error(this, "Error on getting element counts", e); - return -1; + public boolean deleteRecord(final int iRequesterId, final int iClusterId, final long iPosition, final int iVersion) { + checkOpeness(); + return deleteRecord(iRequesterId, getClusterById(iClusterId), iPosition, iVersion); + } - } finally { - releaseSharedLock(locked); + /** + * Browse N clusters. The entire operation use a shared lock on the storage and lock the cluster from the external avoiding atomic + * lock at every record read. + * + * @param iRequesterId + * The requester of the operation. Needed to know who locks + * @param iClusterId + * Array of cluster ids + * @param iListener + * The listener to call for each record found + * @param ioRecord + */ + public void browse(final int iRequesterId, final int[] iClusterId, final ORecordBrowsingListener iListener, + ORecordInternal<?> ioRecord, final boolean iLockEntireCluster) { + checkOpeness(); - OProfiler.getInstance().stopChrono("OStorageLocal.getClusterElementCounts", timer); - } - } + final long timer = OProfiler.getInstance().startChrono(); - public long createRecord(final int iClusterId, final byte[] iContent, final byte iRecordType) { - checkOpeness(); - return createRecord(getClusterById(iClusterId), iContent, iRecordType); - } + final boolean locked = acquireSharedLock(); - public ORawBuffer readRecord(final ODatabaseRecord<?> iDatabase, final int iRequesterId, final int iClusterId, - final long iPosition, final String iFetchPlan) { - checkOpeness(); - return readRecord(iRequesterId, getClusterById(iClusterId), iPosition, true); - } + try { + OCluster cluster; - public int updateRecord(final int iRequesterId, final int iClusterId, final long iPosition, final byte[] iContent, - final int iVersion, final byte iRecordType) { - checkOpeness(); - return updateRecord(iRequesterId, getClusterById(iClusterId), iPosition, iContent, iVersion, iRecordType); - } + for (int clusterId : iClusterId) { + cluster = getClusterById(clusterId); - public boolean deleteRecord(final int iRequesterId, final int iClusterId, final long iPosition, final int iVersion) { - checkOpeness(); - return deleteRecord(iRequesterId, getClusterById(iClusterId), iPosition, iVersion); - } + ioRecord = browseCluster(iRequesterId, iListener, ioRecord, cluster, iLockEntireCluster); + } + } catch (IOException e) { - /** - * Browse N clusters. The entire operation use a shared lock on the storage and lock the cluster from the external avoiding atomic - * lock at every record read. - * - * @param iRequesterId - * The requester of the operation. Needed to know who locks - * @param iClusterId - * Array of cluster ids - * @param iListener - * The listener to call for each record found - * @param ioRecord - */ - public void browse(final int iRequesterId, final int[] iClusterId, final ORecordBrowsingListener iListener, - ORecordInternal<?> ioRecord, final boolean iLockEntireCluster) { - checkOpeness(); + OLogManager.instance().error(this, "Error on browsing elements of cluster: " + iClusterId, e); - final long timer = OProfiler.getInstance().startChrono(); + } finally { + releaseSharedLock(locked); - final boolean locked = acquireSharedLock(); + OProfiler.getInstance().stopChrono("OStorageLocal.foreach", timer); + } + } - try { - OCluster cluster; + private ORecordInternal<?> browseCluster(final int iRequesterId, final ORecordBrowsingListener iListener, + ORecordInternal<?> ioRecord, OCluster cluster, final boolean iLockEntireCluster) throws IOException { + ORawBuffer recordBuffer; + long positionInPhyCluster; - for (int clusterId : iClusterId) { - cluster = getClusterById(clusterId); + try { + if (iLockEntireCluster) + // LOCK THE ENTIRE CLUSTER AVOIDING TO LOCK EVERY SINGLE RECORD + cluster.lock(); - ioRecord = browseCluster(iRequesterId, iListener, ioRecord, cluster, iLockEntireCluster); - } - } catch (IOException e) { + OClusterPositionIterator iterator = cluster.absoluteIterator(); - OLogManager.instance().error(this, "Error on browsing elements of cluster: " + iClusterId, e); + // BROWSE ALL THE RECORDS + while (iterator.hasNext()) { + positionInPhyCluster = iterator.next(); - } finally { - releaseSharedLock(locked); + // READ THE RAW RECORD. IF iLockEntireCluster THEN THE READ WILL + // BE NOT-LOCKING, OTHERWISE YES + recordBuffer = readRecord(iRequesterId, cluster, positionInPhyCluster, !iLockEntireCluster); + if (recordBuffer == null) + continue; - OProfiler.getInstance().stopChrono("OStorageLocal.foreach", timer); - } - } + if (recordBuffer.recordType != ODocument.RECORD_TYPE && recordBuffer.recordType != ORecordColumn.RECORD_TYPE) + // WRONG RECORD TYPE: JUMP IT + continue; - private ORecordInternal<?> browseCluster(final int iRequesterId, final ORecordBrowsingListener iListener, - ORecordInternal<?> ioRecord, OCluster cluster, final boolean iLockEntireCluster) throws IOException { - ORawBuffer recordBuffer; - long positionInPhyCluster; + if (ioRecord == null) + // RECORD NULL OR DIFFERENT IN TYPE: CREATE A NEW ONE + ioRecord = ORecordFactory.newInstance(recordBuffer.recordType); + else if (ioRecord.getRecordType() != recordBuffer.recordType) { + // RECORD NULL OR DIFFERENT IN TYPE: CREATE A NEW ONE + final ORecordInternal<?> newRecord = ORecordFactory.newInstance(recordBuffer.recordType); + newRecord.setDatabase(ioRecord.getDatabase()); + ioRecord = newRecord; + } else + // RESET CURRENT RECORD + ioRecord.reset(); - try { - if (iLockEntireCluster) - // LOCK THE ENTIRE CLUSTER AVOIDING TO LOCK EVERY SINGLE RECORD - cluster.lock(); + ioRecord.setVersion(recordBuffer.version); + ioRecord.setIdentity(cluster.getId(), positionInPhyCluster); + ioRecord.fromStream(recordBuffer.buffer); + if (!iListener.foreach(ioRecord)) + // LISTENER HAS INTERRUPTED THE EXECUTION + break; + } + } finally { - OClusterPositionIterator iterator = cluster.absoluteIterator(); + if (iLockEntireCluster) + // UNLOCK THE ENTIRE CLUSTER + cluster.unlock(); + } - // BROWSE ALL THE RECORDS - while (iterator.hasNext()) { - positionInPhyCluster = iterator.next(); + return ioRecord; + } - // READ THE RAW RECORD. IF iLockEntireCluster THEN THE READ WILL BE NOT-LOCKING, OTHERWISE YES - recordBuffer = readRecord(iRequesterId, cluster, positionInPhyCluster, !iLockEntireCluster); - if (recordBuffer == null) - continue; + public Set<String> getClusterNames() { + checkOpeness(); - if (recordBuffer.recordType != ODocument.RECORD_TYPE && recordBuffer.recordType != ORecordColumn.RECORD_TYPE) - // WRONG RECORD TYPE: JUMP IT - continue; + final boolean locked = acquireSharedLock(); - if (ioRecord == null) - // RECORD NULL OR DIFFERENT IN TYPE: CREATE A NEW ONE - ioRecord = ORecordFactory.newInstance(recordBuffer.recordType); - else if (ioRecord.getRecordType() != recordBuffer.recordType) { - // RECORD NULL OR DIFFERENT IN TYPE: CREATE A NEW ONE - final ORecordInternal<?> newRecord = ORecordFactory.newInstance(recordBuffer.recordType); - newRecord.setDatabase(ioRecord.getDatabase()); - ioRecord = newRecord; - } else - // RESET CURRENT RECORD - ioRecord.reset(); + try { - ioRecord.setVersion(recordBuffer.version); - ioRecord.setIdentity(cluster.getId(), positionInPhyCluster); - ioRecord.fromStream(recordBuffer.buffer); - if (!iListener.foreach(ioRecord)) - // LISTENER HAS INTERRUPTED THE EXECUTION - break; - } - } finally { + return clusterMap.keySet(); - if (iLockEntireCluster) - // UNLOCK THE ENTIRE CLUSTER - cluster.unlock(); - } + } finally { + releaseSharedLock(locked); + } + } - return ioRecord; - } + public int getClusterIdByName(final String iClusterName) { + checkOpeness(); - public Set<String> getClusterNames() { - checkOpeness(); + if (iClusterName == null) + throw new IllegalArgumentException("Cluster name is null"); - final boolean locked = acquireSharedLock(); + if (Character.isDigit(iClusterName.charAt(0))) + return Integer.parseInt(iClusterName); - try { + // SEARCH IT BETWEEN PHYSICAL CLUSTERS + OCluster segment; - return clusterMap.keySet(); + final boolean locked = acquireSharedLock(); - } finally { - releaseSharedLock(locked); - } - } + try { + segment = clusterMap.get(iClusterName.toLowerCase()); - public int getClusterIdByName(final String iClusterName) { - checkOpeness(); + } finally { + releaseSharedLock(locked); + } - if (iClusterName == null) - throw new IllegalArgumentException("Cluster name is null"); + if (segment != null) + return segment.getId(); - if (Character.isDigit(iClusterName.charAt(0))) - return Integer.parseInt(iClusterName); + return -1; + } - // SEARCH IT BETWEEN PHYSICAL CLUSTERS - OCluster segment; + public String getClusterTypeByName(final String iClusterName) { + checkOpeness(); - final boolean locked = acquireSharedLock(); + if (iClusterName == null) + throw new IllegalArgumentException("Cluster name is null"); - try { - segment = clusterMap.get(iClusterName.toLowerCase()); + // SEARCH IT BETWEEN PHYSICAL CLUSTERS + OCluster segment; - } finally { - releaseSharedLock(locked); - } + final boolean locked = acquireSharedLock(); - if (segment != null) - return segment.getId(); + try { + segment = clusterMap.get(iClusterName.toLowerCase()); - return -1; - } + } finally { + releaseSharedLock(locked); + } - public String getClusterTypeByName(final String iClusterName) { - checkOpeness(); + if (segment != null) + return segment.getType(); - if (iClusterName == null) - throw new IllegalArgumentException("Cluster name is null"); + return null; + } - // SEARCH IT BETWEEN PHYSICAL CLUSTERS - OCluster segment; + public void commit(final int iRequesterId, final OTransaction<?> iTx) { + final boolean locked = acquireSharedLock(); - final boolean locked = acquireSharedLock(); + try { + txManager.commitAllPendingRecords(iRequesterId, iTx); - try { - segment = clusterMap.get(iClusterName.toLowerCase()); + } catch (IOException e) { + rollback(iRequesterId, iTx); - } finally { - releaseSharedLock(locked); - } + } finally { + releaseSharedLock(locked); + } - if (segment != null) - return segment.getType(); + } - return null; - } + public void rollback(final int iRequesterId, final OTransaction<?> iTx) { + } - public void commit(final int iRequesterId, final OTransaction<?> iTx) { - final boolean locked = acquireSharedLock(); + public void synch() { + checkOpeness(); - try { - txManager.commitAllPendingRecords(iRequesterId, iTx); + final long timer = OProfiler.getInstance().startChrono(); - } catch (IOException e) { - rollback(iRequesterId, iTx); + final boolean locked = acquireExclusiveLock(); - } finally { - releaseSharedLock(locked); - } + try { + for (OCluster cluster : clusters) + cluster.synch(); - } + for (ODataLocal data : dataSegments) + data.synch(); - public void rollback(final int iRequesterId, final OTransaction<?> iTx) { - } + } finally { + releaseExclusiveLock(locked); - public void synch() { - checkOpeness(); + OProfiler.getInstance().stopChrono("OStorageLocal.synch", timer); + } + } - final long timer = OProfiler.getInstance().startChrono(); + public String getPhysicalClusterNameById(final int iClusterId) { + checkOpeness(); - final boolean locked = acquireExclusiveLock(); + for (OCluster cluster : clusters) + if (cluster != null && cluster.getId() == iClusterId) + return cluster.getName(); - try { - for (OCluster cluster : clusters) - cluster.synch(); + return null; + } - for (ODataLocal data : dataSegments) - data.synch(); + @Override + public OStorageConfiguration getConfiguration() { + return configuration; + } - } finally { - releaseExclusiveLock(locked); + public int getDefaultClusterId() { + return defaultClusterId; + } - OProfiler.getInstance().stopChrono("OStorageLocal.synch", timer); - } - } + public OCluster getClusterById(int iClusterId) { + if (iClusterId == ORID.CLUSTER_ID_INVALID) + // GET THE DEFAULT CLUSTER + iClusterId = defaultClusterId; - public String getPhysicalClusterNameById(final int iClusterId) { - checkOpeness(); + checkClusterSegmentIndexRange(iClusterId); - for (OCluster cluster : clusters) - if (cluster != null && cluster.getId() == iClusterId) - return cluster.getName(); + return clusters[iClusterId]; + } - return null; - } + public OCluster getClusterByName(final String iClusterName) { + final boolean locked = acquireSharedLock(); - @Override - public OStorageConfiguration getConfiguration() { - return configuration; - } + try { + final OCluster cluster = clusterMap.get(iClusterName.toLowerCase()); - public int getDefaultClusterId() { - return defaultClusterId; - } + if (cluster == null) + throw new IllegalArgumentException("Cluster " + iClusterName + " not exists"); + return cluster; - public OCluster getClusterById(int iClusterId) { - if (iClusterId == ORID.CLUSTER_ID_INVALID) - // GET THE DEFAULT CLUSTER - iClusterId = defaultClusterId; + } finally { - checkClusterSegmentIndexRange(iClusterId); + releaseSharedLock(locked); + } + } - return clusters[iClusterId]; - } + public ODictionary<?> createDictionary(ODatabaseRecord<?> iDatabase) throws Exception { + return new ODictionaryLocal<Object>(iDatabase); + } - public OCluster getClusterByName(final String iClusterName) { - final boolean locked = acquireSharedLock(); + public String getStoragePath() { + return storagePath; + } - try { - final OCluster cluster = clusterMap.get(iClusterName.toLowerCase()); + public String getMode() { + return mode; + } - if (cluster == null) - throw new IllegalArgumentException("Cluster " + iClusterName + " not exists"); - return cluster; + public OStorageVariableParser getVariableParser() { + return variableParser; + } - } finally { + protected int registerDataSegment(final OStorageDataConfiguration iConfig) throws IOException { + checkOpeness(); - releaseSharedLock(locked); - } - } + int pos = 0; - public ODictionary<?> createDictionary(ODatabaseRecord<?> iDatabase) throws Exception { - return new ODictionaryLocal<Object>(iDatabase); - } + // CHECK FOR DUPLICATION OF NAMES + for (ODataLocal data : dataSegments) + if (data.getName().equals(iConfig.name)) { + // OVERWRITE CONFIG + data.config = iConfig; + return -1; + } + pos = dataSegments.length; - public String getStoragePath() { - return storagePath; - } + // CREATE AND ADD THE NEW REF SEGMENT + ODataLocal segment = new ODataLocal(this, iConfig, pos); - public String getMode() { - return mode; - } + dataSegments = OArrays.copyOf(dataSegments, dataSegments.length + 1); + dataSegments[pos] = segment; - public OStorageVariableParser getVariableParser() { - return variableParser; - } + return pos; + } - protected int registerDataSegment(final OStorageDataConfiguration iConfig) throws IOException { - checkOpeness(); + /** + * Create the cluster by reading the configuration received as argument and register it assigning it the higher serial id. + * + * @param iConfig + * A OStorageClusterConfiguration implementation, namely physical or logical + * @return The id (physical position into the array) of the new cluster just created. First is 0. + * @throws IOException + * @throws IOException + */ + private int createClusterFromConfig(final OStorageClusterConfiguration iConfig) throws IOException { + if (clusterMap.containsKey(iConfig.getName())) { + OCluster c = clusterMap.get(iConfig.getName()); + if (c instanceof OClusterLocal) + // ALREADY CONFIGURED, JUST OVERWRITE CONFIG + ((OClusterLocal) c).config = (OStorageSegmentConfiguration) iConfig; + return -1; + } - int pos = 0; + final OCluster cluster; - // CHECK FOR DUPLICATION OF NAMES - for (ODataLocal data : dataSegments) - if (data.getName().equals(iConfig.name)) { - // OVERWRITE CONFIG - data.config = iConfig; - return -1; - } - pos = dataSegments.length; + if (iConfig instanceof OStoragePhysicalClusterConfiguration) { + cluster = new OClusterLocal(this, (OStoragePhysicalClusterConfiguration) iConfig); + } else + cluster = new OClusterLogical(this, (OStorageLogicalClusterConfiguration) iConfig); - // CREATE AND ADD THE NEW REF SEGMENT - ODataLocal segment = new ODataLocal(this, iConfig, pos); + return registerCluster(cluster); + } - dataSegments = OArrays.copyOf(dataSegments, dataSegments.length + 1); - dataSegments[pos] = segment; + /** + * Register the cluster internally. + * + * @param cluster + * OCluster implementation + * @return The id (physical position into the array) of the new cluster just created. First is 0. + * @throws IOException + */ + private int registerCluster(final OCluster cluster) throws IOException { + // CHECK FOR DUPLICATION OF NAMES + if (clusterMap.containsKey(cluster.getName())) + throw new OConfigurationException("Can't add segment " + cluster.getName() + " because it was already registered"); - return pos; - } + // CREATE AND ADD THE NEW REF SEGMENT + clusterMap.put(cluster.getName(), cluster); - /** - * Create the cluster by reading the configuration received as argument and register it assigning it the higher serial id. - * - * @param iConfig - * A OStorageClusterConfiguration implementation, namely physical or logical - * @return The id (physical position into the array) of the new cluster just created. First is 0. - * @throws IOException - * @throws IOException - */ - private int createClusterFromConfig(final OStorageClusterConfiguration iConfig) throws IOException { - if (clusterMap.containsKey(iConfig.getName())) { - OCluster c = clusterMap.get(iConfig.getName()); - if (c instanceof OClusterLocal) - // ALREADY CONFIGURED, JUST OVERWRITE CONFIG - ((OClusterLocal) c).config = (OStorageSegmentConfiguration) iConfig; - return -1; - } + final int id = clusters.length; - final OCluster cluster; + clusters = OArrays.copyOf(clusters, id + 1); + clusters[id] = cluster; - if (iConfig instanceof OStoragePhysicalClusterConfiguration) { - cluster = new OClusterLocal(this, (OStoragePhysicalClusterConfiguration) iConfig); - } else - cluster = new OClusterLogical(this, (OStorageLogicalClusterConfiguration) iConfig); + return id; + } - return registerCluster(cluster); - } + private void checkClusterSegmentIndexRange(final int iClusterId) { + if (iClusterId > clusters.length - 1) + throw new IllegalArgumentException("Cluster segment #" + iClusterId + " not exists"); + } - /** - * Register the cluster internally. - * - * @param cluster - * OCluster implementation - * @return The id (physical position into the array) of the new cluster just created. First is 0. - * @throws IOException - */ - private int registerCluster(final OCluster cluster) throws IOException { - // CHECK FOR DUPLICATION OF NAMES - if (clusterMap.containsKey(cluster.getName())) - throw new OConfigurationException("Can't add segment " + cluster.getName() + " because it was already registered"); + protected int getDataSegmentForRecord(final OCluster iCluster, final byte[] iContent) { + // TODO: CREATE POLICY & STRATEGY TO ASSIGN THE BEST-MULTIPLE DATA + // SEGMENT + return 0; + } - // CREATE AND ADD THE NEW REF SEGMENT - clusterMap.put(cluster.getName(), cluster); + protected long createRecord(final OCluster iClusterSegment, final byte[] iContent, final byte iRecordType) { + checkOpeness(); - final int id = clusters.length; + if (iContent == null) + throw new IllegalArgumentException("Record " + iContent + " is null"); - clusters = OArrays.copyOf(clusters, id + 1); - clusters[id] = cluster; + final long timer = OProfiler.getInstance().startChrono(); - return id; - } + final boolean locked = acquireSharedLock(); - private void checkClusterSegmentIndexRange(final int iClusterId) { - if (iClusterId > clusters.length - 1) - throw new IllegalArgumentException("Cluster segment #" + iClusterId + " not exists"); - } + try { + final int dataSegment = getDataSegmentForRecord(iClusterSegment, iContent); + ODataLocal data = getDataSegment(dataSegment); - protected int getDataSegmentForRecord(final OCluster iCluster, final byte[] iContent) { - // TODO: CREATE POLICY & STRATEGY TO ASSIGN THE BEST-MULTIPLE DATA SEGMENT - return 0; - } + final long clusterPosition = iClusterSegment.addPhysicalPosition(-1, -1, iRecordType); - protected long createRecord(final OCluster iClusterSegment, final byte[] iContent, final byte iRecordType) { - checkOpeness(); + final long dataOffset = data.addRecord(iClusterSegment.getId(), clusterPosition, iContent); - if (iContent == null) - throw new IllegalArgumentException("Record " + iContent + " is null"); + // UPDATE THE POSITION IN CLUSTER WITH THE POSITION OF RECORD IN + // DATA + iClusterSegment.setPhysicalPosition(clusterPosition, dataSegment, dataOffset, iRecordType); - final long timer = OProfiler.getInstance().startChrono(); + return clusterPosition; - final boolean locked = acquireSharedLock(); + } catch (IOException e) { - try { - final int dataSegment = getDataSegmentForRecord(iClusterSegment, iContent); - ODataLocal data = getDataSegment(dataSegment); + OLogManager.instance().error(this, "Error on creating record in cluster: " + iClusterSegment, e); + return -1; + } finally { + releaseSharedLock(locked); - final long clusterPosition = iClusterSegment.addPhysicalPosition(-1, -1, iRecordType); + OProfiler.getInstance().stopChrono("OStorageLocal.createRecord", timer); + } + } - final long dataOffset = data.addRecord(iClusterSegment.getId(), clusterPosition, iContent); + protected ORawBuffer readRecord(final int iRequesterId, final OCluster iClusterSegment, final long iPosition, boolean iAtomicLock) { + if (iPosition < 0) + throw new IllegalArgumentException("Can't read the record because the position #" + iPosition + " is invalid"); - // UPDATE THE POSITION IN CLUSTER WITH THE POSITION OF RECORD IN DATA - iClusterSegment.setPhysicalPosition(clusterPosition, dataSegment, dataOffset, iRecordType); + // NOT FOUND: SEARCH IT IN THE STORAGE + final long timer = OProfiler.getInstance().startChrono(); - return clusterPosition; + // GET LOCK ONLY IF IT'S IN ATOMIC-MODE (SEE THE PARAMETER iAtomicLock) + // USUALLY BROWSING OPERATIONS (QUERY) AVOID ATOMIC LOCKING + // TO IMPROVE PERFORMANCES BY LOCKING THE ENTIRE CLUSTER FROM THE + // OUTSIDE. + final boolean locked = iAtomicLock ? acquireSharedLock() : false; - } catch (IOException e) { + try { + // lockManager.acquireLock(iRequesterId, recId, LOCK.SHARED, + // timeout); - OLogManager.instance().error(this, "Error on creating record in cluster: " + iClusterSegment, e); - return -1; - } finally { - releaseSharedLock(locked); + final OPhysicalPosition ppos = iClusterSegment.getPhysicalPosition(iPosition, new OPhysicalPosition()); + if (ppos == null || !checkForRecordValidity(ppos)) + // DELETED + return null; - OProfiler.getInstance().stopChrono("OStorageLocal.createRecord", timer); - } - } + final ODataLocal data = getDataSegment(ppos.dataSegment); + return new ORawBuffer(data.getRecord(ppos.dataPosition), ppos.version, ppos.type); - protected ORawBuffer readRecord(final int iRequesterId, final OCluster iClusterSegment, final long iPosition, boolean iAtomicLock) { - if (iPosition < 0) - throw new IllegalArgumentException("Can't read the record because the position #" + iPosition + " is invalid"); + } catch (IOException e) { - // NOT FOUND: SEARCH IT IN THE STORAGE - final long timer = OProfiler.getInstance().startChrono(); + OLogManager.instance().error(this, "Error on reading record #" + iPosition + " in cluster: " + iClusterSegment, e); + return null; - // GET LOCK ONLY IF IT'S IN ATOMIC-MODE (SEE THE PARAMETER iAtomicLock) USUALLY BROWSING OPERATIONS (QUERY) AVOID ATOMIC LOCKING - // TO IMPROVE PERFORMANCES BY LOCKING THE ENTIRE CLUSTER FROM THE OUTSIDE. - final boolean locked = iAtomicLock ? acquireSharedLock() : false; + } finally { + releaseSharedLock(locked); - try { - // lockManager.acquireLock(iRequesterId, recId, LOCK.SHARED, timeout); + OProfiler.getInstance().stopChrono("OStorageLocal.readRecord", timer); + } + } - final OPhysicalPosition ppos = iClusterSegment.getPhysicalPosition(iPosition, new OPhysicalPosition()); - if (ppos == null || !checkForRecordValidity(ppos)) - // DELETED - return null; + protected int updateRecord(final int iRequesterId, final OCluster iClusterSegment, final long iPosition, final byte[] iContent, + final int iVersion, final byte iRecordType) { + final long timer = OProfiler.getInstance().startChrono(); - final ODataLocal data = getDataSegment(ppos.dataSegment); - return new ORawBuffer(data.getRecord(ppos.dataPosition), ppos.version, ppos.type); + final String recId = ORecordId.generateString(iClusterSegment.getId(), iPosition); - } catch (IOException e) { + final boolean locked = acquireSharedLock(); - OLogManager.instance().error(this, "Error on reading record #" + iPosition + " in cluster: " + iClusterSegment, e); - return null; + try { + // lockManager.acquireLock(iRequesterId, recId, LOCK.EXCLUSIVE, + // timeout); - } finally { - releaseSharedLock(locked); + final OPhysicalPosition ppos = iClusterSegment.getPhysicalPosition(iPosition, new OPhysicalPosition()); + if (!checkForRecordValidity(ppos)) + // DELETED + return -1; - OProfiler.getInstance().stopChrono("OStorageLocal.readRecord", timer); - } - } + // MVCC TRANSACTION: CHECK IF VERSION IS THE SAME + if (iVersion > -1 && ppos.version != iVersion) + throw new OConcurrentModificationException( + "Can't update record #" + + recId + + " because it has been modified by another user in the meanwhile of current transaction. Use pessimistic locking instead of optimistic or simply re-execute the transaction"); - protected int updateRecord(final int iRequesterId, final OCluster iClusterSegment, final long iPosition, final byte[] iContent, - final int iVersion, final byte iRecordType) { - final long timer = OProfiler.getInstance().startChrono(); + if (ppos.type != iRecordType) + iClusterSegment.updateRecordType(iPosition, iRecordType); - final String recId = ORecordId.generateString(iClusterSegment.getId(), iPosition); + iClusterSegment.updateVersion(iPosition, ++ppos.version); - final boolean locked = acquireSharedLock(); + final long newDataSegmentOffset = getDataSegment(ppos.dataSegment).setRecord(ppos.dataPosition, iClusterSegment.getId(), + iPosition, iContent); - try { - // lockManager.acquireLock(iRequesterId, recId, LOCK.EXCLUSIVE, timeout); + if (newDataSegmentOffset != ppos.dataPosition) + // UPDATE DATA SEGMENT OFFSET WITH THE NEW PHYSICAL POSITION + iClusterSegment.setPhysicalPosition(iPosition, ppos.dataSegment, newDataSegmentOffset, iRecordType); - final OPhysicalPosition ppos = iClusterSegment.getPhysicalPosition(iPosition, new OPhysicalPosition()); - if (!checkForRecordValidity(ppos)) - // DELETED - return -1; + return ppos.version; - // MVCC TRANSACTION: CHECK IF VERSION IS THE SAME - if (iVersion > -1 && ppos.version != iVersion) - throw new OConcurrentModificationException( - "Can't update record #" - + recId - + " because it has been modified by another user in the meanwhile of current transaction. Use pessimistic locking instead of optimistic or simply re-execute the transaction"); + } catch (IOException e) { - if (ppos.type != iRecordType) - iClusterSegment.updateRecordType(iPosition, iRecordType); + OLogManager.instance().error(this, "Error on updating record #" + iPosition + " in cluster: " + iClusterSegment, e); - iClusterSegment.updateVersion(iPosition, ++ppos.version); + } finally { + releaseSharedLock(locked); - final long newDataSegmentOffset = getDataSegment(ppos.dataSegment).setRecord(ppos.dataPosition, iClusterSegment.getId(), - iPosition, iContent); + OProfiler.getInstance().stopChrono("OStorageLocal.updateRecord", timer); + } - if (newDataSegmentOffset != ppos.dataPosition) - // UPDATE DATA SEGMENT OFFSET WITH THE NEW PHYSICAL POSITION - iClusterSegment.setPhysicalPosition(iPosition, ppos.dataSegment, newDataSegmentOffset, iRecordType); + return -1; + } - return ppos.version; + protected boolean deleteRecord(final int iRequesterId, final OCluster iClusterSegment, final long iPosition, final int iVersion) { + final long timer = OProfiler.getInstance().startChrono(); - } catch (IOException e) { + final String recId = ORecordId.generateString(iClusterSegment.getId(), iPosition); - OLogManager.instance().error(this, "Error on updating record #" + iPosition + " in cluster: " + iClusterSegment, e); + final boolean locked = acquireSharedLock(); - } finally { - releaseSharedLock(locked); + try { + final OPhysicalPosition ppos = iClusterSegment.getPhysicalPosition(iPosition, new OPhysicalPosition()); - OProfiler.getInstance().stopChrono("OStorageLocal.updateRecord", timer); - } + if (!checkForRecordValidity(ppos)) + // ALREADY DELETED + return false; - return -1; - } + // MVCC TRANSACTION: CHECK IF VERSION IS THE SAME + if (iVersion > -1 && ppos.version != iVersion) + throw new OConcurrentModificationException( + "Can't delete the record #" + + recId + + " because it was modified by another user in the meanwhile of current transaction. Use pessimistic locking instead of optimistic or simply re-execute the transaction"); - protected boolean deleteRecord(final int iRequesterId, final OCluster iClusterSegment, final long iPosition, final int iVersion) { - final long timer = OProfiler.getInstance().startChrono(); + iClusterSegment.removePhysicalPosition(iPosition, ppos); - final String recId = ORecordId.generateString(iClusterSegment.getId(), iPosition); + getDataSegment(ppos.dataSegment).deleteRecord(ppos.dataPosition); - final boolean locked = acquireSharedLock(); + return true; - try { - final OPhysicalPosition ppos = iClusterSegment.getPhysicalPosition(iPosition, new OPhysicalPosition()); + } catch (IOException e) { - if (!checkForRecordValidity(ppos)) - // ALREADY DELETED - return false; + OLogManager.instance().error(this, "Error on deleting record #" + iPosition + " in cluster: " + iClusterSegment, e); - // MVCC TRANSACTION: CHECK IF VERSION IS THE SAME - if (iVersion > -1 && ppos.version != iVersion) - throw new OConcurrentModificationException( - "Can't delete the record #" - + recId - + " because it was modified by another user in the meanwhile of current transaction. Use pessimistic locking instead of optimistic or simply re-execute the transaction"); + } finally { + releaseSharedLock(locked); - iClusterSegment.removePhysicalPosition(iPosition, ppos); + OProfiler.getInstance().stopChrono("OStorageLocal.deleteRecord", timer); + } - getDataSegment(ppos.dataSegment).deleteRecord(ppos.dataPosition); + return false; + } - return true; + /** + * Check if the storage is open. If it's closed an exception is raised. + */ + private void checkOpeness() { + if (!open) + throw new OStorageException("Storage " + name + " is not opened."); + } - } catch (IOException e) { + public Set<OCluster> getClusters() { + Set<OCluster> result = new HashSet<OCluster>(); - OLogManager.instance().error(this, "Error on deleting record #" + iPosition + " in cluster: " + iClusterSegment, e); + // ADD ALL THE CLUSTERS + for (OCluster c : clusters) + result.add(c); - } finally { - releaseSharedLock(locked); + return result; + } - OProfiler.getInstance().stopChrono("OStorageLocal.deleteRecord", timer); - } + /** + * Execute the command request and return the result back. + */ + public Object command(final OCommandRequestText iCommand) { + final OCommandExecutor executor = OCommandManager.instance().getExecutor(iCommand); + executor.parse(iCommand); + try { + return executor.execute(); + } catch (OCommandExecutionException e) { + // PASS THROUGHT + throw e; + } catch (Exception e) { + throw new OCommandExecutionException("Error on execution of command: " + iCommand, e); + } + } - return false; - } + /** + * Add a new physical cluster into the storage. + * + * @throws IOException + */ + private int addPhysicalCluster(final String iClusterName, String iClusterFileName, final int iStartSize) throws IOException { + final OStoragePhysicalClusterConfiguration config = new OStoragePhysicalClusterConfiguration(configuration, iClusterName, + clusters.length); + configuration.clusters.add(config); - /** - * Check if the storage is open. If it's closed an exception is raised. - */ - private void checkOpeness() { - if (!open) - throw new OStorageException("Storage " + name + " is not opened."); - } + final OClusterLocal cluster = new OClusterLocal(this, config); + final int id = registerCluster(cluster); - public Set<OCluster> getClusters() { - Set<OCluster> result = new HashSet<OCluster>(); + clusters[id].create(iStartSize); + configuration.update(); + return id; + } - // ADD ALL THE CLUSTERS - for (OCluster c : clusters) - result.add(c); + private int addLogicalCluster(final String iClusterName, final int iPhysicalCluster) throws IOException { + final OStorageLogicalClusterConfiguration config = new OStorageLogicalClusterConfiguration(iClusterName, clusters.length, + iPhysicalCluster, null); - return result; - } - - /** - * Execute the command request and return the result back. - */ - public Object command(final OCommandRequestText iCommand) { - final OCommandExecutor executor = OCommandManager.instance().getExecutor(iCommand); - executor.parse(iCommand); - try { - return executor.execute(); - } catch (OCommandExecutionException e) { - // PASS THROUGHT - throw e; - } catch (Exception e) { - throw new OCommandExecutionException("Error on execution of command: " + iCommand, e); - } - } - - /** - * Add a new physical cluster into the storage. - * - * @throws IOException - */ - private int addPhysicalCluster(final String iClusterName, String iClusterFileName, final int iStartSize) throws IOException { - final OStoragePhysicalClusterConfiguration config = new OStoragePhysicalClusterConfiguration(configuration, iClusterName, - clusters.length); - configuration.clusters.add(config); - - final OClusterLocal cluster = new OClusterLocal(this, config); - final int id = registerCluster(cluster); - - clusters[id].create(iStartSize); - configuration.update(); - return id; - } - - private int addLogicalCluster(final String iClusterName, final int iPhysicalCluster) throws IOException { - final OStorageLogicalClusterConfiguration config = new OStorageLogicalClusterConfiguration(iClusterName, clusters.length, - iPhysicalCluster, null); - - configuration.clusters.add(config); - - final OClusterLogical cluster = new OClusterLogical(this, clusters.length, iClusterName, iPhysicalCluster); - config.map = cluster.getRID(); - final int id = registerCluster(cluster); - - configuration.update(); - return id; - } - - public ODataLocal[] getDataSegments() { - return dataSegments; - } - - public OStorageLocalTxExecuter getTxManager() { - return txManager; - } + configuration.clusters.add(config); + + final OClusterLogical cluster = new OClusterLogical(this, clusters.length, iClusterName, iPhysicalCluster); + config.map = cluster.getRID(); + final int id = registerCluster(cluster); + + configuration.update(); + return id; + } + + public ODataLocal[] getDataSegments() { + return dataSegments; + } + + public OStorageLocalTxExecuter getTxManager() { + return txManager; + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OClusterMemory.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OClusterMemory.java index c0eedb04af3..60b1ee15859 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OClusterMemory.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OClusterMemory.java @@ -25,12 +25,12 @@ import com.orientechnologies.orient.core.storage.OPhysicalPosition; public class OClusterMemory extends OSharedResource implements OCluster { - public static final String TYPE = "MEMORY"; + public static final String TYPE = "MEMORY"; - private int id; - private String name; - private List<OPhysicalPosition> entries = new ArrayList<OPhysicalPosition>(); - private int removed = 0; + private int id; + private String name; + private List<OPhysicalPosition> entries = new ArrayList<OPhysicalPosition>(); + private int removed = 0; public OClusterMemory(final int id, final String name) { this.id = id; @@ -57,6 +57,10 @@ public long getEntries() { return entries.size() - removed; } + public long getFirstEntryPosition() { + return 0; + } + public long getLastEntryPosition() { return entries.size(); } @@ -73,12 +77,15 @@ public long getAvailablePosition() throws IOException { return entries.size(); } - public long addPhysicalPosition(final int iDataSegmentId, final long iRecordPosition, final byte iRecordType) { - entries.add(new OPhysicalPosition(iDataSegmentId, iRecordPosition, iRecordType)); + public long addPhysicalPosition(final int iDataSegmentId, + final long iRecordPosition, final byte iRecordType) { + entries.add(new OPhysicalPosition(iDataSegmentId, iRecordPosition, + iRecordType)); return entries.size() - 1; } - public void updateRecordType(final long iPosition, final byte iRecordType) throws IOException { + public void updateRecordType(final long iPosition, final byte iRecordType) + throws IOException { entries.get((int) iPosition).type = iRecordType; } @@ -86,20 +93,23 @@ public void updateVersion(long iPosition, int iVersion) throws IOException { entries.get((int) iPosition).version = iVersion; } - public OPhysicalPosition getPhysicalPosition(final long iPosition, final OPhysicalPosition iPPosition) { + public OPhysicalPosition getPhysicalPosition(final long iPosition, + final OPhysicalPosition iPPosition) { return entries.get((int) iPosition); } public void open() throws IOException { } - public void removePhysicalPosition(final long iPosition, OPhysicalPosition iPPosition) { + public void removePhysicalPosition(final long iPosition, + OPhysicalPosition iPPosition) { if (entries.set((int) iPosition, null) != null) // ADD A REMOVED removed++; } - public void setPhysicalPosition(final long iPosition, final int iDataId, final long iDataPosition, final byte iRecordType) { + public void setPhysicalPosition(final long iPosition, final int iDataId, + final long iDataPosition, final byte iRecordType) { final OPhysicalPosition ppos = entries.get((int) iPosition); ppos.dataSegment = iDataId; ppos.dataPosition = iDataPosition; diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OStorageMemory.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OStorageMemory.java index 2a0a386190a..6969a6a7792 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OStorageMemory.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/OStorageMemory.java @@ -216,10 +216,10 @@ public long count(final int iClusterId) { } } - public long getClusterLastEntryPosition(final int iClusterId) { + public long[] getClusterDataRange(final int iClusterId) { final OCluster cluster = getClusterById(iClusterId); try { - return cluster.getLastEntryPosition(); + return new long[]{ cluster.getFirstEntryPosition(), cluster.getLastEntryPosition() }; } catch (IOException e) { throw new OStorageException("Error on getting last entry position in cluster: " + iClusterId, e); } diff --git a/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryProtocol.java b/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryProtocol.java index bc841416dde..732c7b395af 100644 --- a/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryProtocol.java +++ b/enterprise/src/main/java/com/orientechnologies/orient/enterprise/channel/binary/OChannelBinaryProtocol.java @@ -29,7 +29,7 @@ public class OChannelBinaryProtocol { public static final byte CLUSTER_ADD = 10; public static final byte CLUSTER_REMOVE = 11; public static final byte CLUSTER_COUNT = 12; - public static final byte CLUSTER_LASTPOS = 13; + public static final byte CLUSTER_DATARANGE = 13; public static final byte DATASEGMENT_ADD = 20; public static final byte DATASEGMENT_REMOVE = 21; 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 fa2f4e62c24..f45f2a79d6a 100644 --- 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 @@ -71,21 +71,22 @@ import com.orientechnologies.orient.server.tx.OTransactionRecordProxy; public class ONetworkProtocolBinary extends ONetworkProtocol { - protected OClientConnection connection; - protected OChannelBinary channel; - protected OUser account; + protected OClientConnection connection; + protected OChannelBinary channel; + protected OUser account; - private String user; - private String passwd; - private ODatabaseRaw underlyingDatabase; - private int commandType; + private String user; + private String passwd; + private ODatabaseRaw underlyingDatabase; + private int commandType; public ONetworkProtocolBinary() { super(OServer.getThreadGroup(), "Binary-DB"); } @Override - public void config(final Socket iSocket, final OClientConnection iConnection) throws IOException { + public void config(final Socket iSocket, final OClientConnection iConnection) + throws IOException { channel = new OChannelBinaryServer(iSocket); connection = iConnection; @@ -127,11 +128,13 @@ protected void execute() throws Exception { passwd = channel.readString(); // SEARCH THE DB IN MEMORY FIRST - connection.database = (ODatabaseDocumentTx) OServerMain.server().getMemoryDatabases().get(dbName); + connection.database = (ODatabaseDocumentTx) OServerMain + .server().getMemoryDatabases().get(dbName); if (connection.database == null) // SEARCH THE DB IN LOCAL FS - connection.database = new ODatabaseDocumentTx(OServerMain.server().getStoragePath(dbName)); + connection.database = new ODatabaseDocumentTx(OServerMain + .server().getStoragePath(dbName)); if (connection.database.isClosed()) if (connection.database.getStorage() instanceof OStorageMemory) @@ -139,16 +142,23 @@ protected void execute() throws Exception { else connection.database.open(user, passwd); - underlyingDatabase = ((ODatabaseRaw) ((ODatabaseComplex<?>) connection.database.getUnderlying()).getUnderlying()); + underlyingDatabase = ((ODatabaseRaw) ((ODatabaseComplex<?>) connection.database + .getUnderlying()).getUnderlying()); - if (!(underlyingDatabase.getStorage() instanceof OStorageMemory) && !loadUserFromSchema(user, passwd)) { - sendError(new OSecurityAccessException(connection.database.getName(), "Access denied to database '" - + connection.database.getName() + "' for user: " + user)); + if (!(underlyingDatabase.getStorage() instanceof OStorageMemory) + && !loadUserFromSchema(user, passwd)) { + sendError(new OSecurityAccessException( + connection.database.getName(), + "Access denied to database '" + + connection.database.getName() + + "' for user: " + user)); } else { sendOk(); channel.writeString(connection.id); - channel.writeInt(connection.database.getClusterNames().size()); - for (OCluster c : (connection.database.getStorage()).getClusters()) { + channel.writeInt(connection.database.getClusterNames() + .size()); + for (OCluster c : (connection.database.getStorage()) + .getClusters()) { if (c != null) { channel.writeString(c.getName()); channel.writeInt(c.getId()); @@ -170,18 +180,25 @@ protected void execute() throws Exception { if (storageMode.equals(OEngineLocal.NAME)) { if (OServerMain.server().existsStoragePath(dbName)) - throw new IllegalArgumentException("Database '" + dbName + "' already exists."); + throw new IllegalArgumentException("Database '" + + dbName + "' already exists."); - path = storageMode + ":${ORIENTDB_HOME}/databases/" + dbName + "/" + dbName; - realPath = OSystemVariableResolver.resolveSystemVariables(path); + path = storageMode + ":${ORIENTDB_HOME}/databases/" + + dbName + "/" + dbName; + realPath = OSystemVariableResolver + .resolveSystemVariables(path); } else if (storageMode.equals(OEngineMemory.NAME)) { - if (OServerMain.server().getMemoryDatabases().containsKey(dbName)) - throw new IllegalArgumentException("Database '" + dbName + "' already exists."); + if (OServerMain.server().getMemoryDatabases() + .containsKey(dbName)) + throw new IllegalArgumentException("Database '" + + dbName + "' already exists."); path = storageMode + ":" + dbName; realPath = path; } else - throw new IllegalArgumentException("Can't create databse: storage mode '" + storageMode + "' is not supported."); + throw new IllegalArgumentException( + "Can't create databse: storage mode '" + + storageMode + "' is not supported."); connection.database = new ODatabaseDocumentTx(realPath); connection.database.create(); @@ -192,10 +209,12 @@ protected void execute() throws Exception { } else if (storageMode.equals(OEngineMemory.NAME)) { // SAVE THE DB IN MEMORY - OServerMain.server().getMemoryDatabases().put(dbName, connection.database); + OServerMain.server().getMemoryDatabases() + .put(dbName, connection.database); } - underlyingDatabase = ((ODatabaseRaw) ((ODatabaseComplex<?>) connection.database.getUnderlying()).getUnderlying()); + underlyingDatabase = ((ODatabaseRaw) ((ODatabaseComplex<?>) connection.database + .getUnderlying()).getUnderlying()); sendOk(); break; @@ -223,20 +242,23 @@ protected void execute() throws Exception { for (int i = 0; i < clusterIds.length; ++i) clusterIds[i] = channel.readShort(); - long count = connection.database.countClusterElements(clusterIds); + long count = connection.database + .countClusterElements(clusterIds); sendOk(); channel.writeLong(count); break; } - case OChannelBinaryProtocol.CLUSTER_LASTPOS: { - data.commandInfo = "Get last entry position in cluster"; + case OChannelBinaryProtocol.CLUSTER_DATARANGE: { + data.commandInfo = "Get the begin/end range of data in cluster"; - long pos = connection.database.getStorage().getClusterLastEntryPosition(channel.readShort()); + long[] pos = connection.database.getStorage() + .getClusterDataRange(channel.readShort()); sendOk(); - channel.writeLong(pos); + channel.writeLong(pos[0]); + channel.writeLong(pos[1]); break; } @@ -248,9 +270,11 @@ protected void execute() throws Exception { final int num; if (OClusterLocal.TYPE.equals(type)) - num = connection.database.addPhysicalCluster(name, channel.readString(), channel.readInt()); + num = connection.database.addPhysicalCluster(name, + channel.readString(), channel.readInt()); else - num = connection.database.addLogicalCluster(name, channel.readInt()); + num = connection.database.addLogicalCluster(name, + channel.readInt()); sendOk(); channel.writeShort((short) num); @@ -262,7 +286,8 @@ protected void execute() throws Exception { final int id = channel.readShort(); - boolean result = connection.database.getStorage().removeCluster(id); + boolean result = connection.database.getStorage() + .removeCluster(id); sendOk(); channel.writeByte((byte) (result ? '1' : '0')); @@ -277,7 +302,8 @@ protected void execute() throws Exception { final String fetchPlanString = channel.readString(); // LOAD THE RAW BUFFER - final ORawBuffer buffer = underlyingDatabase.read(clusterId, clusterPosition, null); + final ORawBuffer buffer = underlyingDatabase.read(clusterId, + clusterPosition, null); sendOk(); if (buffer != null) { @@ -288,33 +314,50 @@ protected void execute() throws Exception { channel.writeByte(buffer.recordType); if (fetchPlanString.length() > 0) { - // BUILD THE SERVER SIDE RECORD TO ACCES TO THE FETCH PLAN - final ORecordInternal<?> record = ORecordFactory.newInstance(buffer.recordType); - record.fill(connection.database, clusterId, clusterPosition, buffer.version); + // BUILD THE SERVER SIDE RECORD TO ACCES TO THE FETCH + // PLAN + final ORecordInternal<?> record = ORecordFactory + .newInstance(buffer.recordType); + record.fill(connection.database, clusterId, + clusterPosition, buffer.version); record.fromStream(buffer.buffer); if (record instanceof ODocument) { - final Map<String, Integer> fetchPlan = OFetchHelper.buildFetchPlan(fetchPlanString); + final Map<String, Integer> fetchPlan = OFetchHelper + .buildFetchPlan(fetchPlanString); final Set<ODocument> recordsToSend = new HashSet<ODocument>(); - OFetchHelper.fetch((ODocument) record, record, fetchPlan, null, 0, -1, new OFetchListener() { - public int size() { - return recordsToSend.size(); - } + OFetchHelper.fetch((ODocument) record, record, + fetchPlan, null, 0, -1, + new OFetchListener() { + public int size() { + return recordsToSend.size(); + } - // ADD TO THE SET OF OBJECTS TO SEND - public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final String iFieldName, - final Object iLinked) { - if (iLinked instanceof ODocument) - return recordsToSend.add((ODocument) iLinked) ? iLinked : null; - else - return recordsToSend.addAll((Collection<? extends ODocument>) iLinked) ? iLinked : null; - } - }); + // ADD TO THE SET OF OBJECTS TO SEND + public Object fetchLinked( + final ODocument iRoot, + final Object iUserObject, + final String iFieldName, + final Object iLinked) { + if (iLinked instanceof ODocument) + return recordsToSend + .add((ODocument) iLinked) ? iLinked + : null; + else + return recordsToSend + .addAll((Collection<? extends ODocument>) iLinked) ? iLinked + : null; + } + }); // SEND RECORDS TO LOAD IN CLIENT CACHE for (ODocument doc : recordsToSend) { - channel.writeByte((byte) 2); // CLIENT CACHE RECORD. IT ISN'T PART OF THE RESULT SET + channel.writeByte((byte) 2); // CLIENT CACHE + // RECORD. IT + // ISN'T PART OF + // THE RESULT + // SET writeRecord(doc); } } @@ -331,8 +374,9 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final case OChannelBinaryProtocol.RECORD_CREATE: data.commandInfo = "Create record"; - final long location = underlyingDatabase.save(channel.readShort(), ORID.CLUSTER_POS_INVALID, channel.readBytes(), -1, - channel.readByte()); + final long location = underlyingDatabase.save( + channel.readShort(), ORID.CLUSTER_POS_INVALID, + channel.readBytes(), -1, channel.readByte()); sendOk(); channel.writeLong(location); break; @@ -343,15 +387,25 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final final int clusterId = channel.readShort(); final long position = channel.readLong(); - long newVersion = underlyingDatabase.save(clusterId, position, channel.readBytes(), channel.readInt(), channel.readByte()); + long newVersion = underlyingDatabase.save(clusterId, position, + channel.readBytes(), channel.readInt(), + channel.readByte()); // TODO: Handle it by using triggers - if (connection.database.getMetadata().getSchema().getDocument().getIdentity().getClusterId() == clusterId - && connection.database.getMetadata().getSchema().getDocument().getIdentity().getClusterPosition() == position) + if (connection.database.getMetadata().getSchema().getDocument() + .getIdentity().getClusterId() == clusterId + && connection.database.getMetadata().getSchema() + .getDocument().getIdentity() + .getClusterPosition() == position) connection.database.getMetadata().loadSchema(); - else if (((ODictionaryLocal<?>) connection.database.getDictionary()).getTree().getRecord().getIdentity().getClusterId() == clusterId - && ((ODictionaryLocal<?>) connection.database.getDictionary()).getTree().getRecord().getIdentity().getClusterPosition() == position) - ((ODictionaryLocal<?>) connection.database.getDictionary()).load(); + else if (((ODictionaryLocal<?>) connection.database + .getDictionary()).getTree().getRecord().getIdentity() + .getClusterId() == clusterId + && ((ODictionaryLocal<?>) connection.database + .getDictionary()).getTree().getRecord() + .getIdentity().getClusterPosition() == position) + ((ODictionaryLocal<?>) connection.database.getDictionary()) + .load(); sendOk(); @@ -361,7 +415,8 @@ else if (((ODictionaryLocal<?>) connection.database.getDictionary()).getTree().g case OChannelBinaryProtocol.RECORD_DELETE: data.commandInfo = "Delete record"; - underlyingDatabase.delete(channel.readShort(), channel.readLong(), channel.readInt()); + underlyingDatabase.delete(channel.readShort(), + channel.readLong(), channel.readInt()); sendOk(); channel.writeByte((byte) '1'); @@ -371,7 +426,8 @@ else if (((ODictionaryLocal<?>) connection.database.getDictionary()).getTree().g data.commandInfo = "Count cluster records"; final String clusterName = channel.readString(); - final long size = connection.database.countClusterElements(clusterName); + final long size = connection.database + .countClusterElements(clusterName); sendOk(); @@ -384,10 +440,11 @@ else if (((ODictionaryLocal<?>) connection.database.getDictionary()).getTree().g final boolean asynch = channel.readByte() == 'a'; - final OCommandRequestText command = (OCommandRequestText) OStreamSerializerAnyStreamable.INSTANCE.fromStream(channel - .readBytes()); + final OCommandRequestText command = (OCommandRequestText) OStreamSerializerAnyStreamable.INSTANCE + .fromStream(channel.readBytes()); - final OQuery<?> query = (OQuery<?>) (command instanceof OQuery<?> ? command : null); + final OQuery<?> query = (OQuery<?>) (command instanceof OQuery<?> ? command + : null); data.commandDetail = command.getText(); @@ -396,7 +453,8 @@ else if (((ODictionaryLocal<?>) connection.database.getDictionary()).getTree().g final StringBuilder empty = new StringBuilder(); final Set<ODocument> recordsToSend = new HashSet<ODocument>(); - final Map<String, Integer> fetchPlan = query != null ? OFetchHelper.buildFetchPlan(query.getFetchPlan()) : null; + final Map<String, Integer> fetchPlan = query != null ? OFetchHelper + .buildFetchPlan(query.getFetchPlan()) : null; command.setResultListener(new OCommandResultListener() { public boolean result(final Object iRecord) { @@ -412,21 +470,32 @@ public boolean result(final Object iRecord) { writeRecord((ORecordInternal<?>) iRecord); channel.flush(); - if (fetchPlan != null && iRecord instanceof ODocument) { - OFetchHelper.fetch((ODocument) iRecord, iRecord, fetchPlan, null, 0, -1, new OFetchListener() { - public int size() { - return recordsToSend.size(); - } - - // ADD TO THE SET OF OBJECT TO SEND - public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final String iFieldName, - final Object iLinked) { - if (iLinked instanceof ODocument) - return recordsToSend.add((ODocument) iLinked) ? iLinked : null; - else - return recordsToSend.addAll((Collection<? extends ODocument>) iLinked) ? iLinked : null; - } - }); + if (fetchPlan != null + && iRecord instanceof ODocument) { + OFetchHelper.fetch((ODocument) iRecord, + iRecord, fetchPlan, null, 0, -1, + new OFetchListener() { + public int size() { + return recordsToSend.size(); + } + + // ADD TO THE SET OF OBJECT TO + // SEND + public Object fetchLinked( + final ODocument iRoot, + final Object iUserObject, + final String iFieldName, + final Object iLinked) { + if (iLinked instanceof ODocument) + return recordsToSend + .add((ODocument) iLinked) ? iLinked + : null; + else + return recordsToSend + .addAll((Collection<? extends ODocument>) iLinked) ? iLinked + : null; + } + }); } } catch (IOException e) { @@ -437,7 +506,8 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final } }); - ((OCommandRequestInternal) connection.database.command(command)).execute(); + ((OCommandRequestInternal) connection.database + .command(command)).execute(); if (empty.length() == 0) try { @@ -447,14 +517,17 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final // SEND RECORDS TO LOAD IN CLIENT CACHE for (ODocument doc : recordsToSend) { - channel.writeByte((byte) 2); // CLIENT CACHE RECORD. IT ISN'T PART OF THE RESULT SET + channel.writeByte((byte) 2); // CLIENT CACHE RECORD. IT + // ISN'T PART OF THE + // RESULT SET writeRecord(doc); } channel.writeByte((byte) 0); // NO MORE RECORDS } else { // SYNCHRONOUS - final Object result = ((OCommandRequestInternal) connection.database.command(command)).execute(); + final Object result = ((OCommandRequestInternal) connection.database + .command(command)).execute(); sendOk(); @@ -469,7 +542,8 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final } else { // ANY OTHER (INCLUDING LITERALS) channel.writeByte((byte) 'a'); - channel.writeBytes(OStreamSerializerAnyRuntime.INSTANCE.toStream(result)); + channel.writeBytes(OStreamSerializerAnyRuntime.INSTANCE + .toStream(result)); } } break; @@ -479,10 +553,12 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final data.commandInfo = "Dictionary lookup"; final String key = channel.readString(); - final ORecordAbstract<?> value = connection.database.getDictionary().get(key); + final ORecordAbstract<?> value = connection.database + .getDictionary().get(key); if (value != null) - ((ODatabaseRecordTx<ORecordInternal<?>>) connection.database.getUnderlying()).load(value); + ((ODatabaseRecordTx<ORecordInternal<?>>) connection.database + .getUnderlying()).load(value); sendOk(); @@ -494,16 +570,19 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final data.commandInfo = "Dictionary put"; String key = channel.readString(); - ORecordInternal<?> value = ORecordFactory.newInstance(channel.readByte()); + ORecordInternal<?> value = ORecordFactory.newInstance(channel + .readByte()); final ORecordId rid = new ORecordId(channel.readString()); value.setIdentity(rid.clusterId, rid.clusterPosition); value.setDatabase(connection.database); - value = connection.database.getDictionary().putRecord(key, value); + value = connection.database.getDictionary().putRecord(key, + value); if (value != null) - ((ODatabaseRecordTx<ORecordInternal<?>>) connection.database.getUnderlying()).load(value); + ((ODatabaseRecordTx<ORecordInternal<?>>) connection.database + .getUnderlying()).load(value); sendOk(); @@ -515,10 +594,12 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final data.commandInfo = "Dictionary remove"; final String key = channel.readString(); - final ORecordInternal<?> value = connection.database.getDictionary().remove(key); + final ORecordInternal<?> value = connection.database + .getDictionary().remove(key); if (value != null) - ((ODatabaseRecordTx<ORecordInternal<?>>) connection.database.getUnderlying()).load(value); + ((ODatabaseRecordTx<ORecordInternal<?>>) connection.database + .getUnderlying()).load(value); sendOk(); @@ -538,15 +619,19 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final data.commandInfo = "Dictionary keys"; sendOk(); - channel.writeCollectionString(connection.database.getDictionary().keySet()); + channel.writeCollectionString(connection.database + .getDictionary().keySet()); break; } case OChannelBinaryProtocol.TX_COMMIT: data.commandInfo = "Transaction commit"; - ((OStorageLocal) connection.database.getStorage()).commit(connection.database.getId(), new OTransactionOptimisticProxy( - (ODatabaseRecordTx<OTransactionRecordProxy>) connection.database.getUnderlying(), channel)); + ((OStorageLocal) connection.database.getStorage()) + .commit(connection.database.getId(), + new OTransactionOptimisticProxy( + (ODatabaseRecordTx<OTransactionRecordProxy>) connection.database + .getUnderlying(), channel)); sendOk(); break; @@ -554,7 +639,8 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final default: data.commandInfo = "Command not supported"; - OLogManager.instance().error(this, "Request not supported. Code: " + commandType); + OLogManager.instance().error(this, + "Request not supported. Code: " + commandType); channel.clearInput(); sendError(null); @@ -572,12 +658,14 @@ public Object fetchLinked(final ODocument iRoot, final Object iUserObject, final try { channel.flush(); } catch (Throwable t) { - OLogManager.instance().debug(this, "Error on send data over the network", t); + OLogManager.instance().debug(this, + "Error on send data over the network", t); } OSerializationThreadLocal.INSTANCE.get().clear(); - data.lastCommandExecutionTime = System.currentTimeMillis() - data.lastCommandReceived; + data.lastCommandExecutionTime = System.currentTimeMillis() + - data.lastCommandReceived; data.totalCommandExecutionTime += data.lastCommandExecutionTime; data.lastCommandInfo = data.commandInfo; @@ -595,7 +683,8 @@ public void shutdown() { sendShutdown(); channel.close(); - OClientConnectionManager.instance().onClientDisconnection(connection.id); + OClientConnectionManager.instance() + .onClientDisconnection(connection.id); } @Override @@ -625,11 +714,14 @@ protected void sendError(final Throwable t) throws IOException { channel.clearInput(); } - private boolean loadUserFromSchema(final String iUserName, final String iUserPassword) { - account = connection.database.getMetadata().getSecurity().getUser(iUserName); + private boolean loadUserFromSchema(final String iUserName, + final String iUserPassword) { + account = connection.database.getMetadata().getSecurity() + .getUser(iUserName); if (account == null) - throw new OSecurityAccessException(connection.database.getName(), "User '" + iUserName + "' was not found in database: " - + connection.database.getName()); + throw new OSecurityAccessException(connection.database.getName(), + "User '" + iUserName + "' was not found in database: " + + connection.database.getName()); boolean allow = account.checkPassword(iUserPassword); @@ -651,13 +743,14 @@ private boolean loadUserFromSchema(final String iUserName, final String iUserPas * @param iRecord * @throws IOException */ - private void writeRecord(final ORecordInternal<?> iRecord) throws IOException { + private void writeRecord(final ORecordInternal<?> iRecord) + throws IOException { if (iRecord == null) { channel.writeShort((short) OChannelBinaryProtocol.RECORD_NULL); } else { channel.writeShort((short) (iRecord instanceof ORecordSchemaAware<?> - && ((ORecordSchemaAware<?>) iRecord).getSchemaClass() != null ? ((ORecordSchemaAware<?>) iRecord).getSchemaClass() - .getId() : -1)); + && ((ORecordSchemaAware<?>) iRecord).getSchemaClass() != null ? ((ORecordSchemaAware<?>) iRecord) + .getSchemaClass().getId() : -1)); channel.writeByte(iRecord.getRecordType()); channel.writeShort((short) iRecord.getIdentity().getClusterId()); diff --git a/tools/src/main/java/com/orientechnologies/orient/console/cmd/OConsoleDatabaseCompare.java b/tools/src/main/java/com/orientechnologies/orient/console/cmd/OConsoleDatabaseCompare.java index f9f6f2d28d9..b8fea9effa3 100644 --- a/tools/src/main/java/com/orientechnologies/orient/console/cmd/OConsoleDatabaseCompare.java +++ b/tools/src/main/java/com/orientechnologies/orient/console/cmd/OConsoleDatabaseCompare.java @@ -139,8 +139,8 @@ private boolean compareRecords() { clusterId = storage1.getClusterIdByName(clusterName); - long db1Max = storage1.getClusterLastEntryPosition(clusterId); - long db2Max = storage2.getClusterLastEntryPosition(clusterId); + long db1Max = storage1.getClusterDataRange(clusterId)[1]; + long db2Max = storage2.getClusterDataRange(clusterId)[1]; long clusterMax = Math.max(db1Max, db2Max); for (int i = 0; i < clusterMax; ++i) { diff --git a/tools/src/main/java/com/orientechnologies/orient/console/cmd/OConsoleDatabaseImport.java b/tools/src/main/java/com/orientechnologies/orient/console/cmd/OConsoleDatabaseImport.java index 0f30a9b69ef..667ba0da585 100644 --- a/tools/src/main/java/com/orientechnologies/orient/console/cmd/OConsoleDatabaseImport.java +++ b/tools/src/main/java/com/orientechnologies/orient/console/cmd/OConsoleDatabaseImport.java @@ -462,7 +462,7 @@ record = ORecordSerializerJSON.INSTANCE.fromString(database, value, record); String rid = record.getIdentity().toString(); - long nextAvailablePos = database.getStorage().getClusterLastEntryPosition(record.getIdentity().getClusterId()) + 1; + long nextAvailablePos = database.getStorage().getClusterDataRange(record.getIdentity().getClusterId())[1] + 1; // SAVE THE RECORD if (record.getIdentity().getClusterPosition() < nextAvailablePos) {
e32f16b78909e9567d3410edd5cb760ac2a70bfd
elasticsearch
Fix file handle leak in readBlob method of- AbstractFsBlobContainer--
c
https://github.com/elastic/elasticsearch
diff --git a/src/main/java/org/elasticsearch/common/blobstore/fs/AbstractFsBlobContainer.java b/src/main/java/org/elasticsearch/common/blobstore/fs/AbstractFsBlobContainer.java index 0565220424839..ebf9eb6a83d4c 100644 --- a/src/main/java/org/elasticsearch/common/blobstore/fs/AbstractFsBlobContainer.java +++ b/src/main/java/org/elasticsearch/common/blobstore/fs/AbstractFsBlobContainer.java @@ -84,21 +84,17 @@ public void run() { FileInputStream is = null; try { is = new FileInputStream(new File(path, blobName)); - } catch (FileNotFoundException e) { - IOUtils.closeWhileHandlingException(is); - listener.onFailure(e); - return; - } - try { int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { listener.onPartial(buffer, 0, bytesRead); } - listener.onCompleted(); - } catch (Exception e) { + } catch (Throwable e) { IOUtils.closeWhileHandlingException(is); listener.onFailure(e); + return; } + IOUtils.closeWhileHandlingException(is); + listener.onCompleted(); } }); }
15fe100f951a1bba5817676c8d1f9a0fe03c1f65
restlet-framework-java
- Reference now verifies the validity of- characters before setting them. Suggested by Stephan Koops.--
a
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet/src/org/restlet/data/Reference.java b/modules/org.restlet/src/org/restlet/data/Reference.java index e845037352..605e71129d 100644 --- a/modules/org.restlet/src/org/restlet/data/Reference.java +++ b/modules/org.restlet/src/org/restlet/data/Reference.java @@ -522,13 +522,14 @@ public Reference(Reference baseRef, Reference uriReference) { * * @param baseRef * The base reference. - * @param uriReference + * @param uriRef * The URI reference, either absolute or relative. */ - public Reference(Reference baseRef, String uriReference) { + public Reference(Reference baseRef, String uriRef) { + checkValidity(uriRef); this.baseRef = baseRef; - this.internalRef = uriReference; - internalUpdate(); + this.internalRef = uriRef; + updateIndexes(); } /** @@ -649,6 +650,25 @@ public Reference addSegment(String value) { return this; } + /** + * Checks if all characters are valid. + * + * @param uriRef + * The URI reference to check. + */ + private void checkValidity(String uriRef) throws IllegalArgumentException { + if (uriRef != null) { + // Ensure that all characters are valid + for (int i = 0; i < uriRef.length(); i++) { + if (!isValid(uriRef.charAt(i))) { + throw new IllegalArgumentException( + "Invalid character detected in URI reference at index '" + + i + "': \"" + uriRef.charAt(i) + "\""); + } + } + } + } + @Override public Reference clone() { Reference newRef = new Reference(); @@ -1749,6 +1769,8 @@ public void setBaseRef(String baseUri) { * ('#'). */ public void setFragment(String fragment) { + checkValidity(fragment); + if ((fragment != null) && (fragment.indexOf('#') != -1)) { throw new IllegalArgumentException( "Illegal '#' character detected in parameter"); @@ -1777,7 +1799,7 @@ public void setFragment(String fragment) { } } - internalUpdate(); + updateIndexes(); } /** @@ -1864,8 +1886,12 @@ public void setHostPort(Integer port) { * delimiter ('#'). */ public void setIdentifier(String identifier) { - if (identifier == null) + checkValidity(identifier); + + if (identifier == null) { identifier = ""; + } + if (identifier.indexOf('#') != -1) { throw new IllegalArgumentException( "Illegal '#' character detected in parameter"); @@ -1879,7 +1905,7 @@ public void setIdentifier(String identifier) { this.internalRef = identifier; } - internalUpdate(); + updateIndexes(); } } @@ -1968,6 +1994,8 @@ public void setProtocol(Protocol protocol) { * The query component for hierarchical identifiers. */ public void setQuery(String query) { + checkValidity(query); + if (queryIndex != -1) { // Query found if (fragmentIndex != -1) { @@ -2019,7 +2047,7 @@ public void setQuery(String query) { } } - internalUpdate(); + updateIndexes(); } /** @@ -2029,8 +2057,12 @@ public void setQuery(String query) { * The relative part to set. */ public void setRelativePart(String relativePart) { - if (relativePart == null) + checkValidity(relativePart); + + if (relativePart == null) { relativePart = ""; + } + if (schemeIndex == -1) { // This is a relative reference, no scheme found if (queryIndex != -1) { @@ -2047,7 +2079,7 @@ public void setRelativePart(String relativePart) { } } - internalUpdate(); + updateIndexes(); } /** @@ -2057,6 +2089,8 @@ public void setRelativePart(String relativePart) { * The scheme component. */ public void setScheme(String scheme) { + checkValidity(scheme); + if (scheme != null) { // URI specification indicates that scheme names should be // produced in lower case @@ -2082,7 +2116,7 @@ public void setScheme(String scheme) { } } - internalUpdate(); + updateIndexes(); } /** @@ -2092,8 +2126,12 @@ public void setScheme(String scheme) { * The scheme specific part. */ public void setSchemeSpecificPart(String schemeSpecificPart) { - if (schemeSpecificPart == null) + checkValidity(schemeSpecificPart); + + if (schemeSpecificPart == null) { schemeSpecificPart = ""; + } + if (schemeIndex != -1) { // Scheme found if (fragmentIndex != -1) { @@ -2120,7 +2158,7 @@ public void setSchemeSpecificPart(String schemeSpecificPart) { } } - internalUpdate(); + updateIndexes(); } /** @@ -2222,20 +2260,10 @@ public String toString(boolean query, boolean fragment) { } /** - * Update internal indexes and check if all characters are valid. + * Updates internal indexes. */ - private void internalUpdate() { + private void updateIndexes() { if (internalRef != null) { - // Ensure that all characters are valid - for (int i = 0; i < internalRef.length(); i++) { - if (!isValid(internalRef.charAt(i))) { - throw new IllegalArgumentException( - "Invalid character detected in URI reference at index '" - + i + "': \"" + internalRef.charAt(i) - + "\""); - } - } - // Compute the indexes int firstSlashIndex = this.internalRef.indexOf('/'); this.schemeIndex = this.internalRef.indexOf(':');
3d5e8e7204d2c84cc3eb1306b1c7b7e7f971d23b
Vala
gtktemplate: Allow connecting signals of the template class itself
a
https://github.com/GNOME/vala/
diff --git a/codegen/valagtkmodule.vala b/codegen/valagtkmodule.vala index e3e00cb66d..b8c8f418ea 100644 --- a/codegen/valagtkmodule.vala +++ b/codegen/valagtkmodule.vala @@ -108,7 +108,7 @@ public class Vala.GtkModule : GSignalModule { MarkupTokenType current_token = reader.read_token (null, null); while (current_token != MarkupTokenType.EOF) { - if (current_token == MarkupTokenType.START_ELEMENT && reader.name == "object") { + if (current_token == MarkupTokenType.START_ELEMENT && (reader.name == "template" || reader.name == "object")) { var class_name = reader.get_attribute ("class"); if (class_name != null) { current_class = cclass_to_vala_map.get (class_name);
601b513c63b8d1a17601235122f6570e610cb8a4
Vala
libgda-4.0: fix vfunc names om Gda.DataModel and Gda.Lockable
c
https://github.com/GNOME/vala/
diff --git a/vapi/libgda-4.0.vapi b/vapi/libgda-4.0.vapi index 83c008b8e7..b2eb13d954 100644 --- a/vapi/libgda-4.0.vapi +++ b/vapi/libgda-4.0.vapi @@ -1462,72 +1462,44 @@ namespace Gda { } [CCode (cheader_filename = "libgda/libgda.h")] public interface DataModel : GLib.Object { - public int append_row () throws GLib.Error; - public int append_values (GLib.List values) throws GLib.Error; - public unowned Gda.DataModelIter create_iter (); - public unowned Gda.Column describe_column (int col); + [CCode (vfunc_name = "i_append_row")] + public virtual int append_row () throws GLib.Error; + [CCode (vfunc_name = "i_append_values")] + public virtual int append_values (GLib.List values) throws GLib.Error; + [CCode (vfunc_name = "i_create_iter")] + public virtual unowned Gda.DataModelIter create_iter (); + [CCode (vfunc_name = "i_describe_column")] + public virtual unowned Gda.Column describe_column (int col); public void dump (GLib.FileStream to_stream); public unowned string dump_as_string (); public static GLib.Quark error_quark (); public bool export_to_file (Gda.DataModelIOFormat format, string file, int cols, int nb_cols, int rows, int nb_rows, Gda.Set options) throws GLib.Error; public unowned string export_to_string (Gda.DataModelIOFormat format, int cols, int nb_cols, int rows, int nb_rows, Gda.Set options); public void freeze (); - public Gda.DataModelAccessFlags get_access_flags (); - public Gda.ValueAttribute get_attributes_at (int col, int row); + [CCode (vfunc_name = "i_get_access_flags")] + public virtual Gda.DataModelAccessFlags get_access_flags (); + [CCode (vfunc_name = "i_get_attributes_at")] + public virtual Gda.ValueAttribute get_attributes_at (int col, int row); public int get_column_index (string name); public unowned string get_column_name (int col); public unowned string get_column_title (int col); - public int get_n_columns (); - public int get_n_rows (); + [CCode (vfunc_name = "i_get_n_columns")] + public virtual int get_n_columns (); + [CCode (vfunc_name = "i_get_n_rows")] + public virtual int get_n_rows (); public int get_row_from_values (GLib.SList values, int cols_index); public unowned GLib.Value? get_typed_value_at (int col, int row, GLib.Type expected_type, bool nullok) throws GLib.Error; public unowned GLib.Value? get_value_at (int col, int row) throws GLib.Error; - [NoWrapper] - public abstract int i_append_row () throws GLib.Error; - [NoWrapper] - public abstract int i_append_values (GLib.List values) throws GLib.Error; - [NoWrapper] - public abstract unowned Gda.DataModelIter i_create_iter (); - [NoWrapper] - public abstract unowned Gda.Column i_describe_column (int col); - [NoWrapper] - public abstract int i_find_row (GLib.SList values, int cols_index); - [NoWrapper] - public abstract Gda.DataModelAccessFlags i_get_access_flags (); - [NoWrapper] - public abstract Gda.ValueAttribute i_get_attributes_at (int col, int row); - [NoWrapper] - public abstract int i_get_n_columns (); - [NoWrapper] - public abstract int i_get_n_rows (); - [NoWrapper] - public abstract bool i_get_notify (); - [NoWrapper] - public abstract GLib.Value i_get_value_at (int col, int row) throws GLib.Error; - [NoWrapper] - public abstract bool i_iter_at_row (Gda.DataModelIter iter, int row); - [NoWrapper] - public abstract bool i_iter_next (Gda.DataModelIter iter); - [NoWrapper] - public abstract bool i_iter_prev (Gda.DataModelIter iter); - [NoWrapper] - public abstract bool i_iter_set_value (Gda.DataModelIter iter, int col, GLib.Value value) throws GLib.Error; - [NoWrapper] - public abstract bool i_remove_row (int row) throws GLib.Error; - [NoWrapper] - public abstract void i_send_hint (Gda.DataModelHint hint, GLib.Value hint_value); - [NoWrapper] - public abstract void i_set_notify (bool do_notify_changes); - [NoWrapper] - public abstract bool i_set_value_at (int col, int row, GLib.Value value) throws GLib.Error; - [NoWrapper] - public abstract bool i_set_values (int row, GLib.List values) throws GLib.Error; - public bool remove_row (int row) throws GLib.Error; - public void send_hint (Gda.DataModelHint hint, GLib.Value hint_value); + [CCode (vfunc_name = "i_remove_row")] + public virtual bool remove_row (int row) throws GLib.Error; + [CCode (vfunc_name = "i_send_hint")] + public virtual void send_hint (Gda.DataModelHint hint, GLib.Value hint_value); public void set_column_name (int col, string name); public void set_column_title (int col, string title); - public bool set_value_at (int col, int row, GLib.Value value) throws GLib.Error; - public bool set_values (int row, GLib.List values) throws GLib.Error; + [CCode (vfunc_name = "i_set_value_at")] + public virtual bool set_value_at (int col, int row, GLib.Value value) throws GLib.Error; + [CCode (vfunc_name = "i_set_values")] + public virtual bool set_values (int row, GLib.List values) throws GLib.Error; public void thaw (); public signal void changed (); public signal void reset (); @@ -1537,15 +1509,12 @@ namespace Gda { } [CCode (cheader_filename = "libgda/libgda.h")] public interface Lockable : GLib.Object { - [NoWrapper] - public abstract void i_lock (); - [NoWrapper] - public abstract bool i_trylock (); - [NoWrapper] - public abstract void i_unlock (); - public void @lock (); - public bool trylock (); - public void unlock (); + [CCode (vfunc_name = "i_lock")] + public virtual void @lock (); + [CCode (vfunc_name = "i_trylock")] + public virtual bool trylock (); + [CCode (vfunc_name = "i_unlock")] + public virtual void unlock (); } [CCode (type_id = "GDA_TYPE_DSN_INFO", cheader_filename = "libgda/libgda.h")] public struct DsnInfo { diff --git a/vapi/packages/libgda-4.0/libgda-4.0.metadata b/vapi/packages/libgda-4.0/libgda-4.0.metadata index 91cd2984f4..05564e59e0 100644 --- a/vapi/packages/libgda-4.0/libgda-4.0.metadata +++ b/vapi/packages/libgda-4.0/libgda-4.0.metadata @@ -1,9 +1,33 @@ Gda cheader_filename="libgda/libgda.h" +*_i_* hidden="1" gda_connection_open_from_string.cnc_string nullable="1" gda_connection_open_from_string.auth_string nullable="1" gda_connection_open_from_dsn.auth_string nullable="1" gda_connection_statement_execute_non_select.params nullable="1" gda_connection_statement_execute_non_select.last_insert_row nullable="1" +gda_data_model_append_row virtual="1" vfunc_name="i_append_row" +gda_data_model_append_values virtual="1" vfunc_name="i_append_values" +gda_data_model_create_iter virtual="1" vfunc_name="i_create_iter" +gda_data_model_describe_column virtual="1" vfunc_name="i_describe_column" +gda_data_model_find_row virtual="1" vfunc_name="i_find_row" +gda_data_model_get_access_flags virtual="1" vfunc_name="i_get_access_flags" +gda_data_model_get_attributes_at virtual="1" vfunc_name="i_get_attributes_at" +gda_data_model_get_n_columns virtual="1" vfunc_name="i_get_n_columns" +gda_data_model_get_n_rows virtual="1" vfunc_name="i_get_n_rows" +gda_data_model_get_notify virtual="1" vfunc_name="i_get_notify" +gda_data_model_get_value_at virtual="1" vfunc_name="i_get_value_at" +gda_data_model_iter_at_row virtual="1" vfunc_name="i_iter_at_row" +gda_data_model_iter_next virtual="1" vfunc_name="i_iter_next" +gda_data_model_iter_prev virtual="1" vfunc_name="i_iter_prev" +gda_data_model_iter_set_value virtual="1" vfunc_name="i_iter_set_value" +gda_data_model_remove_row virtual="1" vfunc_name="i_remove_row" +gda_data_model_send_hint virtual="1" vfunc_name="i_send_hint" +gda_data_model_set_notify virtual="1" vfunc_name="i_set_notify" +gda_data_model_set_value_at virtual="1" vfunc_name="i_set_value_at" +gda_data_model_set_values virtual="1" vfunc_name="i_set_values" +gda_lockable_lock virtual="1" vfunc_name="i_lock" +gda_lockable_trylock virtual="1" vfunc_name="i_trylock" +gda_lockable_unlock virtual="1" vfunc_name="i_unlock" gda_data_model_import_new_xml_node name="from_xml_node" gda_sql_parser_parse_string.remain is_out="1" xmlNodePtr name="Node" namespace="Xml"
50e3118098635261c57d3e959023e0c950fa8f09
Delta Spike
add invocation for tomee-1.7.0
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/buildall.sh b/deltaspike/buildall.sh index 98fd88df1..4eab7cad8 100755 --- a/deltaspike/buildall.sh +++ b/deltaspike/buildall.sh @@ -31,6 +31,7 @@ mvn clean install -POWB2 -Dowb.version=2.0.0-SNAPSHOT -Dopenejb.owb.version=1.1. mvn clean install -PWeld -Dweld.version=1.1.10.Final | tee mvn-weld1_1_10.log mvn clean install -Ptomee-build-managed -Dtomee.version=1.6.0 -Dopenejb.version=4.6.0 -Dopenejb.owb.version=1.2.1 | tee mvn-tomee_1_6_0.log mvn clean install -Ptomee-build-managed -Dtomee.version=1.5.2 -Dopenejb.version=4.5.2 -Dopenejb.owb.version=1.1.8 | tee mvn-tomee_1_5_2.log +mvn clean install -Ptomee-build-managed -Dtomee.version=1.7.0 -Dopenejb.version=4.7.0 -Dopenejb.owb.version=1.2.6 | tee mvn-tomee_1_7_0.log mvn clean install -Pjbossas-build-managed-7 | tee mvn-jbossas_7.log
cbaaca7d5bbc93d4d5dab31dfa07c7523a7d1a38
restlet-framework-java
prevented primitive type from being returned as- models in API Declarations (https://github.com/restlet/apispark/issues/1168)--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet.ext.swagger/src/org/restlet/ext/swagger/internal/RWADefToSwaggerConverter.java b/modules/org.restlet.ext.swagger/src/org/restlet/ext/swagger/internal/RWADefToSwaggerConverter.java index 1f3e8ea715..fa1b407e47 100644 --- a/modules/org.restlet.ext.swagger/src/org/restlet/ext/swagger/internal/RWADefToSwaggerConverter.java +++ b/modules/org.restlet.ext.swagger/src/org/restlet/ext/swagger/internal/RWADefToSwaggerConverter.java @@ -251,7 +251,7 @@ public ApiDeclaration getApiDeclaration(String category, Definition def) { String model = iterator.next(); Representation repr = getRepresentationByName(model, def.getContract()); - if (repr == null) { + if (repr == null || isPrimitiveType(model)) { continue; } ModelDeclaration md = new ModelDeclaration();
a2483770055e4265683d9f7c165afb49ad9c2f95
Vala
sdl: Remove unnecessary argument to SDL.Key.get_keys
c
https://github.com/GNOME/vala/
diff --git a/vapi/sdl.vapi b/vapi/sdl.vapi index 251cfd9ac2..a965f18814 100644 --- a/vapi/sdl.vapi +++ b/vapi/sdl.vapi @@ -577,7 +577,7 @@ namespace SDL { public static void get_repeat(ref int delay, ref int interval); [CCode (cname="SDL_GetKeyState")] - public static weak uchar[] get_keys(ref int numkeys); + public static weak uchar[] get_keys(); [CCode (cname="SDL_GetModState")] public static KeyModifier get_modifiers();
bbf0610c6b4e6989d975bfcfd9e1fec60e863b34
Mylyn Reviews
Merge branch 'master' of git://git.eclipse.org/gitroot/mylyn/org.eclipse.mylyn.reviews
p
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/gerrit/org.eclipse.mylyn.gerrit.ui/META-INF/MANIFEST.MF b/gerrit/org.eclipse.mylyn.gerrit.ui/META-INF/MANIFEST.MF index ad134f7b..b3fd055e 100644 --- a/gerrit/org.eclipse.mylyn.gerrit.ui/META-INF/MANIFEST.MF +++ b/gerrit/org.eclipse.mylyn.gerrit.ui/META-INF/MANIFEST.MF @@ -30,4 +30,4 @@ Export-Package: org.eclipse.mylyn.internal.gerrit.ui;x-internal:=true, org.eclipse.mylyn.internal.reviews.ui.editors.ruler;x-internal:=true, org.eclipse.mylyn.internal.reviews.ui.operations;x-internal:=true, org.eclipse.mylyn.reviews.ui -Import-Package: org.apache.commons.io +Import-Package: org.apache.commons.io;version="1.4.0" diff --git a/tbr/org.eclipse.mylyn.reviews.tasks/feature.properties b/tbr/org.eclipse.mylyn.reviews.tasks/feature.properties index 7a0742a2..c71c5ccb 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks/feature.properties +++ b/tbr/org.eclipse.mylyn.reviews.tasks/feature.properties @@ -11,7 +11,7 @@ featureName=Task-based Reviews for Mylyn (Incubation) description=Provides Review functionality for Mylyn providerName=Eclipse Mylyn -copyright=Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology and others. All rights reserved. +copyright=Copyright (c) 2010, 2011 Research Group for Industrial Software (INSO), Vienna University of Technology and others. All rights reserved. license=\ Eclipse Foundation Software User Agreement\n\ April 14, 2010\n\
3086b191dda16c22e7a909f131296f6c060bc639
hbase
HBASE-1647 Filter-filterRow is called too often
c
https://github.com/apache/hbase
diff --git a/CHANGES.txt b/CHANGES.txt index 58065a2b05d7..564b5dce52fd 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -295,8 +295,6 @@ Release 0.20.0 - Unreleased (Tim Sell and Ryan Rawson via Stack) HBASE-1703 ICVs across /during a flush can cause multiple keys with the same TS (bad) - HBASE-1647 Filter#filterRow is called too often, filters rows it - shouldn't have (Doğacan Güney via Ryan Rawson and Stack) IMPROVEMENTS HBASE-1089 Add count of regions on filesystem to master UI; add percentage diff --git a/src/java/org/apache/hadoop/hbase/regionserver/HRegion.java b/src/java/org/apache/hadoop/hbase/regionserver/HRegion.java index 23c141b92cce..29ea7e5bfd0b 100644 --- a/src/java/org/apache/hadoop/hbase/regionserver/HRegion.java +++ b/src/java/org/apache/hadoop/hbase/regionserver/HRegion.java @@ -53,8 +53,6 @@ import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; -import org.apache.hadoop.hbase.filter.Filter; -import org.apache.hadoop.hbase.filter.RowFilterInterface; import org.apache.hadoop.hbase.io.HeapSize; import org.apache.hadoop.hbase.io.Reference.Range; import org.apache.hadoop.hbase.io.hfile.BlockCache; @@ -1683,13 +1681,8 @@ public Path getBaseDir() { class RegionScanner implements InternalScanner { private final KeyValueHeap storeHeap; private final byte [] stopRow; - private Filter filter; - private RowFilterInterface oldFilter; - private List<KeyValue> results = new ArrayList<KeyValue>(); RegionScanner(Scan scan, List<KeyValueScanner> additionalScanners) { - this.filter = scan.getFilter(); - this.oldFilter = scan.getOldFilter(); if (Bytes.equals(scan.getStopRow(), HConstants.EMPTY_END_ROW)) { this.stopRow = null; } else { @@ -1713,74 +1706,46 @@ class RegionScanner implements InternalScanner { this(scan, null); } - private void resetFilters() { - if (filter != null) { - filter.reset(); - } - if (oldFilter != null) { - oldFilter.reset(); - } - } - /** * Get the next row of results from this region. * @param results list to append results to * @return true if there are more rows, false if scanner is done */ - @Override - public boolean next(List<KeyValue> outResults) throws IOException { - results.clear(); - boolean returnResult = nextInternal(); - if (!returnResult && filter != null && filter.filterRow()) { - results.clear(); - } - outResults.addAll(results); - resetFilters(); - return returnResult; - } - - private boolean nextInternal() throws IOException { + public boolean next(List<KeyValue> results) + throws IOException { // This method should probably be reorganized a bit... has gotten messy - KeyValue kv; - byte[] currentRow = null; - boolean filterCurrentRow = false; + KeyValue kv = this.storeHeap.peek(); + if (kv == null) { + return false; + } + byte [] currentRow = kv.getRow(); + // See if we passed stopRow + if (stopRow != null && + comparator.compareRows(stopRow, 0, stopRow.length, + currentRow, 0, currentRow.length) <= 0) { + return false; + } + this.storeHeap.next(results); while(true) { kv = this.storeHeap.peek(); if (kv == null) { return false; } byte [] row = kv.getRow(); - if (filterCurrentRow && Bytes.equals(currentRow, row)) { - // filter all columns until row changes - this.storeHeap.next(results); - results.clear(); - continue; - } - // see if current row should be filtered based on row key - if ((filter != null && filter.filterRowKey(row, 0, row.length)) || - (oldFilter != null && oldFilter.filterRowKey(row, 0, row.length))) { - this.storeHeap.next(results); - results.clear(); - resetFilters(); - filterCurrentRow = true; - currentRow = row; - continue; - } if(!Bytes.equals(currentRow, row)) { - // Continue on the next row: - currentRow = row; - filterCurrentRow = false; - // See if we passed stopRow - if(stopRow != null && - comparator.compareRows(stopRow, 0, stopRow.length, - currentRow, 0, currentRow.length) <= 0) { - return false; - } - // if there are _no_ results or current row should be filtered - if (results.isEmpty() || filter != null && filter.filterRow()) { - // make sure results is empty - results.clear(); - resetFilters(); + // Next row: + + // what happens if there are _no_ results: + if (results.isEmpty()) { + // Continue on the next row: + currentRow = row; + + // But did we pass the stop row? + if (stopRow != null && + comparator.compareRows(stopRow, 0, stopRow.length, + currentRow, 0, currentRow.length) <= 0) { + return false; + } continue; } return true; diff --git a/src/java/org/apache/hadoop/hbase/regionserver/QueryMatcher.java b/src/java/org/apache/hadoop/hbase/regionserver/QueryMatcher.java index a0ba3369ba44..9e9295de9621 100644 --- a/src/java/org/apache/hadoop/hbase/regionserver/QueryMatcher.java +++ b/src/java/org/apache/hadoop/hbase/regionserver/QueryMatcher.java @@ -325,6 +325,7 @@ public void update() { public void reset() { this.deletes.reset(); this.columns.reset(); + if (this.filter != null) this.filter.reset(); } /** diff --git a/src/java/org/apache/hadoop/hbase/regionserver/ScanQueryMatcher.java b/src/java/org/apache/hadoop/hbase/regionserver/ScanQueryMatcher.java index 2ad16708e76c..cb15d317823b 100644 --- a/src/java/org/apache/hadoop/hbase/regionserver/ScanQueryMatcher.java +++ b/src/java/org/apache/hadoop/hbase/regionserver/ScanQueryMatcher.java @@ -114,6 +114,16 @@ public MatchCode match(KeyValue kv) { if (this.stickyNextRow) return MatchCode.SEEK_NEXT_ROW; + // Give the row filter a chance to do it's job. + if (filter != null && filter.filterRowKey(bytes, offset, rowLength)) { + stickyNextRow = true; // optimize to keep from calling the filter too much. + return MatchCode.SEEK_NEXT_ROW; + } else if (oldFilter != null && oldFilter.filterRowKey(bytes, offset, rowLength)) { + stickyNextRow = true; + return MatchCode.SEEK_NEXT_ROW; + } + + if (this.columns.done()) { stickyNextRow = true; return MatchCode.SEEK_NEXT_ROW; @@ -189,6 +199,16 @@ public MatchCode match(KeyValue kv) { return MatchCode.SEEK_NEXT_ROW; } + /** + * If the row was otherwise going to be included, call this to last-minute + * check. + * + * @return <code>true</code> if the row should be filtered. + */ + public boolean filterEntireRow() { + return filter == null? false: filter.filterRow(); + } + /** * Set current row * @param row @@ -203,5 +223,7 @@ public void setRow(byte [] row) { public void reset() { super.reset(); stickyNextRow = false; + if (filter != null) + filter.reset(); } } \ No newline at end of file diff --git a/src/java/org/apache/hadoop/hbase/regionserver/StoreScanner.java b/src/java/org/apache/hadoop/hbase/regionserver/StoreScanner.java index 0b39a9871afa..1c279fccca98 100644 --- a/src/java/org/apache/hadoop/hbase/regionserver/StoreScanner.java +++ b/src/java/org/apache/hadoop/hbase/regionserver/StoreScanner.java @@ -162,12 +162,20 @@ public synchronized boolean next(List<KeyValue> outResult) throws IOException { continue; case DONE: + if (matcher.filterEntireRow()) { + // nuke all results, and then return. + results.clear(); + } // copy jazz outResult.addAll(results); return true; case DONE_SCAN: + if (matcher.filterEntireRow()) { + // nuke all results, and then return. + results.clear(); + } close(); // copy jazz @@ -194,6 +202,11 @@ public synchronized boolean next(List<KeyValue> outResult) throws IOException { throw new RuntimeException("UNEXPECTED"); } } + + if (matcher.filterEntireRow()) { + // nuke all results, and then return. + results.clear(); + } if (!results.isEmpty()) { // copy jazz diff --git a/src/test/org/apache/hadoop/hbase/regionserver/TestScanner.java b/src/test/org/apache/hadoop/hbase/regionserver/TestScanner.java index d93668222296..369b504faec1 100644 --- a/src/test/org/apache/hadoop/hbase/regionserver/TestScanner.java +++ b/src/test/org/apache/hadoop/hbase/regionserver/TestScanner.java @@ -38,14 +38,6 @@ import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.Scan; -import org.apache.hadoop.hbase.filter.Filter; -import org.apache.hadoop.hbase.filter.InclusiveStopFilter; -import org.apache.hadoop.hbase.filter.InclusiveStopRowFilter; -import org.apache.hadoop.hbase.filter.PrefixFilter; -import org.apache.hadoop.hbase.filter.PrefixRowFilter; -import org.apache.hadoop.hbase.filter.RowFilterInterface; -import org.apache.hadoop.hbase.filter.WhileMatchFilter; -import org.apache.hadoop.hbase.filter.WhileMatchRowFilter; import org.apache.hadoop.hbase.io.hfile.Compression; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.Writables; @@ -117,7 +109,7 @@ public void testStopRow() throws Exception { count++; } s.close(); - assertEquals(0, count); + assertEquals(1, count); // Now do something a bit more imvolved. scan = new Scan(startrow, stoprow); scan.addFamily(HConstants.CATALOG_FAMILY); @@ -144,69 +136,6 @@ public void testStopRow() throws Exception { shutdownDfs(this.cluster); } } - - void rowPrefixFilter(Scan scan) throws IOException { - List<KeyValue> results = new ArrayList<KeyValue>(); - scan.addFamily(HConstants.CATALOG_FAMILY); - InternalScanner s = r.getScanner(scan); - boolean hasMore = true; - while (hasMore) { - hasMore = s.next(results); - for (KeyValue kv : results) { - assertEquals((byte)'a', kv.getRow()[0]); - assertEquals((byte)'b', kv.getRow()[1]); - } - results.clear(); - } - s.close(); - } - - void rowInclusiveStopFilter(Scan scan, byte[] stopRow) throws IOException { - List<KeyValue> results = new ArrayList<KeyValue>(); - scan.addFamily(HConstants.CATALOG_FAMILY); - InternalScanner s = r.getScanner(scan); - boolean hasMore = true; - while (hasMore) { - hasMore = s.next(results); - for (KeyValue kv : results) { - assertTrue(Bytes.compareTo(kv.getRow(), stopRow) <= 0); - } - results.clear(); - } - s.close(); - } - - public void testFilters() throws IOException { - try { - this.r = createNewHRegion(REGION_INFO.getTableDesc(), null, null); - addContent(this.r, HConstants.CATALOG_FAMILY); - Filter newFilter = new PrefixFilter(Bytes.toBytes("ab")); - Scan scan = new Scan(); - scan.setFilter(newFilter); - rowPrefixFilter(scan); - RowFilterInterface oldFilter = new PrefixRowFilter(Bytes.toBytes("ab")); - scan = new Scan(); - scan.setOldFilter(oldFilter); - rowPrefixFilter(scan); - - byte[] stopRow = Bytes.toBytes("bbc"); - newFilter = new WhileMatchFilter(new InclusiveStopFilter(stopRow)); - scan = new Scan(); - scan.setFilter(newFilter); - rowInclusiveStopFilter(scan, stopRow); - - oldFilter = new WhileMatchRowFilter( - new InclusiveStopRowFilter(stopRow)); - scan = new Scan(); - scan.setOldFilter(oldFilter); - rowInclusiveStopFilter(scan, stopRow); - - } finally { - this.r.close(); - this.r.getLog().closeAndDelete(); - shutdownDfs(this.cluster); - } - } /** The test! * @throws IOException @@ -387,6 +316,7 @@ private void scan(boolean validateStartcode, String serverName) String server = Bytes.toString(val); assertEquals(0, server.compareTo(serverName)); } + results.clear(); } } finally { InternalScanner s = scanner; diff --git a/src/test/org/apache/hadoop/hbase/regionserver/TestStoreScanner.java b/src/test/org/apache/hadoop/hbase/regionserver/TestStoreScanner.java index 8fb2cc18b793..6f611b1f4259 100644 --- a/src/test/org/apache/hadoop/hbase/regionserver/TestStoreScanner.java +++ b/src/test/org/apache/hadoop/hbase/regionserver/TestStoreScanner.java @@ -20,23 +20,25 @@ package org.apache.hadoop.hbase.regionserver; +import junit.framework.TestCase; +import org.apache.hadoop.hbase.KeyValue; +import org.apache.hadoop.hbase.KeyValueTestUtil; +import org.apache.hadoop.hbase.client.Scan; +import org.apache.hadoop.hbase.filter.WhileMatchFilter; +import org.apache.hadoop.hbase.filter.*; +import org.apache.hadoop.hbase.util.Bytes; + import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.NavigableSet; import java.util.TreeSet; -import junit.framework.TestCase; - -import org.apache.hadoop.hbase.KeyValue; -import org.apache.hadoop.hbase.KeyValueTestUtil; -import org.apache.hadoop.hbase.client.Scan; -import org.apache.hadoop.hbase.util.Bytes; public class TestStoreScanner extends TestCase { final byte [] CF = Bytes.toBytes("cf"); - + /** * Test utility for building a NavigableSet for scanners. * @param strCols @@ -65,9 +67,9 @@ public void testScanSameTimestamp() throws IOException { Scan scanSpec = new Scan(Bytes.toBytes("R1")); // this only uses maxVersions (default=1) and TimeRange (default=all) StoreScanner scan = - new StoreScanner(scanSpec, CF, Long.MAX_VALUE, - KeyValue.COMPARATOR, getCols("a"), - scanners); + new StoreScanner(scanSpec, CF, Long.MAX_VALUE, + KeyValue.COMPARATOR, getCols("a"), + scanners); List<KeyValue> results = new ArrayList<KeyValue>(); assertEquals(true, scan.next(results)); @@ -96,9 +98,9 @@ public void testWontNextToNext() throws IOException { Scan scanSpec = new Scan(Bytes.toBytes("R1")); // this only uses maxVersions (default=1) and TimeRange (default=all) StoreScanner scan = - new StoreScanner(scanSpec, CF, Long.MAX_VALUE, - KeyValue.COMPARATOR, getCols("a"), - scanners); + new StoreScanner(scanSpec, CF, Long.MAX_VALUE, + KeyValue.COMPARATOR, getCols("a"), + scanners); List<KeyValue> results = new ArrayList<KeyValue>(); scan.next(results); @@ -128,8 +130,8 @@ public void testDeleteVersionSameTimestamp() throws IOException { }; Scan scanSpec = new Scan(Bytes.toBytes("R1")); StoreScanner scan = - new StoreScanner(scanSpec, CF, Long.MAX_VALUE, KeyValue.COMPARATOR, - getCols("a"), scanners); + new StoreScanner(scanSpec, CF, Long.MAX_VALUE, KeyValue.COMPARATOR, + getCols("a"), scanners); List<KeyValue> results = new ArrayList<KeyValue>(); assertFalse(scan.next(results)); @@ -151,9 +153,9 @@ public void testDeletedRowThenGoodRow() throws IOException { }; Scan scanSpec = new Scan(Bytes.toBytes("R1")); StoreScanner scan = - new StoreScanner(scanSpec, CF, Long.MAX_VALUE, KeyValue.COMPARATOR, - getCols("a"), scanners); - + new StoreScanner(scanSpec, CF, Long.MAX_VALUE, KeyValue.COMPARATOR, + getCols("a"), scanners); + List<KeyValue> results = new ArrayList<KeyValue>(); assertEquals(true, scan.next(results)); assertEquals(0, results.size()); @@ -181,8 +183,8 @@ public void testDeleteVersionMaskingMultiplePuts() throws IOException { new KeyValueScanFixture(KeyValue.COMPARATOR, kvs2) }; StoreScanner scan = - new StoreScanner(new Scan(Bytes.toBytes("R1")), CF, Long.MAX_VALUE, KeyValue.COMPARATOR, - getCols("a"), scanners); + new StoreScanner(new Scan(Bytes.toBytes("R1")), CF, Long.MAX_VALUE, KeyValue.COMPARATOR, + getCols("a"), scanners); List<KeyValue> results = new ArrayList<KeyValue>(); // the two put at ts=now will be masked by the 1 delete, and // since the scan default returns 1 version we'll return the newest @@ -209,8 +211,8 @@ public void testDeleteVersionsMixedAndMultipleVersionReturn() throws IOException }; Scan scanSpec = new Scan(Bytes.toBytes("R1")).setMaxVersions(2); StoreScanner scan = - new StoreScanner(scanSpec, CF, Long.MAX_VALUE, KeyValue.COMPARATOR, - getCols("a"), scanners); + new StoreScanner(scanSpec, CF, Long.MAX_VALUE, KeyValue.COMPARATOR, + getCols("a"), scanners); List<KeyValue> results = new ArrayList<KeyValue>(); assertEquals(true, scan.next(results)); assertEquals(2, results.size()); @@ -219,17 +221,17 @@ public void testDeleteVersionsMixedAndMultipleVersionReturn() throws IOException } public void testWildCardOneVersionScan() throws IOException { - KeyValue [] kvs = new KeyValue [] { - KeyValueTestUtil.create("R1", "cf", "a", 2, KeyValue.Type.Put, "dont-care"), - KeyValueTestUtil.create("R1", "cf", "b", 1, KeyValue.Type.Put, "dont-care"), - KeyValueTestUtil.create("R1", "cf", "a", 1, KeyValue.Type.DeleteColumn, "dont-care"), - }; + KeyValue [] kvs = new KeyValue [] { + KeyValueTestUtil.create("R1", "cf", "a", 2, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R1", "cf", "b", 1, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R1", "cf", "a", 1, KeyValue.Type.DeleteColumn, "dont-care"), + }; KeyValueScanner [] scanners = new KeyValueScanner[] { new KeyValueScanFixture(KeyValue.COMPARATOR, kvs) }; StoreScanner scan = - new StoreScanner(new Scan(Bytes.toBytes("R1")), CF, Long.MAX_VALUE, KeyValue.COMPARATOR, - null, scanners); + new StoreScanner(new Scan(Bytes.toBytes("R1")), CF, Long.MAX_VALUE, KeyValue.COMPARATOR, + null, scanners); List<KeyValue> results = new ArrayList<KeyValue>(); assertEquals(true, scan.next(results)); assertEquals(2, results.size()); @@ -259,8 +261,8 @@ public void testWildCardScannerUnderDeletes() throws IOException { new KeyValueScanFixture(KeyValue.COMPARATOR, kvs) }; StoreScanner scan = - new StoreScanner(new Scan().setMaxVersions(2), CF, Long.MAX_VALUE, KeyValue.COMPARATOR, - null, scanners); + new StoreScanner(new Scan().setMaxVersions(2), CF, Long.MAX_VALUE, KeyValue.COMPARATOR, + null, scanners); List<KeyValue> results = new ArrayList<KeyValue>(); assertEquals(true, scan.next(results)); assertEquals(5, results.size()); @@ -289,8 +291,8 @@ public void testDeleteFamily() throws IOException { new KeyValueScanFixture(KeyValue.COMPARATOR, kvs) }; StoreScanner scan = - new StoreScanner(new Scan().setMaxVersions(Integer.MAX_VALUE), CF, Long.MAX_VALUE, KeyValue.COMPARATOR, - null, scanners); + new StoreScanner(new Scan().setMaxVersions(Integer.MAX_VALUE), CF, Long.MAX_VALUE, KeyValue.COMPARATOR, + null, scanners); List<KeyValue> results = new ArrayList<KeyValue>(); assertEquals(true, scan.next(results)); assertEquals(0, results.size()); @@ -312,8 +314,8 @@ public void testDeleteColumn() throws IOException { new KeyValueScanFixture(KeyValue.COMPARATOR, kvs), }; StoreScanner scan = - new StoreScanner(new Scan(), CF, Long.MAX_VALUE, KeyValue.COMPARATOR, - null, scanners); + new StoreScanner(new Scan(), CF, Long.MAX_VALUE, KeyValue.COMPARATOR, + null, scanners); List<KeyValue> results = new ArrayList<KeyValue>(); assertEquals(true, scan.next(results)); assertEquals(1, results.size()); @@ -337,9 +339,9 @@ public void testSkipColumn() throws IOException { new KeyValueScanFixture(KeyValue.COMPARATOR, kvs) }; StoreScanner scan = - new StoreScanner(new Scan(), CF, Long.MAX_VALUE, KeyValue.COMPARATOR, - getCols("a", "d"), scanners); - + new StoreScanner(new Scan(), CF, Long.MAX_VALUE, KeyValue.COMPARATOR, + getCols("a", "d"), scanners); + List<KeyValue> results = new ArrayList<KeyValue>(); assertEquals(true, scan.next(results)); assertEquals(2, results.size()); @@ -350,8 +352,156 @@ public void testSkipColumn() throws IOException { assertEquals(true, scan.next(results)); assertEquals(1, results.size()); assertEquals(kvs[kvs.length-1], results.get(0)); - + results.clear(); assertEquals(false, scan.next(results)); } + + KeyValue [] stdKvs = new KeyValue[] { + KeyValueTestUtil.create("R:1", "cf", "a", 11, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R:1", "cf", "b", 11, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R:1", "cf", "c", 11, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R:1", "cf", "d", 11, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R:1", "cf", "e", 11, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R:1", "cf", "f", 11, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R:1", "cf", "g", 11, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R:1", "cf", "h", 11, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R:1", "cf", "i", 11, KeyValue.Type.Put, "dont-care"), + + // 9... + KeyValueTestUtil.create("R:2", "cf", "a", 11, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R:2", "cf", "c", 11, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R:2", "cf", "c", 10, KeyValue.Type.Put, "dont-care"), + + // 12... + KeyValueTestUtil.create("R:3", "cf", "a", 11, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R:3", "cf", "c", 11, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R:3", "cf", "c", 10, KeyValue.Type.Put, "dont-care"), + + // 15 ... + KeyValueTestUtil.create("R:4", "cf", "a", 11, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R:4", "cf", "c", 11, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R:4", "cf", "c", 10, KeyValue.Type.Put, "dont-care"), + + // 18 .. + KeyValueTestUtil.create("R:5", "cf", "a", 11, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R:5", "cf", "c", 11, KeyValue.Type.Put, "dont-care"), + + // 20... + KeyValueTestUtil.create("R:6", "cf", "a", 11, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R:6", "cf", "c", 11, KeyValue.Type.Put, "dont-care"), + + // 22... + KeyValueTestUtil.create("R:7", "cf", "a", 11, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R:7", "cf", "c", 11, KeyValue.Type.Put, "dont-care"), + + // 24... + KeyValueTestUtil.create("R:8", "cf", "a", 11, KeyValue.Type.Put, "dont-care"), + KeyValueTestUtil.create("R:8", "cf", "c", 11, KeyValue.Type.Put, "dont-care"), + + // 26 .. + KeyValueTestUtil.create("RA:1", "cf", "a", 11, KeyValue.Type.Put, "dont-care"), + + // 27... + KeyValueTestUtil.create("RA:2", "cf", "a", 11, KeyValue.Type.Put, "dont-care"), + + // 28.. + KeyValueTestUtil.create("RA:3", "cf", "a", 11, KeyValue.Type.Put, "dont-care"), + }; + private StoreScanner getTestScanner(Scan s, NavigableSet<byte[]> cols) { + KeyValueScanner [] scanners = new KeyValueScanner[] { + new KeyValueScanFixture(KeyValue.COMPARATOR, stdKvs) + }; + + return new StoreScanner(s, CF, Long.MAX_VALUE, KeyValue.COMPARATOR, cols, + scanners); + } + + + // Test new and old row prefix filters. + public void testNewRowPrefixFilter() throws IOException { + Filter f = new WhileMatchFilter( + new PrefixFilter(Bytes.toBytes("R:"))); + Scan s = new Scan(Bytes.toBytes("R:7")); + s.setFilter(f); + + rowPrefixFilter(s); + } + + public void testOldRowPrefixFilter() throws IOException { + RowFilterInterface f = new WhileMatchRowFilter( + new PrefixRowFilter(Bytes.toBytes("R:"))); + Scan s = new Scan(Bytes.toBytes("R:7")); + s.setOldFilter(f); + + rowPrefixFilter(s); + + } + public void rowPrefixFilter(Scan s) throws IOException { + + StoreScanner scan = getTestScanner(s, null); + + List<KeyValue> results = new ArrayList<KeyValue>(); + assertTrue(scan.next(results)); + assertEquals(2, results.size()); + assertEquals(stdKvs[22], results.get(0)); + assertEquals(stdKvs[23], results.get(1)); + results.clear(); + + assertTrue(scan.next(results)); + assertEquals(2, results.size()); + assertEquals(stdKvs[24], results.get(0)); + assertEquals(stdKvs[25], results.get(1)); + results.clear(); + + assertFalse(scan.next(results)); + assertEquals(0, results.size()); + } + + // Test new and old row-inclusive stop filter. + public void testNewRowInclusiveStopFilter() throws IOException { + Filter f = new WhileMatchFilter(new InclusiveStopFilter(Bytes.toBytes("R:3"))); + Scan scan = new Scan(); + scan.setFilter(f); + + rowInclusiveStopFilter(scan); + } + + public void testOldRowInclusiveTopFilter() throws IOException { + RowFilterInterface f = new WhileMatchRowFilter( + new InclusiveStopRowFilter(Bytes.toBytes("R:3"))); + Scan scan = new Scan(); + scan.setOldFilter(f); + + rowInclusiveStopFilter(scan); + } + + public void rowInclusiveStopFilter(Scan scan) throws IOException { + StoreScanner s = getTestScanner(scan, getCols("a")); + + // read crap. + List<KeyValue> results = new ArrayList<KeyValue>(); + assertTrue(s.next(results)); + assertEquals(1, results.size()); + assertEquals(stdKvs[0], results.get(0)); + results.clear(); + + assertTrue(s.next(results)); + assertEquals(1, results.size()); + assertEquals(stdKvs[9], results.get(0)); + results.clear(); + + assertTrue(s.next(results)); + assertEquals(1, results.size()); + assertEquals(stdKvs[12], results.get(0)); + results.clear(); + + // without aggressive peeking, the scanner doesnt know if the next row is good or not + // under the affects of a filter. + assertFalse(s.next(results)); + assertEquals(0, results.size()); + } + + + }
d31b4a666d45a7c37bc2d1677c09a28070a5acaf
coremedia$jangaroo-tools
extracted Ide.usageInExpr() from Ide.analyzeAsExpr() which is just the functionality needed in Catch to analyze the type clause [git-p4: depot-paths = "//coremedia/jangaroo/": change = 179440]
p
https://github.com/coremedia/jangaroo-tools
diff --git a/jangaroo-core/jangaroo-compiler/src/main/java/net/jangaroo/jooc/Catch.java b/jangaroo-core/jangaroo-compiler/src/main/java/net/jangaroo/jooc/Catch.java index 71252fe93..33885243a 100644 --- a/jangaroo-core/jangaroo-compiler/src/main/java/net/jangaroo/jooc/Catch.java +++ b/jangaroo-core/jangaroo-compiler/src/main/java/net/jangaroo/jooc/Catch.java @@ -118,7 +118,7 @@ public AstNode analyze(AstNode parentNode, AnalyzeContext context) { Type type = typeRelation.getType(); if (type instanceof IdeType) { IdeType ideType = (IdeType) type; - ideType.getIde().addExternalUsage(); + ideType.getIde().usageInExpr(ideType); } } block.analyze(this, context); diff --git a/jangaroo-core/jangaroo-compiler/src/main/java/net/jangaroo/jooc/Ide.java b/jangaroo-core/jangaroo-compiler/src/main/java/net/jangaroo/jooc/Ide.java index 669c60eb3..e53e0eb46 100644 --- a/jangaroo-core/jangaroo-compiler/src/main/java/net/jangaroo/jooc/Ide.java +++ b/jangaroo-core/jangaroo-compiler/src/main/java/net/jangaroo/jooc/Ide.java @@ -229,20 +229,23 @@ public void analyzeAsExpr(AstNode exprParent, Expr parentExpr, final AnalyzeCont } } if (scope != null) { - addExternalUsage(); - //todo handle references to static super members - // check access to another class or a constant of another class; other class then must be initialized: - if (!isQualifier() && !(exprParent instanceof ApplyExpr)) { - ClassDeclaration classDeclaration = getScope().getClassDeclaration(); - if (classDeclaration != null) { - if (isQualified()) { - // access to constant of other class - classDeclaration.addInitIfClass(getQualifier()); - } else { - // access to other class - classDeclaration.addInitIfClass(this); - } + usageInExpr(exprParent); + } + } + + public void usageInExpr(final AstNode exprParent) { + addExternalUsage(); + //todo handle references to static super members + // check access to another class or a constant of another class; other class then must be initialized: + if (!isQualifier() && !(exprParent instanceof ApplyExpr)) { + ClassDeclaration classDeclaration = getScope().getClassDeclaration(); + if (classDeclaration != null) { + if (isQualified()) { + // access to constant of other class? + classDeclaration.addInitIfClass(getQualifier()); } + // access to other class? + classDeclaration.addInitIfClass(this); } } }
2ec270d61805f97d9e2b61f336040c3413b1d7e0
epfldata$squall
Added more flexibility in positioning an operator inside a chain of operators in Component and StormComponent classes. An order in which user specifies the operators will be respected.
p
https://github.com/epfldata/squall
diff --git a/src/squall/src/optimizers/SimpleOpt.java b/src/squall/src/optimizers/SimpleOpt.java index c2b1cee0..0241c662 100755 --- a/src/squall/src/optimizers/SimpleOpt.java +++ b/src/squall/src/optimizers/SimpleOpt.java @@ -16,8 +16,8 @@ import net.sf.jsqlparser.statement.select.Join; import net.sf.jsqlparser.statement.select.SelectItem; import operators.AggregateOperator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ProjectOperator; +import operators.SelectOperator; import predicates.Predicate; import schema.Schema; import util.ParserUtil; @@ -53,6 +53,8 @@ public ComponentGenerator generate(List<Table> tableList, List<Join> joinList, L processSelectClause(selectItems); processWhereClause(whereExpr); + ParserUtil.orderOperators(_cg.getQueryPlan()); + ParallelismAssigner parAssign = new ParallelismAssigner(_cg.getQueryPlan(), _tan, _schema, _map); parAssign.assignPar(); @@ -98,8 +100,8 @@ private int processSelectClause(List<SelectItem> selectItems) { private void attachSelectClause(List<AggregateOperator> aggOps, List<ValueExpression> selectVEs, Component affectedComponent) { if (aggOps.isEmpty()){ - ProjectionOperator project = new ProjectionOperator(selectVEs); - affectedComponent.setProjection(project); + ProjectOperator project = new ProjectOperator(selectVEs); + affectedComponent.addOperator(project); }else if (aggOps.size() == 1){ //all the others are group by AggregateOperator firstAgg = aggOps.get(0); @@ -116,10 +118,10 @@ private void attachSelectClause(List<AggregateOperator> aggOps, List<ValueExpres affectedComponent.setHashIndexes(groupByColumns); OperatorComponent newComponent = new OperatorComponent(affectedComponent, ParserUtil.generateUniqueName("OPERATOR"), - _cg.getQueryPlan()).setAggregation(firstAgg); + _cg.getQueryPlan()).addOperator(firstAgg); }else{ - affectedComponent.setAggregation(firstAgg); + affectedComponent.addOperator(firstAgg); } }else{ //Sometimes selectExpr contains other functions, so we have to use projections instead of simple groupBy @@ -132,11 +134,11 @@ private void attachSelectClause(List<AggregateOperator> aggOps, List<ValueExpres affectedComponent.setHashExpressions((List<ValueExpression>)DeepCopy.copy(selectVEs)); //always new level - ProjectionOperator groupByProj = new ProjectionOperator((List<ValueExpression>)DeepCopy.copy(selectVEs)); + ProjectOperator groupByProj = new ProjectOperator((List<ValueExpression>)DeepCopy.copy(selectVEs)); firstAgg.setGroupByProjection(groupByProj); OperatorComponent newComponent = new OperatorComponent(affectedComponent, ParserUtil.generateUniqueName("OPERATOR"), - _cg.getQueryPlan()).setAggregation(firstAgg); + _cg.getQueryPlan()).addOperator(firstAgg); } }else{ @@ -158,7 +160,7 @@ private void processWhereClause(Expression whereExpr) { } private void attachWhereClause(Predicate predicate, Component affectedComponent) { - affectedComponent.setSelection(new SelectionOperator(predicate)); + affectedComponent.addOperator(new SelectOperator(predicate)); } } diff --git a/src/squall/src/optimizers/ruleBased/EarlyProjection.java b/src/squall/src/optimizers/ruleBased/EarlyProjection.java index 33f74d06..57e73359 100644 --- a/src/squall/src/optimizers/ruleBased/EarlyProjection.java +++ b/src/squall/src/optimizers/ruleBased/EarlyProjection.java @@ -14,7 +14,7 @@ import java.util.HashMap; import java.util.List; import operators.AggregateOperator; -import operators.ProjectionOperator; +import operators.ProjectOperator; import queryPlans.QueryPlan; import util.ParserUtil; import visitors.squall.ColumnRefCollectVisitor; @@ -68,8 +68,8 @@ private void bottomUp(Component component, List<Integer> inheritedUsed, int leve afterProjIndexes = sortElimDuplicates(afterProjIndexes); //set projection as if parent do not change - ProjectionOperator projection = new ProjectionOperator(ParserUtil.listToArr(afterProjIndexes)); - component.setProjection(projection); + ProjectOperator projection = new ProjectOperator(ParserUtil.listToArr(afterProjIndexes)); + component.addOperator(projection); //projection changed, everybody after it should notice that updateColumnRefs(afterProjColRefs, afterProjIndexes); @@ -111,7 +111,7 @@ private List<Integer> getDirectlyUsedIndexes(Component component){ if(hashIndexes != null){ result.addAll(hashIndexes); } - AggregateOperator agg = component.getAggregation(); + AggregateOperator agg = component.getChainOperator().getAggregation(); if(agg!=null){ List<Integer> groupBy = agg.getGroupByColumns(); if(groupBy != null){ @@ -216,7 +216,7 @@ private void updateIndexes(Component component, List<Integer> filteredIndexList) List<Integer> newHashIndexes = elemsBefore(oldHashIndexes, filteredIndexList); component.setHashIndexes(newHashIndexes); } - AggregateOperator agg = component.getAggregation(); + AggregateOperator agg = component.getChainOperator().getAggregation(); if(agg!=null){ List<Integer> oldGroupBy = agg.getGroupByColumns(); if(oldGroupBy != null && !oldGroupBy.isEmpty()){ @@ -294,7 +294,7 @@ private void topDown(){ updateColumnRefs(beforeProjColRefs, fromParents); //update Projection indexes - List<ValueExpression> projVE = comp.getProjection().getExpressions(); + List<ValueExpression> projVE = comp.getChainOperator().getProjection().getExpressions(); List<ColumnReference> projColRefs = extractColumnRefFromVEs(projVE); //after bottom-up: projection will be set, so it will contain all the necessary fields, @@ -331,7 +331,7 @@ private List<Integer> arrivedFromParents(CompPackage cp){ private List<Integer> extractProjIndexesAfterBottomUp(Component comp){ if(comp instanceof DataSourceComponent){ - return ParserUtil.extractColumnIndexes(comp.getProjection().getExpressions()); + return ParserUtil.extractColumnIndexes(comp.getChainOperator().getProjection().getExpressions()); }else{ return _compOldProj.get(comp); } diff --git a/src/squall/src/optimizers/ruleBased/RuleBasedOpt.java b/src/squall/src/optimizers/ruleBased/RuleBasedOpt.java index 93c0546d..29787590 100644 --- a/src/squall/src/optimizers/ruleBased/RuleBasedOpt.java +++ b/src/squall/src/optimizers/ruleBased/RuleBasedOpt.java @@ -23,8 +23,8 @@ import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.statement.select.SelectItem; import operators.AggregateOperator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ProjectOperator; +import operators.SelectOperator; import optimizers.ComponentGenerator; import optimizers.Optimizer; import optimizers.OptimizerTranslator; @@ -40,7 +40,11 @@ import visitors.squall.SelectItemsVisitor; import visitors.squall.WhereVisitor; - +/* + * Does not take relation cardinalities into account. + * Assume no projections before the aggregation, so that EarlyProjection may impose some projections. + * Aggregation only on the last level. + */ public class RuleBasedOpt implements Optimizer { private Schema _schema; private String _dataPath; @@ -75,6 +79,8 @@ public ComponentGenerator generate(List<Table> tableList, List<Join> joinList, L earlyProjection(_cg.getQueryPlan()); } + ParserUtil.orderOperators(_cg.getQueryPlan()); + ParallelismAssigner parAssign = new ParallelismAssigner(_cg.getQueryPlan(), _tan, _schema, _map); parAssign.assignPar(); @@ -210,8 +216,8 @@ private int processSelectClause(List<SelectItem> selectItems) { private void attachSelectClause(List<AggregateOperator> aggOps, List<ValueExpression> selectVEs, Component affectedComponent) { if (aggOps.isEmpty()){ - ProjectionOperator project = new ProjectionOperator(selectVEs); - affectedComponent.setProjection(project); + ProjectOperator project = new ProjectOperator(selectVEs); + affectedComponent.addOperator(project); }else if (aggOps.size() == 1){ //all the others are group by AggregateOperator firstAgg = aggOps.get(0); @@ -228,10 +234,10 @@ private void attachSelectClause(List<AggregateOperator> aggOps, List<ValueExpres affectedComponent.setHashIndexes(groupByColumns); OperatorComponent newComponent = new OperatorComponent(affectedComponent, ParserUtil.generateUniqueName("OPERATOR"), - _cg.getQueryPlan()).setAggregation(firstAgg); + _cg.getQueryPlan()).addOperator(firstAgg); }else{ - affectedComponent.setAggregation(firstAgg); + affectedComponent.addOperator(firstAgg); } }else{ //Sometimes selectExpr contains other functions, so we have to use projections instead of simple groupBy @@ -244,11 +250,11 @@ private void attachSelectClause(List<AggregateOperator> aggOps, List<ValueExpres affectedComponent.setHashExpressions((List<ValueExpression>)DeepCopy.copy(selectVEs)); //always new level - ProjectionOperator groupByProj = new ProjectionOperator((List<ValueExpression>)DeepCopy.copy(selectVEs)); + ProjectOperator groupByProj = new ProjectOperator((List<ValueExpression>)DeepCopy.copy(selectVEs)); firstAgg.setGroupByProjection(groupByProj); OperatorComponent newComponent = new OperatorComponent(affectedComponent, ParserUtil.generateUniqueName("OPERATOR"), - _cg.getQueryPlan()).setAggregation(firstAgg); + _cg.getQueryPlan()).addOperator(firstAgg); } }else{ @@ -306,7 +312,7 @@ private void processWhereForComponent(Expression whereExpression, Component affe } private void attachWhereClause(Predicate predicate, Component affectedComponent) { - affectedComponent.setSelection(new SelectionOperator(predicate)); + affectedComponent.addOperator(new SelectOperator(predicate)); } //HELPER diff --git a/src/squall/src/optimizers/ruleBased/RuleTranslator.java b/src/squall/src/optimizers/ruleBased/RuleTranslator.java index ad647251..291b247e 100644 --- a/src/squall/src/optimizers/ruleBased/RuleTranslator.java +++ b/src/squall/src/optimizers/ruleBased/RuleTranslator.java @@ -43,7 +43,7 @@ public int getChildIndex(int originalIndex, Component originator, Component requ Component child = originator.getChild(); Component[] parents = child.getParents(); - if(child.getProjection()!=null){ + if(child.getChainOperator().getProjection()!=null){ throw new RuntimeException("Cannot use getChildIndex method on the component with Projection! getOutputSize does not work anymore!"); } diff --git a/src/squall/src/util/ParserUtil.java b/src/squall/src/util/ParserUtil.java index 72cddc02..63a6e3f7 100755 --- a/src/squall/src/util/ParserUtil.java +++ b/src/squall/src/util/ParserUtil.java @@ -16,6 +16,8 @@ import java.util.List; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.select.Join; +import operators.ChainOperator; +import operators.Operator; import queryPlans.QueryPlan; import utilities.MyUtilities; @@ -77,18 +79,7 @@ public static void printQueryPlan(QueryPlan queryPlan) { for(Component comp: queryPlan.getPlan()){ sb.append("\n\nComponent ").append(comp.getName()); - if(comp.getSelection()!=null){ - sb.append("\n").append(comp.getSelection().toString()); - } - if(comp.getProjection()!=null){ - sb.append("\n").append(comp.getProjection().toString()); - } - if(comp.getDistinct()!=null){ - sb.append("\n").append(comp.getDistinct().toString()); - } - if(comp.getAggregation()!=null){ - sb.append("\n").append(comp.getAggregation().toString()); - } + sb.append("\n").append(comp.getChainOperator()); if(comp.getHashIndexes()!=null && !comp.getHashIndexes().isEmpty()){ sb.append("\n HashIndexes: ").append(listToStr(comp.getHashIndexes())); } @@ -223,4 +214,33 @@ public static String readStringFromFile(String sqlPath) { } return sqlstring.toString(); } + + /* + * On each component order the Operators as Select, Distinct, Project, Aggregation + */ + public static void orderOperators(QueryPlan queryPlan) { + List<Component> comps = queryPlan.getPlan(); + for(Component comp: comps){ + ChainOperator chain = comp.getChainOperator(); + chain.setOperators(orderOperators(chain)); + } + } + + private static List<Operator> orderOperators(ChainOperator chain) { + List<Operator> result = new ArrayList<Operator>(); + + Operator selection = chain.getSelection(); + if (selection!=null) result.add(selection); + + Operator distinct = chain.getDistinct(); + if (distinct!=null) result.add(distinct); + + Operator projection = chain.getProjection(); + if (projection!=null) result.add(projection); + + Operator agg = chain.getAggregation(); + if (agg!=null) result.add(agg); + + return result; + } } \ No newline at end of file diff --git a/src/squall/src/visitors/squall/VECollectVisitor.java b/src/squall/src/visitors/squall/VECollectVisitor.java index 55d108fb..b7ea7988 100755 --- a/src/squall/src/visitors/squall/VECollectVisitor.java +++ b/src/squall/src/visitors/squall/VECollectVisitor.java @@ -11,15 +11,17 @@ import java.util.List; import operators.AggregateOperator; import operators.DistinctOperator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.Operator; +import operators.ProjectOperator; +import operators.SelectOperator; import predicates.Predicate; +import visitors.OperatorVisitor; /* * Collects all the VE inside a component. * Lists refering to VE appearing after and before projection are necessary only for rule-based optimization. */ -public class VECollectVisitor { +public class VECollectVisitor implements OperatorVisitor { private List<ValueExpression> _veList = new ArrayList<ValueExpression>(); private List<ValueExpression> _afterProjection = new ArrayList<ValueExpression>(); private List<ValueExpression> _beforeProjection = new ArrayList<ValueExpression>(); @@ -43,25 +45,14 @@ public void visit(Component component) { _veList.addAll(hashExpressions); } - SelectionOperator selection = component.getSelection(); - if(selection!=null){ - visit(selection); - } - ProjectionOperator projection = component.getProjection(); - if(projection!=null){ - visit(projection); - } - DistinctOperator distinct = component.getDistinct(); - if(distinct!=null){ - visit(distinct); - } - AggregateOperator aggregation = component.getAggregation(); - if(aggregation!=null){ - visit(aggregation); + List<Operator> operators = component.getChainOperator().getOperators(); + for(Operator op: operators){ + visit(op); } } - public void visit(SelectionOperator selection){ + @Override + public void visit(SelectOperator selection){ Predicate predicate = selection.getPredicate(); VECollectPredVisitor vecpv = new VECollectPredVisitor(); predicate.accept(vecpv); @@ -69,21 +60,8 @@ public void visit(SelectionOperator selection){ _veList.addAll(vecpv.getExpressions()); } - private void visitNested(ProjectionOperator projection) { - if(projection!=null){ - _afterProjection.addAll(projection.getExpressions()); - _veList.addAll(projection.getExpressions()); - } - } - - private void visitNested(DistinctOperator distinct) { - ProjectionOperator project = distinct.getProjection(); - if(project!=null){ - visitNested(project); - } - } - //TODO: this should be only in the last component + @Override public void visit(AggregateOperator aggregation) { if(aggregation!=null){ DistinctOperator distinct = aggregation.getDistinct(); @@ -101,13 +79,51 @@ public void visit(AggregateOperator aggregation) { //unsupported //because we assing by ourselves to projection - public void visit(ProjectionOperator projection){ + @Override + public void visit(ProjectOperator projection){ //TODO ignored because of topDown - makes no harm } //because it changes the output of the component + @Override public void visit(DistinctOperator distinct){ throw new RuntimeException("EarlyProjection cannon work if in bottom-up phase encounter Distinct!"); } + + @Override + public void visit(Operator op){ + //List<Operator> is visited, thus we have to do conversion to the specific type + //TODO: alternative is to use methods such as + // visit(Operator operator, Class SelectOperator.class), but this is also not very nice + if (op instanceof SelectOperator){ + SelectOperator selection = (SelectOperator) op; + visit(selection); + }else if(op instanceof DistinctOperator){ + DistinctOperator distinct = (DistinctOperator) op; + visit(distinct); + }else if(op instanceof ProjectOperator){ + ProjectOperator projection = (ProjectOperator) op; + visit(projection); + }else if(op instanceof AggregateOperator){ + AggregateOperator agg = (AggregateOperator) op; + visit(agg); + }else{ + throw new RuntimeException("Should not be here in operator!"); + } + } + + private void visitNested(ProjectOperator projection) { + if(projection!=null){ + _afterProjection.addAll(projection.getExpressions()); + _veList.addAll(projection.getExpressions()); + } + } + + private void visitNested(DistinctOperator distinct) { + ProjectOperator project = distinct.getProjection(); + if(project!=null){ + visitNested(project); + } + } } \ No newline at end of file diff --git a/src/squall/src/visitors/squall/WhereVisitor.java b/src/squall/src/visitors/squall/WhereVisitor.java index 7726847d..16c92e39 100755 --- a/src/squall/src/visitors/squall/WhereVisitor.java +++ b/src/squall/src/visitors/squall/WhereVisitor.java @@ -62,7 +62,6 @@ import net.sf.jsqlparser.expression.operators.relational.NotEqualsTo; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.statement.select.SubSelect; -import operators.SelectionOperator; import optimizers.OptimizerTranslator; import predicates.AndPredicate; import predicates.ComparisonPredicate; diff --git a/src/squall_plan_runner/src/components/Component.java b/src/squall_plan_runner/src/components/Component.java index 418d8505..f40396af 100755 --- a/src/squall_plan_runner/src/components/Component.java +++ b/src/squall_plan_runner/src/components/Component.java @@ -11,9 +11,11 @@ import java.io.Serializable; import java.util.List; import operators.AggregateOperator; +import operators.ChainOperator; import operators.DistinctOperator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.Operator; +import operators.ProjectOperator; +import operators.SelectOperator; import stormComponents.StormEmitter; import stormComponents.synchronization.TopologyKiller; @@ -42,15 +44,8 @@ public void makeBolts(TopologyBuilder builder, public Component setHashExpressions(List<ValueExpression> hashExpressions); public List<ValueExpression> getHashExpressions(); - public Component setSelection(SelectionOperator selection); - public SelectionOperator getSelection(); - public Component setDistinct(DistinctOperator distinct); - public DistinctOperator getDistinct(); - public Component setProjection(ProjectionOperator projection); - public ProjectionOperator getProjection(); - public Component setAggregation(AggregateOperator aggregation); - public AggregateOperator getAggregation(); - + public Component addOperator(Operator operator); //add to the end of ChainOperator + public ChainOperator getChainOperator(); //contains all the previously added operators // methods necessary for query plan processing public Component[] getParents(); diff --git a/src/squall_plan_runner/src/components/DataSourceComponent.java b/src/squall_plan_runner/src/components/DataSourceComponent.java index 5a367e0d..d71544c5 100755 --- a/src/squall_plan_runner/src/components/DataSourceComponent.java +++ b/src/squall_plan_runner/src/components/DataSourceComponent.java @@ -11,9 +11,11 @@ import java.util.ArrayList; import java.util.List; import operators.AggregateOperator; +import operators.ChainOperator; import operators.DistinctOperator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.Operator; +import operators.ProjectOperator; +import operators.SelectOperator; import stormComponents.StormDataSource; import stormComponents.synchronization.TopologyKiller; import org.apache.log4j.Logger; @@ -38,10 +40,7 @@ public class DataSourceComponent implements Component { private List<ColumnNameType> _tableSchema; private StormDataSource _dataSource; - private SelectionOperator _selection; - private ProjectionOperator _projection; - private DistinctOperator _distinct; - private AggregateOperator _aggregation; + private ChainOperator _chain = new ChainOperator(); private boolean _printOut; private boolean _printOutSet; // whether printOut condition is already set @@ -82,50 +81,16 @@ public DataSourceComponent setHashExpressions(List<ValueExpression> hashExpressi } @Override - public DataSourceComponent setSelection(SelectionOperator selection){ - _selection=selection; + public DataSourceComponent addOperator(Operator operator){ + _chain.addOperator(operator); return this; } @Override - public DataSourceComponent setDistinct(DistinctOperator distinct) { - _distinct = distinct; - return this; - } - - @Override - public DataSourceComponent setProjection(ProjectionOperator projection){ - _projection=projection; - return this; - } - - @Override - public DataSourceComponent setAggregation(AggregateOperator aggregation) { - _aggregation = aggregation; - return this; - } - - @Override - public SelectionOperator getSelection() { - return _selection; - } - - @Override - public DistinctOperator getDistinct() { - return _distinct; + public ChainOperator getChainOperator(){ + return _chain; } - @Override - public ProjectionOperator getProjection() { - return _projection; - } - - @Override - public AggregateOperator getAggregation() { - return _aggregation; - } - - @Override public DataSourceComponent setPrintOut(boolean printOut){ _printOutSet = true; @@ -154,11 +119,11 @@ public void makeBolts(TopologyBuilder builder, } int parallelism = SystemParameters.getInt(conf, _componentName+"_PAR"); - if(parallelism > 1 && _distinct != null){ + if(parallelism > 1 && _chain.getDistinct() != null){ throw new RuntimeException(_componentName + ": Distinct operator cannot be specified for multiple spouts for one input file!"); } - MyUtilities.checkBatchOutput(_batchOutputMillis, _aggregation, conf); + MyUtilities.checkBatchOutput(_batchOutputMillis, _chain.getAggregation(), conf); _dataSource = new StormDataSource( _componentName, @@ -166,10 +131,7 @@ public void makeBolts(TopologyBuilder builder, _inputPath, _hashIndexes, _hashExpressions, - _selection, - _distinct, - _projection, - _aggregation, + _chain, hierarchyPosition, _printOut, _batchOutputMillis, diff --git a/src/squall_plan_runner/src/components/EquiJoinComponent.java b/src/squall_plan_runner/src/components/EquiJoinComponent.java index bdadc6b0..d4305261 100644 --- a/src/squall_plan_runner/src/components/EquiJoinComponent.java +++ b/src/squall_plan_runner/src/components/EquiJoinComponent.java @@ -11,9 +11,11 @@ import java.util.ArrayList; import java.util.List; import operators.AggregateOperator; +import operators.ChainOperator; import operators.DistinctOperator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.Operator; +import operators.ProjectOperator; +import operators.SelectOperator; import stormComponents.StormDstJoin; import stormComponents.StormJoin; import stormComponents.StormSrcJoin; @@ -41,14 +43,11 @@ public class EquiJoinComponent implements Component { private StormJoin _joiner; - private SelectionOperator _selection; - private DistinctOperator _distinct; - private ProjectionOperator _projection; - private AggregateOperator _aggregation; + private ChainOperator _chain = new ChainOperator(); //preAggregation private SquallStorage _firstPreAggStorage, _secondPreAggStorage; - private ProjectionOperator _firstPreAggProj, _secondPreAggProj; + private ProjectOperator _firstPreAggProj, _secondPreAggProj; private boolean _printOut; private boolean _printOutSet; //whether printOut was already set @@ -93,28 +92,16 @@ public EquiJoinComponent setHashExpressions(List<ValueExpression> hashExpression } @Override - public EquiJoinComponent setSelection(SelectionOperator selection){ - _selection = selection; + public EquiJoinComponent addOperator(Operator operator){ + _chain.addOperator(operator); return this; } @Override - public EquiJoinComponent setDistinct(DistinctOperator distinct){ - _distinct = distinct; - return this; - } - - @Override - public EquiJoinComponent setProjection(ProjectionOperator projection){ - _projection = projection; - return this; + public ChainOperator getChainOperator(){ + return _chain; } - @Override - public EquiJoinComponent setAggregation(AggregateOperator aggregation){ - _aggregation = aggregation; - return this; - } //next four methods are for Preaggregation public EquiJoinComponent setFirstPreAggStorage(SquallStorage firstPreAggStorage){ @@ -128,37 +115,17 @@ public EquiJoinComponent setSecondPreAggStorage(SquallStorage secondPreAggStorag } //Out of the first storage (join of S tuple with R relation) - public EquiJoinComponent setFirstPreAggProj(ProjectionOperator firstPreAggProj){ + public EquiJoinComponent setFirstPreAggProj(ProjectOperator firstPreAggProj){ _firstPreAggProj = firstPreAggProj; return this; } //Out of the second storage (join of R tuple with S relation) - public EquiJoinComponent setSecondPreAggProj(ProjectionOperator secondPreAggProj){ + public EquiJoinComponent setSecondPreAggProj(ProjectOperator secondPreAggProj){ _secondPreAggProj = secondPreAggProj; return this; } - @Override - public SelectionOperator getSelection() { - return _selection; - } - - @Override - public DistinctOperator getDistinct() { - return _distinct; - } - - @Override - public ProjectionOperator getProjection() { - return _projection; - } - - @Override - public AggregateOperator getAggregation() { - return _aggregation; - } - @Override public EquiJoinComponent setPrintOut(boolean printOut){ _printOutSet = true; @@ -186,7 +153,7 @@ public void makeBolts(TopologyBuilder builder, setPrintOut(true); } - MyUtilities.checkBatchOutput(_batchOutputMillis, _aggregation, conf); + MyUtilities.checkBatchOutput(_batchOutputMillis, _chain.getAggregation(), conf); if(partitioningType == StormJoin.DST_ORDERING){ //In Preaggregation one or two storages can be set; otherwise no storage is set @@ -201,10 +168,7 @@ public void makeBolts(TopologyBuilder builder, _secondParent, _componentName, allCompNames, - _selection, - _distinct, - _projection, - _aggregation, + _chain, _firstPreAggStorage, _secondPreAggStorage, _firstPreAggProj, @@ -220,7 +184,7 @@ public void makeBolts(TopologyBuilder builder, conf); }else if(partitioningType == StormJoin.SRC_ORDERING){ - if(_distinct!=null){ + if(_chain.getDistinct()!=null){ throw new RuntimeException("Cannot instantiate Distinct operator from StormSourceJoin! There are two Bolts processing operators!"); } //In Preaggregation one or two storages can be set; otherwise no storage is set @@ -237,9 +201,7 @@ public void makeBolts(TopologyBuilder builder, _secondParent, _componentName, allCompNames, - _selection, - _projection, - _aggregation, + _chain, _firstPreAggStorage, _secondPreAggStorage, _firstPreAggProj, diff --git a/src/squall_plan_runner/src/components/OperatorComponent.java b/src/squall_plan_runner/src/components/OperatorComponent.java index 78ddf7b3..230d55b8 100755 --- a/src/squall_plan_runner/src/components/OperatorComponent.java +++ b/src/squall_plan_runner/src/components/OperatorComponent.java @@ -10,10 +10,8 @@ import expressions.ValueExpression; import java.util.ArrayList; import java.util.List; -import operators.AggregateOperator; -import operators.DistinctOperator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ChainOperator; +import operators.Operator; import stormComponents.synchronization.TopologyKiller; import org.apache.log4j.Logger; @@ -38,10 +36,7 @@ public class OperatorComponent implements Component{ private List<Integer> _hashIndexes; private List<ValueExpression> _hashExpressions; - private SelectionOperator _selection; - private DistinctOperator _distinct; - private ProjectionOperator _projection; - private AggregateOperator _aggregation; + private ChainOperator _chain = new ChainOperator(); private boolean _printOut; private boolean _printOutSet; @@ -87,49 +82,17 @@ public OperatorComponent setHashExpressions(List<ValueExpression> hashExpression return this; } - @Override - public OperatorComponent setSelection(SelectionOperator selection){ - _selection = selection; - return this; - } - - @Override - public OperatorComponent setDistinct(DistinctOperator distinct){ - _distinct = distinct; + @Override + public OperatorComponent addOperator(Operator operator){ + _chain.addOperator(operator); return this; } @Override - public OperatorComponent setProjection(ProjectionOperator projection){ - _projection = projection; - return this; + public ChainOperator getChainOperator(){ + return _chain; } - @Override - public OperatorComponent setAggregation(AggregateOperator aggregation){ - _aggregation = aggregation; - return this; - } - - @Override - public SelectionOperator getSelection() { - return _selection; - } - - @Override - public DistinctOperator getDistinct() { - return _distinct; - } - - @Override - public ProjectionOperator getProjection() { - return _projection; - } - - @Override - public AggregateOperator getAggregation() { - return _aggregation; - } @Override public OperatorComponent setPrintOut(boolean printOut){ @@ -158,15 +121,12 @@ public void makeBolts(TopologyBuilder builder, setPrintOut(true); } - MyUtilities.checkBatchOutput(_batchOutputMillis, _aggregation, conf); + MyUtilities.checkBatchOutput(_batchOutputMillis, _chain.getAggregation(), conf); _stormOperator = new StormOperator(_parent, _componentName, allCompNames, - _selection, - _distinct, - _projection, - _aggregation, + _chain, _hashIndexes, _hashExpressions, hierarchyPosition, diff --git a/src/squall_plan_runner/src/components/ThetaJoinComponent.java b/src/squall_plan_runner/src/components/ThetaJoinComponent.java index 694a5292..5609a585 100644 --- a/src/squall_plan_runner/src/components/ThetaJoinComponent.java +++ b/src/squall_plan_runner/src/components/ThetaJoinComponent.java @@ -10,10 +10,8 @@ import expressions.ValueExpression; import java.util.ArrayList; import java.util.List; -import operators.AggregateOperator; -import operators.DistinctOperator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ChainOperator; +import operators.Operator; import stormComponents.StormThetaJoin; import stormComponents.synchronization.TopologyKiller; import org.apache.log4j.Logger; @@ -40,10 +38,7 @@ public class ThetaJoinComponent implements Component { private StormThetaJoin _joiner; - private SelectionOperator _selection; - private DistinctOperator _distinct; - private ProjectionOperator _projection; - private AggregateOperator _aggregation; + private ChainOperator _chain = new ChainOperator(); private boolean _printOut; private boolean _printOutSet; //whether printOut was already set @@ -96,48 +91,16 @@ public ThetaJoinComponent setHashExpressions(List<ValueExpression> hashExpressio } @Override - public ThetaJoinComponent setSelection(SelectionOperator selection){ - _selection = selection; + public ThetaJoinComponent addOperator(Operator operator){ + _chain.addOperator(operator); return this; } @Override - public ThetaJoinComponent setDistinct(DistinctOperator distinct){ - _distinct = distinct; - return this; - } - - @Override - public ThetaJoinComponent setProjection(ProjectionOperator projection){ - _projection = projection; - return this; - } - - @Override - public ThetaJoinComponent setAggregation(AggregateOperator aggregation){ - _aggregation = aggregation; - return this; - } - - @Override - public SelectionOperator getSelection() { - return _selection; - } - - @Override - public DistinctOperator getDistinct() { - return _distinct; + public ChainOperator getChainOperator(){ + return _chain; } - @Override - public ProjectionOperator getProjection() { - return _projection; - } - - @Override - public AggregateOperator getAggregation() { - return _aggregation; - } @Override public ThetaJoinComponent setPrintOut(boolean printOut){ @@ -166,16 +129,13 @@ public void makeBolts(TopologyBuilder builder, setPrintOut(true); } - MyUtilities.checkBatchOutput(_batchOutputMillis, _aggregation, conf); + MyUtilities.checkBatchOutput(_batchOutputMillis, _chain.getAggregation(), conf); _joiner = new StormThetaJoin(_firstParent, _secondParent, _componentName, allCompNames, - _selection, - _distinct, - _projection, - _aggregation, + _chain, _hashIndexes, _hashExpressions, _joinPredicate, diff --git a/src/squall_plan_runner/src/operators/AggregateAvgOperator.java b/src/squall_plan_runner/src/operators/AggregateAvgOperator.java index 510e458b..be51bcd5 100755 --- a/src/squall_plan_runner/src/operators/AggregateAvgOperator.java +++ b/src/squall_plan_runner/src/operators/AggregateAvgOperator.java @@ -30,7 +30,7 @@ public class AggregateAvgOperator implements AggregateOperator<SumCount> { private DistinctOperator _distinct; private int _groupByType = GB_UNSET; private List<Integer> _groupByColumns = new ArrayList<Integer>(); - private ProjectionOperator _groupByProjection; + private ProjectOperator _groupByProjection; private int _numTuplesProcessed = 0; private NumericConversion<Double> _wrapper = new DoubleConversion(); @@ -60,7 +60,7 @@ public AggregateAvgOperator setGroupByColumns(List<Integer> groupByColumns) { } @Override - public AggregateAvgOperator setGroupByProjection(ProjectionOperator groupByProjection){ + public AggregateAvgOperator setGroupByProjection(ProjectOperator groupByProjection){ if(!alreadySetOther(GB_PROJECTION)){ _groupByType = GB_PROJECTION; _groupByProjection = groupByProjection; @@ -83,7 +83,7 @@ public List<Integer> getGroupByColumns() { } @Override - public ProjectionOperator getGroupByProjection(){ + public ProjectOperator getGroupByProjection(){ return _groupByProjection; } diff --git a/src/squall_plan_runner/src/operators/AggregateCountOperator.java b/src/squall_plan_runner/src/operators/AggregateCountOperator.java index dac46750..c7ef31a8 100755 --- a/src/squall_plan_runner/src/operators/AggregateCountOperator.java +++ b/src/squall_plan_runner/src/operators/AggregateCountOperator.java @@ -30,7 +30,7 @@ public class AggregateCountOperator implements AggregateOperator<Integer>{ private DistinctOperator _distinct; private int _groupByType = GB_UNSET; private List<Integer> _groupByColumns = new ArrayList<Integer>(); - private ProjectionOperator _groupByProjection; + private ProjectOperator _groupByProjection; private int _numTuplesProcessed = 0; private NumericConversion<Integer> _wrapper = new IntegerConversion(); @@ -58,7 +58,7 @@ public AggregateCountOperator setGroupByColumns(List<Integer> groupByColumns) { } @Override - public AggregateCountOperator setGroupByProjection(ProjectionOperator groupByProjection){ + public AggregateCountOperator setGroupByProjection(ProjectOperator groupByProjection){ if(!alreadySetOther(GB_PROJECTION)){ _groupByType = GB_PROJECTION; _groupByProjection = groupByProjection; @@ -81,7 +81,7 @@ public List<Integer> getGroupByColumns() { } @Override - public ProjectionOperator getGroupByProjection(){ + public ProjectOperator getGroupByProjection(){ return _groupByProjection; } diff --git a/src/squall_plan_runner/src/operators/AggregateOperator.java b/src/squall_plan_runner/src/operators/AggregateOperator.java index 899ce5f7..aebf95ac 100755 --- a/src/squall_plan_runner/src/operators/AggregateOperator.java +++ b/src/squall_plan_runner/src/operators/AggregateOperator.java @@ -14,8 +14,8 @@ public interface AggregateOperator<T> extends Operator{ // GROUP BY ValueExpression is not part of the SQL standard, only columns can be sed. public AggregateOperator setGroupByColumns(List<Integer> groupByColumns); public List<Integer> getGroupByColumns(); - public AggregateOperator setGroupByProjection(ProjectionOperator projection); - public ProjectionOperator getGroupByProjection(); + public AggregateOperator setGroupByProjection(ProjectOperator projection); + public ProjectOperator getGroupByProjection(); //SUM(DISTINCT ValueExpression), COUNT(DISTINCT ValueExpression): a single ValueExpression by SQL standard // MySQL supports multiple ValueExpression. Inside aggregation(SUM, COUNT), there must be single ValueExpression. diff --git a/src/squall_plan_runner/src/operators/AggregateSumOperator.java b/src/squall_plan_runner/src/operators/AggregateSumOperator.java index 657a6968..89009b3b 100755 --- a/src/squall_plan_runner/src/operators/AggregateSumOperator.java +++ b/src/squall_plan_runner/src/operators/AggregateSumOperator.java @@ -25,7 +25,7 @@ public class AggregateSumOperator<T extends Number & Comparable<T>> implements A private DistinctOperator _distinct; private int _groupByType = GB_UNSET; private List<Integer> _groupByColumns = new ArrayList<Integer>(); - private ProjectionOperator _groupByProjection; + private ProjectOperator _groupByProjection; private int _numTuplesProcessed = 0; private NumericConversion<T> _wrapper; @@ -56,7 +56,7 @@ public AggregateSumOperator<T> setGroupByColumns(List<Integer> groupByColumns) { } @Override - public AggregateSumOperator setGroupByProjection(ProjectionOperator groupByProjection) { + public AggregateSumOperator setGroupByProjection(ProjectOperator groupByProjection) { if(!alreadySetOther(GB_PROJECTION)){ _groupByType = GB_PROJECTION; _groupByProjection = groupByProjection; @@ -79,7 +79,7 @@ public List<Integer> getGroupByColumns() { } @Override - public ProjectionOperator getGroupByProjection() { + public ProjectOperator getGroupByProjection() { return _groupByProjection; } diff --git a/src/squall_plan_runner/src/operators/ChainOperator.java b/src/squall_plan_runner/src/operators/ChainOperator.java index 54de2f93..27519c2a 100755 --- a/src/squall_plan_runner/src/operators/ChainOperator.java +++ b/src/squall_plan_runner/src/operators/ChainOperator.java @@ -24,7 +24,87 @@ public ChainOperator(Operator... opArray){ public ChainOperator(List<Operator> operators){ _operators = operators; } + + //we can creat an empty chainOperator and later fill it in + public ChainOperator(){ + + } + + /* + * Delete the previously added operators and add new list of operators + */ + public void setOperators(List<Operator> operators){ + _operators = operators; + } + + /* + * Add an operator to the tail + */ + public void addOperator(Operator operator){ + _operators.add(operator); + } + + public List<Operator> getOperators(){ + return _operators; + } + + public Operator getLastOperator(){ + if(size()>0){ + return _operators.get(size()-1); + }else{ + return null; + } + } + + //****************************************************** + /* + * return first appearance of SelectOperator + * used when ordering operators in Simple and rule-based optimizer + */ + public SelectOperator getSelection(){ + for(Operator op:_operators){ + if (op instanceof SelectOperator) return (SelectOperator) op; + } + return null; + } + + /* + * return first appearance of DistinctOperator + * used when ordering operators in Simple and rule-based optimizer + */ + public DistinctOperator getDistinct(){ + for(Operator op:_operators){ + if (op instanceof DistinctOperator) return (DistinctOperator) op; + } + return null; + } + + /* + * return first appearance of ProjectOperator + * used when ordering operators in Simple and rule-based optimizer + * used in rule-based optimizer + */ + public ProjectOperator getProjection(){ + for(Operator op:_operators){ + if (op instanceof ProjectOperator) return (ProjectOperator) op; + } + return null; + } + + /* + * return first appearance of AggregationOperator + * used when ordering operators in Simple and rule-based optimizer + * used in rule-based optimizer + */ + public AggregateOperator getAggregation(){ + for(Operator op:_operators){ + if (op instanceof AggregateOperator) return (AggregateOperator) op; + } + return null; + } + //****************************************************** + /* Return tuple if the tuple has to be sent further * Otherwise return null. */ @@ -50,21 +130,25 @@ public boolean isBlocking() { } @Override - public String printContent() { - String result = null; + public int getNumTuplesProcessed(){ if(isBlocking()){ - result = getLastOperator().printContent(); + return getLastOperator().getNumTuplesProcessed(); + }else{ + throw new RuntimeException("tuplesProcessed for non-blocking last operator should never be invoked!"); } - return result; + } + + private int size(){ + return _operators.size(); } @Override - public int getNumTuplesProcessed(){ + public String printContent() { + String result = null; if(isBlocking()){ - return getLastOperator().getNumTuplesProcessed(); - }else{ - throw new RuntimeException("tuplesProcessed for non-blocking last operator should never be invoked!"); + result = getLastOperator().printContent(); } + return result; } @Override @@ -76,16 +160,14 @@ public List<String> getContent() { return result; } - public Operator getLastOperator(){ - if(size()>0){ - return _operators.get(size()-1); - }else{ - return null; + @Override + public String toString(){ + StringBuilder sb = new StringBuilder(); + sb.append("ChainOperator contains the following operators(in this order):\n"); + for(Operator op:_operators){ + sb.append(op).append("\n"); } - } - - private int size(){ - return _operators.size(); + return sb.toString(); } } \ No newline at end of file diff --git a/src/squall_plan_runner/src/operators/DistinctOperator.java b/src/squall_plan_runner/src/operators/DistinctOperator.java index 95173ce2..3607b056 100755 --- a/src/squall_plan_runner/src/operators/DistinctOperator.java +++ b/src/squall_plan_runner/src/operators/DistinctOperator.java @@ -14,7 +14,7 @@ public class DistinctOperator implements Operator { private Map _conf; private int _numTuplesProcessed; - private ProjectionOperator _projection; + private ProjectOperator _projection; private static final long serialVersionUID = 1L; private SquallStorage _storage = new SquallStorage(); /* Dummy value to associate with a tuple in the backing Storage (Since @@ -22,21 +22,21 @@ public class DistinctOperator implements Operator { private static final String dummyString = new String("dummy"); public DistinctOperator(Map conf, ValueExpression ... veArray){ - _projection = new ProjectionOperator(veArray); + _projection = new ProjectOperator(veArray); _conf = conf; } public DistinctOperator(Map conf, List<ValueExpression> veList){ - _projection = new ProjectionOperator(veList); + _projection = new ProjectOperator(veList); _conf = conf; } public DistinctOperator(Map conf, int[] projectionIndexes){ - _projection = new ProjectionOperator(projectionIndexes); + _projection = new ProjectOperator(projectionIndexes); _conf = conf; } - public ProjectionOperator getProjection(){ + public ProjectOperator getProjection(){ return _projection; } diff --git a/src/squall_plan_runner/src/operators/MultiAggregateOperator.java b/src/squall_plan_runner/src/operators/MultiAggregateOperator.java index 1f26920b..5d2c5b6b 100644 --- a/src/squall_plan_runner/src/operators/MultiAggregateOperator.java +++ b/src/squall_plan_runner/src/operators/MultiAggregateOperator.java @@ -49,7 +49,7 @@ private int getNumGroupByColumns(AggregateOperator agg){ if(groupByColumns != null){ result += groupByColumns.size(); } - ProjectionOperator groupByProjection = agg.getGroupByProjection(); + ProjectOperator groupByProjection = agg.getGroupByProjection(); if(groupByProjection != null){ result += groupByProjection.getExpressions().size(); } @@ -98,12 +98,12 @@ public List getGroupByColumns() { } @Override - public AggregateOperator setGroupByProjection(ProjectionOperator projection) { + public AggregateOperator setGroupByProjection(ProjectOperator projection) { throw new UnsupportedOperationException("You are not supposed to call this method from MultiAggregateOperator."); } @Override - public ProjectionOperator getGroupByProjection() { + public ProjectOperator getGroupByProjection() { throw new UnsupportedOperationException("You are not supposed to call this method from MultiAggregateOperator."); } diff --git a/src/squall_plan_runner/src/operators/ProjectOperator.java b/src/squall_plan_runner/src/operators/ProjectOperator.java new file mode 100644 index 00000000..e0b68bd8 --- /dev/null +++ b/src/squall_plan_runner/src/operators/ProjectOperator.java @@ -0,0 +1,80 @@ +package operators; +import conversion.StringConversion; +import expressions.ColumnReference; +import expressions.ValueExpression; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class ProjectOperator implements Operator { + private static final long serialVersionUID = 1L; + + private List<ValueExpression> _veList = new ArrayList<ValueExpression>(); + + private int _numTuplesProcessed = 0; + + public ProjectOperator(ValueExpression... veArray){ + _veList.addAll(Arrays.asList(veArray)); + } + + public ProjectOperator(List<ValueExpression> veList){ + _veList = veList; + } + + public ProjectOperator(int[] projectIndexes){ + for(int columnNumber: projectIndexes){ + ColumnReference columnReference = new ColumnReference(new StringConversion(), columnNumber); + _veList.add(columnReference); + } + } + + public List<ValueExpression> getExpressions(){ + return _veList; + } + + @Override + public List<String> process(List<String> tuple) { + _numTuplesProcessed++; + List<String> projection = new ArrayList<String>(); + for(ValueExpression ve: _veList){ + String columnContent = ve.evalString(tuple); + projection.add(columnContent); + } + return projection; + } + + @Override + public boolean isBlocking() { + return false; + } + + @Override + public String printContent() { + throw new RuntimeException("printContent for ProjectionOperator should never be invoked!"); + } + + @Override + public int getNumTuplesProcessed(){ + return _numTuplesProcessed; + } + + @Override + public List<String> getContent() { + throw new RuntimeException("getContent for ProjectionOperator should never be invoked!"); + } + + @Override + public String toString(){ + StringBuilder sb = new StringBuilder(); + sb.append(" ProjectionOperator ("); + for(int i=0; i<_veList.size();i++){ + sb.append(_veList.get(i).toString()); + if(i==_veList.size()-1){ + sb.append(")"); + }else{ + sb.append(", "); + } + } + return sb.toString(); + } +} \ No newline at end of file diff --git a/src/squall_plan_runner/src/operators/SelectOperator.java b/src/squall_plan_runner/src/operators/SelectOperator.java new file mode 100644 index 00000000..4e41181a --- /dev/null +++ b/src/squall_plan_runner/src/operators/SelectOperator.java @@ -0,0 +1,63 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package operators; + +import java.util.List; +import predicates.Predicate; + +public class SelectOperator implements Operator { + private static final long serialVersionUID = 1L; + + private Predicate _predicate; + + private int _numTuplesProcessed=0; + + public SelectOperator(Predicate predicate){ + _predicate = predicate; + } + + public Predicate getPredicate(){ + return _predicate; + } + + @Override + public List<String> process(List<String> tuple) { + _numTuplesProcessed++; + if (_predicate.test(tuple)){ + return tuple; + }else{ + return null; + } + } + + @Override + public boolean isBlocking() { + return false; + } + + @Override + public String printContent() { + throw new RuntimeException("printContent for SelectionOperator should never be invoked!"); + } + + @Override + public int getNumTuplesProcessed(){ + return _numTuplesProcessed; + } + + @Override + public List<String> getContent() { + throw new RuntimeException("getContent for SelectionOperator should never be invoked!"); + } + + @Override + public String toString(){ + StringBuilder sb = new StringBuilder(); + sb.append("SelectionOperator with Predicate: "); + sb.append(_predicate.toString()); + return sb.toString(); + } +} diff --git a/src/squall_plan_runner/src/queryPlans/HyracksPlan.java b/src/squall_plan_runner/src/queryPlans/HyracksPlan.java index 9ac039d7..5f5677c1 100755 --- a/src/squall_plan_runner/src/queryPlans/HyracksPlan.java +++ b/src/squall_plan_runner/src/queryPlans/HyracksPlan.java @@ -15,7 +15,7 @@ import operators.AggregateCountOperator; import operators.AggregateOperator; import operators.AggregateSumOperator; -import operators.ProjectionOperator; +import operators.ProjectOperator; import org.apache.log4j.Logger; import schema.TPCH_Schema; @@ -30,23 +30,23 @@ public class HyracksPlan { public HyracksPlan(String dataPath, String extension, Map conf){ //------------------------------------------------------------------------------------- // start of query plan filling - ProjectionOperator projectionCustomer = new ProjectionOperator(new int[]{0, 6}); + ProjectOperator projectionCustomer = new ProjectOperator(new int[]{0, 6}); List<Integer> hashCustomer = Arrays.asList(0); DataSourceComponent relationCustomer = new DataSourceComponent( "CUSTOMER", dataPath + "customer" + extension, TPCH_Schema.customer, - _queryPlan).setProjection(projectionCustomer) + _queryPlan).addOperator(projectionCustomer) .setHashIndexes(hashCustomer); //------------------------------------------------------------------------------------- - ProjectionOperator projectionOrders = new ProjectionOperator(new int[]{1}); + ProjectOperator projectionOrders = new ProjectOperator(new int[]{1}); List<Integer> hashOrders = Arrays.asList(0); DataSourceComponent relationOrders = new DataSourceComponent( "ORDERS", dataPath + "orders" + extension, TPCH_Schema.orders, - _queryPlan).setProjection(projectionOrders) + _queryPlan).addOperator(projectionOrders) .setHashIndexes(hashOrders); //------------------------------------------------------------------------------------- @@ -56,7 +56,7 @@ public HyracksPlan(String dataPath, String extension, Map conf){ EquiJoinComponent CUSTOMER_ORDERSjoin = new EquiJoinComponent( relationCustomer, relationOrders, - _queryPlan).setAggregation(agg); + _queryPlan).addOperator(agg); //------------------------------------------------------------------------------------- diff --git a/src/squall_plan_runner/src/queryPlans/HyracksPreAggPlan.java b/src/squall_plan_runner/src/queryPlans/HyracksPreAggPlan.java index fc7d6b87..bc8f3325 100755 --- a/src/squall_plan_runner/src/queryPlans/HyracksPreAggPlan.java +++ b/src/squall_plan_runner/src/queryPlans/HyracksPreAggPlan.java @@ -17,7 +17,7 @@ import java.util.Map; import operators.AggregateOperator; import operators.AggregateSumOperator; -import operators.ProjectionOperator; +import operators.ProjectOperator; import org.apache.log4j.Logger; import schema.TPCH_Schema; @@ -34,30 +34,30 @@ public class HyracksPreAggPlan { public HyracksPreAggPlan(String dataPath, String extension, Map conf){ //------------------------------------------------------------------------------------- // start of query plan filling - ProjectionOperator projectionCustomer = new ProjectionOperator(new int[]{0, 6}); + ProjectOperator projectionCustomer = new ProjectOperator(new int[]{0, 6}); List<Integer> hashCustomer = Arrays.asList(0); DataSourceComponent relationCustomer = new DataSourceComponent( "CUSTOMER", dataPath + "customer" + extension, TPCH_Schema.customer, - _queryPlan).setProjection(projectionCustomer) - .setHashIndexes(hashCustomer); + _queryPlan).addOperator(projectionCustomer) + .setHashIndexes(hashCustomer); //------------------------------------------------------------------------------------- - ProjectionOperator projectionOrders = new ProjectionOperator(new int[]{1}); + ProjectOperator projectionOrders = new ProjectOperator(new int[]{1}); List<Integer> hashOrders = Arrays.asList(0); DataSourceComponent relationOrders = new DataSourceComponent( "ORDERS", dataPath + "orders" + extension, TPCH_Schema.orders, - _queryPlan).setProjection(projectionOrders) - .setHashIndexes(hashOrders); + _queryPlan).addOperator(projectionOrders) + .setHashIndexes(hashOrders); //------------------------------------------------------------------------------------- - ProjectionOperator projFirstOut = new ProjectionOperator( + ProjectOperator projFirstOut = new ProjectOperator( new ColumnReference(_sc, 1), new ValueSpecification(_sc, "1")); - ProjectionOperator projSecondOut = new ProjectionOperator(new int[]{1, 2}); + ProjectOperator projSecondOut = new ProjectOperator(new int[]{1, 2}); // FIXME FIXME FIXME: This should be as below, but there is an incombatibility with SquallStorage // Replace with wrong SquallStorage instantiation, but will be fixed eventually // JoinAggStorage secondJoinStorage = new JoinAggStorage(new AggregateCountOperator(conf), conf); @@ -68,16 +68,16 @@ public HyracksPreAggPlan(String dataPath, String extension, Map conf){ relationCustomer, relationOrders, _queryPlan).setFirstPreAggProj(projFirstOut) - .setSecondPreAggProj(projSecondOut) - .setSecondPreAggStorage(secondJoinStorage) - .setHashIndexes(hashIndexes); + .setSecondPreAggProj(projSecondOut) + .setSecondPreAggStorage(secondJoinStorage) + .setHashIndexes(hashIndexes); //------------------------------------------------------------------------------------- AggregateSumOperator agg = new AggregateSumOperator(_dc, new ColumnReference(_dc, 1), conf) .setGroupByColumns(Arrays.asList(0)); OperatorComponent oc = new OperatorComponent(CUSTOMER_ORDERSjoin, "COUNTAGG", _queryPlan) - .setAggregation(agg); + .addOperator(agg); //------------------------------------------------------------------------------------- diff --git a/src/squall_plan_runner/src/queryPlans/RSTPlan.java b/src/squall_plan_runner/src/queryPlans/RSTPlan.java index 0f1021da..8b669a6f 100755 --- a/src/squall_plan_runner/src/queryPlans/RSTPlan.java +++ b/src/squall_plan_runner/src/queryPlans/RSTPlan.java @@ -19,7 +19,7 @@ import java.util.Map; import operators.AggregateOperator; import operators.AggregateSumOperator; -import operators.SelectionOperator; +import operators.SelectOperator; import org.apache.log4j.Logger; import predicates.ComparisonPredicate; @@ -81,13 +81,12 @@ public RSTPlan(String dataPath, String extension, Map conf){ EquiJoinComponent R_S_Tjoin= new EquiJoinComponent( R_Sjoin, relationT, - _queryPlan).setAggregation(sp) - .setSelection( - new SelectionOperator( + _queryPlan).addOperator( + new SelectOperator( new ComparisonPredicate( new ColumnReference(_ic, 1), - new ValueSpecification(_ic, 10)))); - + new ValueSpecification(_ic, 10)))) + .addOperator(sp); //------------------------------------------------------------------------------------- AggregateOperator overallAgg = diff --git a/src/squall_plan_runner/src/queryPlans/TPCH10Plan.java b/src/squall_plan_runner/src/queryPlans/TPCH10Plan.java index f40d2e27..549826d7 100644 --- a/src/squall_plan_runner/src/queryPlans/TPCH10Plan.java +++ b/src/squall_plan_runner/src/queryPlans/TPCH10Plan.java @@ -9,7 +9,6 @@ import components.EquiJoinComponent; import conversion.DateConversion; import conversion.DoubleConversion; -import conversion.IntegerConversion; import conversion.NumericConversion; import conversion.StringConversion; import conversion.TypeConversion; @@ -26,8 +25,8 @@ import java.util.Map; import operators.AggregateOperator; import operators.AggregateSumOperator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ProjectOperator; +import operators.SelectOperator; import org.apache.log4j.Logger; import predicates.BetweenPredicate; import predicates.ComparisonPredicate; @@ -37,7 +36,6 @@ public class TPCH10Plan { private static final TypeConversion<Date> _dc = new DateConversion(); private static final NumericConversion<Double> _doubleConv = new DoubleConversion(); - private static final IntegerConversion _ic = new IntegerConversion(); private static final StringConversion _sc = new StringConversion(); private QueryPlan _queryPlan = new QueryPlan(); @@ -67,34 +65,34 @@ public TPCH10Plan(String dataPath, String extension, Map conf){ //------------------------------------------------------------------------------------- List<Integer> hashCustomer = Arrays.asList(0); - ProjectionOperator projectionCustomer = new ProjectionOperator(new int[]{0, 1, 2, 3, 4, 5, 7}); + ProjectOperator projectionCustomer = new ProjectOperator(new int[]{0, 1, 2, 3, 4, 5, 7}); DataSourceComponent relationCustomer = new DataSourceComponent( "CUSTOMER", dataPath + "customer" + extension, TPCH_Schema.customer, _queryPlan).setHashIndexes(hashCustomer) - .setProjection(projectionCustomer); + .addOperator(projectionCustomer); //------------------------------------------------------------------------------------- List<Integer> hashOrders = Arrays.asList(1); - SelectionOperator selectionOrders = new SelectionOperator( + SelectOperator selectionOrders = new SelectOperator( new BetweenPredicate( new ColumnReference(_dc, 4), true, new ValueSpecification(_dc, _date1), false, new ValueSpecification(_dc, _date2) )); - ProjectionOperator projectionOrders = new ProjectionOperator(new int[]{0, 1}); + ProjectOperator projectionOrders = new ProjectOperator(new int[]{0, 1}); DataSourceComponent relationOrders = new DataSourceComponent( "ORDERS", dataPath + "orders" + extension, TPCH_Schema.orders, _queryPlan).setHashIndexes(hashOrders) - .setSelection(selectionOrders) - .setProjection(projectionOrders); + .addOperator(selectionOrders) + .addOperator(projectionOrders); //------------------------------------------------------------------------------------- EquiJoinComponent C_Ojoin = new EquiJoinComponent( @@ -104,40 +102,40 @@ false, new ValueSpecification(_dc, _date2) //------------------------------------------------------------------------------------- List<Integer> hashNation = Arrays.asList(0); - ProjectionOperator projectionNation = new ProjectionOperator(new int[]{0, 1}); + ProjectOperator projectionNation = new ProjectOperator(new int[]{0, 1}); DataSourceComponent relationNation = new DataSourceComponent( "NATION", dataPath + "nation" + extension, TPCH_Schema.nation, _queryPlan).setHashIndexes(hashNation) - .setProjection(projectionNation); + .addOperator(projectionNation); //------------------------------------------------------------------------------------- EquiJoinComponent C_O_Njoin = new EquiJoinComponent( C_Ojoin, relationNation, - _queryPlan).setProjection(new ProjectionOperator(new int[]{0, 1, 2, 4, 5, 6, 7, 8})) + _queryPlan).addOperator(new ProjectOperator(new int[]{0, 1, 2, 4, 5, 6, 7, 8})) .setHashIndexes(Arrays.asList(6)); //------------------------------------------------------------------------------------- List<Integer> hashLineitem = Arrays.asList(0); - SelectionOperator selectionLineitem = new SelectionOperator( + SelectOperator selectionLineitem = new SelectOperator( new ComparisonPredicate( new ColumnReference(_sc, 8), new ValueSpecification(_sc, "R") )); - ProjectionOperator projectionLineitem = new ProjectionOperator(new int[]{0, 5, 6}); + ProjectOperator projectionLineitem = new ProjectOperator(new int[]{0, 5, 6}); DataSourceComponent relationLineitem = new DataSourceComponent( "LINEITEM", dataPath + "lineitem" + extension, TPCH_Schema.lineitem, _queryPlan).setHashIndexes(hashLineitem) - .setSelection(selectionLineitem) - .setProjection(projectionLineitem); + .addOperator(selectionLineitem) + .addOperator(projectionLineitem); //------------------------------------------------------------------------------------- // set up aggregation function on the StormComponent(Bolt) where join is performed @@ -158,8 +156,8 @@ false, new ValueSpecification(_dc, _date2) EquiJoinComponent C_O_N_Ljoin = new EquiJoinComponent( C_O_Njoin, relationLineitem, - _queryPlan).setProjection(new ProjectionOperator(new int[]{0, 1, 2, 3, 4, 5, 7, 8, 9})) - .setAggregation(agg); + _queryPlan).addOperator(new ProjectOperator(new int[]{0, 1, 2, 3, 4, 5, 7, 8, 9})) + .addOperator(agg); //------------------------------------------------------------------------------------- AggregateOperator overallAgg = diff --git a/src/squall_plan_runner/src/queryPlans/TPCH3Plan.java b/src/squall_plan_runner/src/queryPlans/TPCH3Plan.java index 4139399f..da97fe70 100755 --- a/src/squall_plan_runner/src/queryPlans/TPCH3Plan.java +++ b/src/squall_plan_runner/src/queryPlans/TPCH3Plan.java @@ -24,8 +24,8 @@ import java.util.Map; import operators.AggregateOperator; import operators.AggregateSumOperator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ProjectOperator; +import operators.SelectOperator; import org.apache.log4j.Logger; import predicates.ComparisonPredicate; @@ -47,68 +47,68 @@ public TPCH3Plan(String dataPath, String extension, Map conf){ //------------------------------------------------------------------------------------- List<Integer> hashCustomer = Arrays.asList(0); - SelectionOperator selectionCustomer = new SelectionOperator( + SelectOperator selectionCustomer = new SelectOperator( new ComparisonPredicate( new ColumnReference(_sc, 6), new ValueSpecification(_sc, _customerMktSegment) )); - ProjectionOperator projectionCustomer = new ProjectionOperator(new int[]{0}); + ProjectOperator projectionCustomer = new ProjectOperator(new int[]{0}); DataSourceComponent relationCustomer = new DataSourceComponent( "CUSTOMER", dataPath + "customer" + extension, TPCH_Schema.customer, _queryPlan).setHashIndexes(hashCustomer) - .setSelection(selectionCustomer) - .setProjection(projectionCustomer); + .addOperator(selectionCustomer) + .addOperator(projectionCustomer); //------------------------------------------------------------------------------------- List<Integer> hashOrders = Arrays.asList(1); - SelectionOperator selectionOrders = new SelectionOperator( + SelectOperator selectionOrders = new SelectOperator( new ComparisonPredicate( ComparisonPredicate.LESS_OP, new ColumnReference(_dateConv, 4), new ValueSpecification(_dateConv, _date) )); - ProjectionOperator projectionOrders = new ProjectionOperator(new int[]{0, 1, 4, 7}); + ProjectOperator projectionOrders = new ProjectOperator(new int[]{0, 1, 4, 7}); DataSourceComponent relationOrders = new DataSourceComponent( "ORDERS", dataPath + "orders" + extension, TPCH_Schema.orders, _queryPlan).setHashIndexes(hashOrders) - .setSelection(selectionOrders) - .setProjection(projectionOrders); + .addOperator(selectionOrders) + .addOperator(projectionOrders); //------------------------------------------------------------------------------------- EquiJoinComponent C_Ojoin = new EquiJoinComponent( relationCustomer, relationOrders, - _queryPlan).setProjection(new ProjectionOperator(new int[]{1, 2, 3})) - .setHashIndexes(Arrays.asList(0)); + _queryPlan).addOperator(new ProjectOperator(new int[]{1, 2, 3})) + .setHashIndexes(Arrays.asList(0)); //------------------------------------------------------------------------------------- List<Integer> hashLineitem = Arrays.asList(0); - SelectionOperator selectionLineitem = new SelectionOperator( + SelectOperator selectionLineitem = new SelectOperator( new ComparisonPredicate( ComparisonPredicate.GREATER_OP, new ColumnReference(_dateConv, 10), new ValueSpecification(_dateConv, _date) )); - ProjectionOperator projectionLineitem = new ProjectionOperator(new int[]{0, 5, 6}); + ProjectOperator projectionLineitem = new ProjectOperator(new int[]{0, 5, 6}); DataSourceComponent relationLineitem = new DataSourceComponent( "LINEITEM", dataPath + "lineitem" + extension, TPCH_Schema.lineitem, _queryPlan).setHashIndexes(hashLineitem) - .setSelection(selectionLineitem) - .setProjection(projectionLineitem); + .addOperator(selectionLineitem) + .addOperator(projectionLineitem); //------------------------------------------------------------------------------------- // set up aggregation function on the StormComponent(Bolt) where join is performed @@ -129,7 +129,7 @@ public TPCH3Plan(String dataPath, String extension, Map conf){ EquiJoinComponent C_O_Ljoin = new EquiJoinComponent( C_Ojoin, relationLineitem, - _queryPlan).setAggregation(agg); + _queryPlan).addOperator(agg); //------------------------------------------------------------------------------------- diff --git a/src/squall_plan_runner/src/queryPlans/TPCH4Plan.java b/src/squall_plan_runner/src/queryPlans/TPCH4Plan.java index 4339147e..67bc0902 100755 --- a/src/squall_plan_runner/src/queryPlans/TPCH4Plan.java +++ b/src/squall_plan_runner/src/queryPlans/TPCH4Plan.java @@ -24,8 +24,8 @@ import operators.AggregateOperator; import operators.AggregateSumOperator; import operators.DistinctOperator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ProjectOperator; +import operators.SelectOperator; import org.apache.log4j.Logger; import predicates.BetweenPredicate; import predicates.ComparisonPredicate; @@ -63,27 +63,27 @@ public TPCH4Plan(String dataPath, String extension, Map conf){ //------------------------------------------------------------------------------------- List<Integer> hashOrders = Arrays.asList(0); - SelectionOperator selectionOrders = new SelectionOperator( + SelectOperator selectionOrders = new SelectOperator( new BetweenPredicate( new ColumnReference(_dc, 4), true, new ValueSpecification(_dc, _date1), false, new ValueSpecification(_dc, _date2) )); - ProjectionOperator projectionOrders = new ProjectionOperator(new int[]{0, 5}); + ProjectOperator projectionOrders = new ProjectOperator(new int[]{0, 5}); DataSourceComponent relationOrders = new DataSourceComponent( "ORDERS", dataPath + "orders" + extension, TPCH_Schema.orders, _queryPlan).setHashIndexes(hashOrders) - .setSelection(selectionOrders) - .setProjection(projectionOrders); + .addOperator(selectionOrders) + .addOperator(projectionOrders); //------------------------------------------------------------------------------------- List<Integer> hashLineitem = Arrays.asList(0); - SelectionOperator selectionLineitem = new SelectionOperator( + SelectOperator selectionLineitem = new SelectOperator( new ComparisonPredicate( ComparisonPredicate.LESS_OP, new ColumnReference(_dc, 11), @@ -97,8 +97,8 @@ false, new ValueSpecification(_dc, _date2) dataPath + "lineitem" + extension, TPCH_Schema.lineitem, _queryPlan).setHashIndexes(hashLineitem) - .setSelection(selectionLineitem) - .setDistinct(distinctLineitem); + .addOperator(selectionLineitem) + .addOperator(distinctLineitem); //------------------------------------------------------------------------------------- EquiJoinComponent O_Ljoin = new EquiJoinComponent( @@ -112,7 +112,7 @@ false, new ValueSpecification(_dc, _date2) OperatorComponent finalComponent = new OperatorComponent( O_Ljoin, "FINAL_RESULT", - _queryPlan).setAggregation(aggOp); + _queryPlan).addOperator(aggOp); //------------------------------------------------------------------------------------- diff --git a/src/squall_plan_runner/src/queryPlans/TPCH5Plan.java b/src/squall_plan_runner/src/queryPlans/TPCH5Plan.java index 3813c354..bae3a22b 100755 --- a/src/squall_plan_runner/src/queryPlans/TPCH5Plan.java +++ b/src/squall_plan_runner/src/queryPlans/TPCH5Plan.java @@ -26,8 +26,8 @@ import java.util.Map; import operators.AggregateOperator; import operators.AggregateSumOperator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ProjectOperator; +import operators.SelectOperator; import org.apache.log4j.Logger; import predicates.BetweenPredicate; import predicates.ComparisonPredicate; @@ -68,145 +68,145 @@ public TPCH5Plan(String dataPath, String extension, Map conf){ //------------------------------------------------------------------------------------- List<Integer> hashRegion = Arrays.asList(0); - SelectionOperator selectionRegion = new SelectionOperator( + SelectOperator selectionRegion = new SelectOperator( new ComparisonPredicate( new ColumnReference(_sc, 1), new ValueSpecification(_sc, REGION_NAME) )); - ProjectionOperator projectionRegion = new ProjectionOperator(new int[]{0}); + ProjectOperator projectionRegion = new ProjectOperator(new int[]{0}); DataSourceComponent relationRegion = new DataSourceComponent( "REGION", dataPath + "region" + extension, TPCH_Schema.region, _queryPlan).setHashIndexes(hashRegion) - .setSelection(selectionRegion) - .setProjection(projectionRegion); + .addOperator(selectionRegion) + .addOperator(projectionRegion); //------------------------------------------------------------------------------------- List<Integer> hashNation = Arrays.asList(2); - ProjectionOperator projectionNation = new ProjectionOperator(new int[]{0, 1, 2}); + ProjectOperator projectionNation = new ProjectOperator(new int[]{0, 1, 2}); DataSourceComponent relationNation = new DataSourceComponent( "NATION", dataPath + "nation" + extension, TPCH_Schema.nation, _queryPlan).setHashIndexes(hashNation) - .setProjection(projectionNation); + .addOperator(projectionNation); //------------------------------------------------------------------------------------- List<Integer> hashRN = Arrays.asList(0); - ProjectionOperator projectionRN = new ProjectionOperator(new int[]{1, 2}); + ProjectOperator projectionRN = new ProjectOperator(new int[]{1, 2}); EquiJoinComponent R_Njoin = new EquiJoinComponent( relationRegion, relationNation, _queryPlan).setHashIndexes(hashRN) - .setProjection(projectionRN); + .addOperator(projectionRN); //------------------------------------------------------------------------------------- List<Integer> hashSupplier = Arrays.asList(1); - ProjectionOperator projectionSupplier = new ProjectionOperator(new int[]{0, 3}); + ProjectOperator projectionSupplier = new ProjectOperator(new int[]{0, 3}); DataSourceComponent relationSupplier = new DataSourceComponent( "SUPPLIER", dataPath + "supplier" + extension, TPCH_Schema.supplier, _queryPlan).setHashIndexes(hashSupplier) - .setProjection(projectionSupplier); + .addOperator(projectionSupplier); //------------------------------------------------------------------------------------- List<Integer> hashRNS = Arrays.asList(2); - ProjectionOperator projectionRNS = new ProjectionOperator(new int[]{0, 1, 2}); + ProjectOperator projectionRNS = new ProjectOperator(new int[]{0, 1, 2}); EquiJoinComponent R_N_Sjoin = new EquiJoinComponent( R_Njoin, relationSupplier, _queryPlan).setHashIndexes(hashRNS) - .setProjection(projectionRNS); + .addOperator(projectionRNS); //------------------------------------------------------------------------------------- List<Integer> hashLineitem = Arrays.asList(1); - ProjectionOperator projectionLineitem = new ProjectionOperator(new int[]{0, 2, 5, 6}); + ProjectOperator projectionLineitem = new ProjectOperator(new int[]{0, 2, 5, 6}); DataSourceComponent relationLineitem = new DataSourceComponent( "LINEITEM", dataPath + "lineitem" + extension, TPCH_Schema.lineitem, _queryPlan).setHashIndexes(hashLineitem) - .setProjection(projectionLineitem); + .addOperator(projectionLineitem); //------------------------------------------------------------------------------------- List<Integer> hashRNSL = Arrays.asList(0, 2); - ProjectionOperator projectionRNSL = new ProjectionOperator(new int[]{0, 1, 3, 4, 5}); + ProjectOperator projectionRNSL = new ProjectOperator(new int[]{0, 1, 3, 4, 5}); EquiJoinComponent R_N_S_Ljoin = new EquiJoinComponent( R_N_Sjoin, relationLineitem, _queryPlan).setHashIndexes(hashRNSL) - .setProjection(projectionRNSL); + .addOperator(projectionRNSL); //------------------------------------------------------------------------------------- List<Integer> hashCustomer = Arrays.asList(0); - ProjectionOperator projectionCustomer = new ProjectionOperator(new int[]{0, 3}); + ProjectOperator projectionCustomer = new ProjectOperator(new int[]{0, 3}); DataSourceComponent relationCustomer = new DataSourceComponent( "CUSTOMER", dataPath + "customer" + extension, TPCH_Schema.customer, _queryPlan).setHashIndexes(hashCustomer) - .setProjection(projectionCustomer); + .addOperator(projectionCustomer); //------------------------------------------------------------------------------------- List<Integer> hashOrders = Arrays.asList(1); - SelectionOperator selectionOrders = new SelectionOperator( + SelectOperator selectionOrders = new SelectOperator( new BetweenPredicate( new ColumnReference(_dc, 4), true, new ValueSpecification(_dc, _date1), false, new ValueSpecification(_dc, _date2) )); - ProjectionOperator projectionOrders = new ProjectionOperator(new int[]{0, 1}); + ProjectOperator projectionOrders = new ProjectOperator(new int[]{0, 1}); DataSourceComponent relationOrders = new DataSourceComponent( "ORDERS", dataPath + "orders" + extension, TPCH_Schema.orders, _queryPlan).setHashIndexes(hashOrders) - .setSelection(selectionOrders) - .setProjection(projectionOrders); + .addOperator(selectionOrders) + .addOperator(projectionOrders); //------------------------------------------------------------------------------------- List<Integer> hashCO = Arrays.asList(0, 1); - ProjectionOperator projectionCO = new ProjectionOperator(new int[]{1, 2}); + ProjectOperator projectionCO = new ProjectOperator(new int[]{1, 2}); EquiJoinComponent C_Ojoin = new EquiJoinComponent( relationCustomer, relationOrders, _queryPlan).setHashIndexes(hashCO) - .setProjection(projectionCO); + .addOperator(projectionCO); //------------------------------------------------------------------------------------- List<Integer> hashRNSLCO = Arrays.asList(0); - ProjectionOperator projectionRNSLCO = new ProjectionOperator(new int[]{1, 3, 4}); + ProjectOperator projectionRNSLCO = new ProjectOperator(new int[]{1, 3, 4}); EquiJoinComponent R_N_S_L_C_Ojoin = new EquiJoinComponent( R_N_S_Ljoin, C_Ojoin, _queryPlan).setHashIndexes(hashRNSLCO) - .setProjection(projectionRNSLCO); + .addOperator(projectionRNSLCO); //------------------------------------------------------------------------------------- // set up aggregation function on a separate StormComponent(Bolt) @@ -225,7 +225,7 @@ false, new ValueSpecification(_dc, _date2) OperatorComponent finalComponent = new OperatorComponent( R_N_S_L_C_Ojoin, "FINAL_RESULT", - _queryPlan).setAggregation(aggOp); + _queryPlan).addOperator(aggOp); //------------------------------------------------------------------------------------- AggregateOperator overallAgg = diff --git a/src/squall_plan_runner/src/queryPlans/TPCH7Plan.java b/src/squall_plan_runner/src/queryPlans/TPCH7Plan.java index 52f6d79a..b7533b57 100755 --- a/src/squall_plan_runner/src/queryPlans/TPCH7Plan.java +++ b/src/squall_plan_runner/src/queryPlans/TPCH7Plan.java @@ -25,8 +25,8 @@ import java.util.Map; import operators.AggregateOperator; import operators.AggregateSumOperator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ProjectOperator; +import operators.SelectOperator; import org.apache.log4j.Logger; import predicates.AndPredicate; import predicates.BetweenPredicate; @@ -54,7 +54,7 @@ public TPCH7Plan(String dataPath, String extension, Map conf){ //------------------------------------------------------------------------------------- List<Integer> hashNation2 = Arrays.asList(1); - SelectionOperator selectionNation2 = new SelectionOperator( + SelectOperator selectionNation2 = new SelectOperator( new OrPredicate( new ComparisonPredicate( new ColumnReference(_sc, 1), @@ -65,90 +65,90 @@ public TPCH7Plan(String dataPath, String extension, Map conf){ ) )); - ProjectionOperator projectionNation2 = new ProjectionOperator(new int[]{1, 0}); + ProjectOperator projectionNation2 = new ProjectOperator(new int[]{1, 0}); DataSourceComponent relationNation2 = new DataSourceComponent( "NATION2", dataPath + "nation" + extension, TPCH_Schema.nation, _queryPlan).setHashIndexes(hashNation2) - .setSelection(selectionNation2) - .setProjection(projectionNation2); + .addOperator(selectionNation2) + .addOperator(projectionNation2); //------------------------------------------------------------------------------------- List<Integer> hashCustomer = Arrays.asList(1); - ProjectionOperator projectionCustomer = new ProjectionOperator(new int[]{0,3}); + ProjectOperator projectionCustomer = new ProjectOperator(new int[]{0,3}); DataSourceComponent relationCustomer = new DataSourceComponent( "CUSTOMER", dataPath + "customer" + extension, TPCH_Schema.customer, _queryPlan).setHashIndexes(hashCustomer) - .setProjection(projectionCustomer); + .addOperator(projectionCustomer); //------------------------------------------------------------------------------------- EquiJoinComponent N_Cjoin = new EquiJoinComponent( relationNation2, relationCustomer, - _queryPlan).setProjection(new ProjectionOperator(new int[]{0, 2})) + _queryPlan).addOperator(new ProjectOperator(new int[]{0, 2})) .setHashIndexes(Arrays.asList(1)); //------------------------------------------------------------------------------------- List<Integer> hashOrders = Arrays.asList(1); - ProjectionOperator projectionOrders = new ProjectionOperator(new int[]{0,1}); + ProjectOperator projectionOrders = new ProjectOperator(new int[]{0,1}); DataSourceComponent relationOrders = new DataSourceComponent( "ORDERS", dataPath + "orders" + extension, TPCH_Schema.orders, _queryPlan).setHashIndexes(hashOrders) - .setProjection(projectionOrders); + .addOperator(projectionOrders); //------------------------------------------------------------------------------------- EquiJoinComponent N_C_Ojoin = new EquiJoinComponent( N_Cjoin, relationOrders, - _queryPlan).setProjection(new ProjectionOperator(new int[]{0, 2})) + _queryPlan).addOperator(new ProjectOperator(new int[]{0, 2})) .setHashIndexes(Arrays.asList(1)); //------------------------------------------------------------------------------------- List<Integer> hashSupplier = Arrays.asList(1); - ProjectionOperator projectionSupplier = new ProjectionOperator(new int[]{0,3}); + ProjectOperator projectionSupplier = new ProjectOperator(new int[]{0,3}); DataSourceComponent relationSupplier = new DataSourceComponent( "SUPPLIER", dataPath + "supplier" + extension, TPCH_Schema.supplier, _queryPlan).setHashIndexes(hashSupplier) - .setProjection(projectionSupplier); + .addOperator(projectionSupplier); //------------------------------------------------------------------------------------- List<Integer> hashNation1 = Arrays.asList(1); - ProjectionOperator projectionNation1 = new ProjectionOperator(new int[]{1,0}); + ProjectOperator projectionNation1 = new ProjectOperator(new int[]{1,0}); DataSourceComponent relationNation1 = new DataSourceComponent( "NATION1", dataPath + "nation" + extension, TPCH_Schema.nation, _queryPlan).setHashIndexes(hashNation1) - .setSelection(selectionNation2) - .setProjection(projectionNation1); + .addOperator(selectionNation2) + .addOperator(projectionNation1); //------------------------------------------------------------------------------------- EquiJoinComponent S_Njoin = new EquiJoinComponent( relationSupplier, relationNation1, - _queryPlan).setProjection(new ProjectionOperator(new int[]{0, 2})) + _queryPlan).addOperator(new ProjectOperator(new int[]{0, 2})) .setHashIndexes(Arrays.asList(0)); //------------------------------------------------------------------------------------- List<Integer> hashLineitem = Arrays.asList(2); - SelectionOperator selectionLineitem = new SelectionOperator( + SelectOperator selectionLineitem = new SelectOperator( new BetweenPredicate( new ColumnReference(_dateConv, 10), true, new ValueSpecification(_dateConv, _date1), @@ -173,26 +173,26 @@ true, new ValueSpecification(_dateConv, _date2) ColumnReference supplierKey = new ColumnReference(_sc, 2); //forth field in projection ColumnReference orderKey = new ColumnReference(_sc, 0); - ProjectionOperator projectionLineitem = new ProjectionOperator(extractYear, product, supplierKey, orderKey); + ProjectOperator projectionLineitem = new ProjectOperator(extractYear, product, supplierKey, orderKey); DataSourceComponent relationLineitem = new DataSourceComponent( "LINEITEM", dataPath + "lineitem" + extension, TPCH_Schema.lineitem, _queryPlan).setHashIndexes(hashLineitem) - .setSelection(selectionLineitem) - .setProjection(projectionLineitem); + .addOperator(selectionLineitem) + .addOperator(projectionLineitem); //------------------------------------------------------------------------------------- EquiJoinComponent L_S_Njoin = new EquiJoinComponent( relationLineitem, S_Njoin, - _queryPlan).setProjection(new ProjectionOperator(new int[]{4, 0, 1, 3})) + _queryPlan).addOperator(new ProjectOperator(new int[]{4, 0, 1, 3})) .setHashIndexes(Arrays.asList(3)); //------------------------------------------------------------------------------------- // set up aggregation function on the same StormComponent(Bolt) where the last join is - SelectionOperator so = new SelectionOperator( + SelectOperator so = new SelectOperator( new OrPredicate( new AndPredicate( new ComparisonPredicate( @@ -220,8 +220,8 @@ true, new ValueSpecification(_dateConv, _date2) EquiJoinComponent N_C_O_L_S_Njoin = new EquiJoinComponent( N_C_Ojoin, L_S_Njoin, - _queryPlan).setSelection(so) - .setAggregation(agg); + _queryPlan).addOperator(so) + .addOperator(agg); //------------------------------------------------------------------------------------- AggregateOperator overallAgg = new AggregateSumOperator(_doubleConv, new ColumnReference(_doubleConv, 1), conf) diff --git a/src/squall_plan_runner/src/queryPlans/TPCH8Plan.java b/src/squall_plan_runner/src/queryPlans/TPCH8Plan.java index 381d248f..fc5f42b2 100755 --- a/src/squall_plan_runner/src/queryPlans/TPCH8Plan.java +++ b/src/squall_plan_runner/src/queryPlans/TPCH8Plan.java @@ -25,8 +25,8 @@ import java.util.Map; import operators.AggregateOperator; import operators.AggregateSumOperator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ProjectOperator; +import operators.SelectOperator; import org.apache.log4j.Logger; import predicates.BetweenPredicate; import predicates.ComparisonPredicate; @@ -56,109 +56,109 @@ public TPCH8Plan(String dataPath, String extension, Map conf){ //------------------------------------------------------------------------------------- List<Integer> hashRegion = Arrays.asList(0); - SelectionOperator selectionRegion = new SelectionOperator( + SelectOperator selectionRegion = new SelectOperator( new ComparisonPredicate( new ColumnReference(_sc, 1), new ValueSpecification(_sc, _region) )); - ProjectionOperator projectionRegion = new ProjectionOperator(new int[]{0}); + ProjectOperator projectionRegion = new ProjectOperator(new int[]{0}); DataSourceComponent relationRegion = new DataSourceComponent( "REGION", dataPath + "region" + extension, TPCH_Schema.region, _queryPlan).setHashIndexes(hashRegion) - .setSelection(selectionRegion) - .setProjection(projectionRegion); + .addOperator(selectionRegion) + .addOperator(projectionRegion); //------------------------------------------------------------------------------------- List<Integer> hashNation1 = Arrays.asList(1); - ProjectionOperator projectionNation1 = new ProjectionOperator(new int[]{0,2}); + ProjectOperator projectionNation1 = new ProjectOperator(new int[]{0,2}); DataSourceComponent relationNation1 = new DataSourceComponent( "NATION1", dataPath + "nation" + extension, TPCH_Schema.nation, _queryPlan).setHashIndexes(hashNation1) - .setProjection(projectionNation1); + .addOperator(projectionNation1); //------------------------------------------------------------------------------------- EquiJoinComponent R_Njoin = new EquiJoinComponent( relationRegion, relationNation1, - _queryPlan).setProjection(new ProjectionOperator(new int[]{1})) + _queryPlan).addOperator(new ProjectOperator(new int[]{1})) .setHashIndexes(Arrays.asList(0)); //------------------------------------------------------------------------------------- List<Integer> hashCustomer = Arrays.asList(0); - ProjectionOperator projectionCustomer = new ProjectionOperator(new int[]{3,0}); + ProjectOperator projectionCustomer = new ProjectOperator(new int[]{3,0}); DataSourceComponent relationCustomer = new DataSourceComponent( "CUSTOMER", dataPath + "customer" + extension, TPCH_Schema.customer, _queryPlan).setHashIndexes(hashCustomer) - .setProjection(projectionCustomer); + .addOperator(projectionCustomer); //------------------------------------------------------------------------------------- EquiJoinComponent R_N_Cjoin = new EquiJoinComponent( R_Njoin, relationCustomer, - _queryPlan).setProjection(new ProjectionOperator(new int[]{1})) + _queryPlan).addOperator(new ProjectOperator(new int[]{1})) .setHashIndexes(Arrays.asList(0)); //------------------------------------------------------------------------------------- List<Integer> hashSupplier = Arrays.asList(1); - ProjectionOperator projectionSupplier = new ProjectionOperator(new int[]{0, 3}); + ProjectOperator projectionSupplier = new ProjectOperator(new int[]{0, 3}); DataSourceComponent relationSupplier = new DataSourceComponent( "SUPPLIER", dataPath + "supplier" + extension, TPCH_Schema.supplier, _queryPlan).setHashIndexes(hashSupplier) - .setProjection(projectionSupplier); + .addOperator(projectionSupplier); //------------------------------------------------------------------------------------- List<Integer> hashNation2 = Arrays.asList(0); - ProjectionOperator projectionNation2 = new ProjectionOperator(new int[]{0, 1}); + ProjectOperator projectionNation2 = new ProjectOperator(new int[]{0, 1}); DataSourceComponent relationNation2 = new DataSourceComponent( "NATION2", dataPath + "nation" + extension, TPCH_Schema.nation, _queryPlan).setHashIndexes(hashNation2) - .setProjection(projectionNation2); + .addOperator(projectionNation2); //------------------------------------------------------------------------------------- EquiJoinComponent S_Njoin = new EquiJoinComponent( relationSupplier, relationNation2, - _queryPlan).setProjection(new ProjectionOperator(new int[]{0, 2})) + _queryPlan).addOperator(new ProjectOperator(new int[]{0, 2})) .setHashIndexes(Arrays.asList(0)); //------------------------------------------------------------------------------------- List<Integer> hashPart = Arrays.asList(0); - SelectionOperator selectionPart = new SelectionOperator( + SelectOperator selectionPart = new SelectOperator( new ComparisonPredicate( new ColumnReference(_sc, 4), new ValueSpecification(_sc, _type) )); - ProjectionOperator projectionPart = new ProjectionOperator(new int[]{0}); + ProjectOperator projectionPart = new ProjectOperator(new int[]{0}); DataSourceComponent relationPart = new DataSourceComponent( "PART", dataPath + "part" + extension, TPCH_Schema.part, _queryPlan).setHashIndexes(hashPart) - .setSelection(selectionPart) - .setProjection(projectionPart); + .addOperator(selectionPart) + .addOperator(projectionPart); //------------------------------------------------------------------------------------- List<Integer> hashLineitem = Arrays.asList(1); @@ -179,26 +179,26 @@ public TPCH8Plan(String dataPath, String extension, Map conf){ _doubleConv, new ColumnReference(_doubleConv, 5), substract); - ProjectionOperator projectionLineitem = new ProjectionOperator(orderKey, partKey, suppKey, product); + ProjectOperator projectionLineitem = new ProjectOperator(orderKey, partKey, suppKey, product); DataSourceComponent relationLineitem = new DataSourceComponent( "LINEITEM", dataPath + "lineitem" + extension, TPCH_Schema.lineitem, _queryPlan).setHashIndexes(hashLineitem) - .setProjection(projectionLineitem); + .addOperator(projectionLineitem); //------------------------------------------------------------------------------------- EquiJoinComponent P_Ljoin = new EquiJoinComponent( relationPart, relationLineitem, - _queryPlan).setProjection(new ProjectionOperator(new int[]{1,2,3})) + _queryPlan).addOperator(new ProjectOperator(new int[]{1,2,3})) .setHashIndexes(Arrays.asList(0)); //------------------------------------------------------------------------------------- List<Integer> hashOrders = Arrays.asList(0); - SelectionOperator selectionOrders = new SelectionOperator( + SelectOperator selectionOrders = new SelectOperator( new BetweenPredicate( new ColumnReference(_dateConv, 4), true, new ValueSpecification(_dateConv, _date1), @@ -212,28 +212,28 @@ true, new ValueSpecification(_dateConv, _date2) //third field in projection ValueExpression OrdersExtractYear = new IntegerYearFromDate( new ColumnReference<Date>(_dateConv, 4)); - ProjectionOperator projectionOrders = new ProjectionOperator(OrdersOrderKey, OrdersCustKey, OrdersExtractYear); + ProjectOperator projectionOrders = new ProjectOperator(OrdersOrderKey, OrdersCustKey, OrdersExtractYear); DataSourceComponent relationOrders = new DataSourceComponent( "ORDERS", dataPath + "orders" + extension, TPCH_Schema.orders, _queryPlan).setHashIndexes(hashOrders) - .setSelection(selectionOrders) - .setProjection(projectionOrders); + .addOperator(selectionOrders) + .addOperator(projectionOrders); //------------------------------------------------------------------------------------- EquiJoinComponent P_L_Ojoin = new EquiJoinComponent( P_Ljoin, relationOrders, - _queryPlan).setProjection(new ProjectionOperator(new int[]{1,2,3,4})) + _queryPlan).addOperator(new ProjectOperator(new int[]{1,2,3,4})) .setHashIndexes(Arrays.asList(0)); //------------------------------------------------------------------------------------- EquiJoinComponent S_N_P_L_Ojoin = new EquiJoinComponent( S_Njoin, P_L_Ojoin, - _queryPlan).setProjection(new ProjectionOperator(new int[]{1,2,3,4})) + _queryPlan).addOperator(new ProjectOperator(new int[]{1,2,3,4})) .setHashIndexes(Arrays.asList(2)); //------------------------------------------------------------------------------------- @@ -243,7 +243,7 @@ true, new ValueSpecification(_dateConv, _date2) EquiJoinComponent R_N_C_S_N_P_L_Ojoin = new EquiJoinComponent( R_N_Cjoin, S_N_P_L_Ojoin, - _queryPlan).setAggregation(agg); + _queryPlan).addOperator(agg); //------------------------------------------------------------------------------------- AggregateOperator overallAgg = diff --git a/src/squall_plan_runner/src/queryPlans/TPCH9Plan.java b/src/squall_plan_runner/src/queryPlans/TPCH9Plan.java index 7db6b014..23701b53 100644 --- a/src/squall_plan_runner/src/queryPlans/TPCH9Plan.java +++ b/src/squall_plan_runner/src/queryPlans/TPCH9Plan.java @@ -24,8 +24,8 @@ import java.util.Map; import operators.AggregateOperator; import operators.AggregateSumOperator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ProjectOperator; +import operators.SelectOperator; import org.apache.log4j.Logger; import predicates.LikePredicate; @@ -44,33 +44,33 @@ public TPCH9Plan(String dataPath, String extension, Map conf){ //------------------------------------------------------------------------------------- List<Integer> hashPart = Arrays.asList(0); - SelectionOperator selectionPart = new SelectionOperator( + SelectOperator selectionPart = new SelectOperator( new LikePredicate( new ColumnReference(_sc, 1), new ValueSpecification(_sc, COLOR) )); - ProjectionOperator projectionPart = new ProjectionOperator(new int[]{0}); + ProjectOperator projectionPart = new ProjectOperator(new int[]{0}); DataSourceComponent relationPart = new DataSourceComponent( "PART", dataPath + "part" + extension, TPCH_Schema.part, _queryPlan).setHashIndexes(hashPart) - .setSelection(selectionPart) - .setProjection(projectionPart); + .addOperator(selectionPart) + .addOperator(projectionPart); //------------------------------------------------------------------------------------- List<Integer> hashLineitem = Arrays.asList(1); - ProjectionOperator projectionLineitem = new ProjectionOperator(new int[]{0, 1, 2, 4, 5, 6}); + ProjectOperator projectionLineitem = new ProjectOperator(new int[]{0, 1, 2, 4, 5, 6}); DataSourceComponent relationLineitem = new DataSourceComponent( "LINEITEM", dataPath + "lineitem" + extension, TPCH_Schema.lineitem, _queryPlan).setHashIndexes(hashLineitem) - .setProjection(projectionLineitem); + .addOperator(projectionLineitem); //------------------------------------------------------------------------------------- EquiJoinComponent P_Ljoin = new EquiJoinComponent( @@ -81,26 +81,26 @@ public TPCH9Plan(String dataPath, String extension, Map conf){ List<Integer> hashPartsupp = Arrays.asList(0, 1); - ProjectionOperator projectionPartsupp = new ProjectionOperator(new int[]{0, 1, 3}); + ProjectOperator projectionPartsupp = new ProjectOperator(new int[]{0, 1, 3}); DataSourceComponent relationPartsupp = new DataSourceComponent( "PARTSUPP", dataPath + "partsupp" + extension, TPCH_Schema.partsupp, _queryPlan).setHashIndexes(hashPartsupp) - .setProjection(projectionPartsupp); + .addOperator(projectionPartsupp); //------------------------------------------------------------------------------------- EquiJoinComponent P_L_PSjoin = new EquiJoinComponent( P_Ljoin, relationPartsupp, _queryPlan).setHashIndexes(Arrays.asList(0)) - .setProjection(new ProjectionOperator(new int[]{1, 2, 3, 4, 5, 6})); + .addOperator(new ProjectOperator(new int[]{1, 2, 3, 4, 5, 6})); //------------------------------------------------------------------------------------- List<Integer> hashOrders = Arrays.asList(0); - ProjectionOperator projectionOrders = new ProjectionOperator( + ProjectOperator projectionOrders = new ProjectOperator( new ColumnReference(_sc, 0), new IntegerYearFromDate(new ColumnReference(_dateConv, 4))); @@ -109,7 +109,7 @@ public TPCH9Plan(String dataPath, String extension, Map conf){ dataPath + "orders" + extension, TPCH_Schema.orders, _queryPlan).setHashIndexes(hashOrders) - .setProjection(projectionOrders); + .addOperator(projectionOrders); //------------------------------------------------------------------------------------- @@ -117,37 +117,37 @@ public TPCH9Plan(String dataPath, String extension, Map conf){ P_L_PSjoin, relationOrders, _queryPlan).setHashIndexes(Arrays.asList(0)) - .setProjection(new ProjectionOperator(new int[]{1, 2, 3, 4, 5, 6})); + .addOperator(new ProjectOperator(new int[]{1, 2, 3, 4, 5, 6})); //------------------------------------------------------------------------------------- List<Integer> hashSupplier = Arrays.asList(0); - ProjectionOperator projectionSupplier = new ProjectionOperator(new int[]{0, 3}); + ProjectOperator projectionSupplier = new ProjectOperator(new int[]{0, 3}); DataSourceComponent relationSupplier = new DataSourceComponent( "SUPPLIER", dataPath + "supplier" + extension, TPCH_Schema.supplier, _queryPlan).setHashIndexes(hashSupplier) - .setProjection(projectionSupplier); + .addOperator(projectionSupplier); //------------------------------------------------------------------------------------- EquiJoinComponent P_L_PS_O_Sjoin = new EquiJoinComponent( P_L_PS_Ojoin, relationSupplier, _queryPlan).setHashIndexes(Arrays.asList(5)) - .setProjection(new ProjectionOperator(new int[]{1, 2, 3, 4, 5, 6})); + .addOperator(new ProjectOperator(new int[]{1, 2, 3, 4, 5, 6})); //------------------------------------------------------------------------------------- List<Integer> hashNation = Arrays.asList(0); - ProjectionOperator projectionNation = new ProjectionOperator(new int[]{0, 1}); + ProjectOperator projectionNation = new ProjectOperator(new int[]{0, 1}); DataSourceComponent relationNation = new DataSourceComponent( "NATION", dataPath + "nation" + extension, TPCH_Schema.nation, _queryPlan).setHashIndexes(hashNation) - .setProjection(projectionNation); + .addOperator(projectionNation); //------------------------------------------------------------------------------------- // set up aggregation function on the StormComponent(Bolt) where join is performed @@ -182,8 +182,8 @@ public TPCH9Plan(String dataPath, String extension, Map conf){ EquiJoinComponent P_L_PS_O_S_Njoin = new EquiJoinComponent( P_L_PS_O_Sjoin, relationNation, - _queryPlan).setProjection(new ProjectionOperator(new int[]{0, 1, 2, 3, 4, 6})) - .setAggregation(agg); + _queryPlan).addOperator(new ProjectOperator(new int[]{0, 1, 2, 3, 4, 6})) + .addOperator(agg); //------------------------------------------------------------------------------------- diff --git a/src/squall_plan_runner/src/queryPlans/debug/HyracksL1Plan.java b/src/squall_plan_runner/src/queryPlans/debug/HyracksL1Plan.java index 3c2e7fa3..50425f55 100644 --- a/src/squall_plan_runner/src/queryPlans/debug/HyracksL1Plan.java +++ b/src/squall_plan_runner/src/queryPlans/debug/HyracksL1Plan.java @@ -10,7 +10,7 @@ import java.util.Arrays; import java.util.List; import java.util.Map; -import operators.ProjectionOperator; +import operators.ProjectOperator; import org.apache.log4j.Logger; import queryPlans.QueryPlan; @@ -26,24 +26,24 @@ public class HyracksL1Plan { public HyracksL1Plan(String dataPath, String extension, Map conf){ //------------------------------------------------------------------------------------- // start of query plan filling - ProjectionOperator projectionCustomer = new ProjectionOperator(new int[]{0, 6}); + ProjectOperator projectionCustomer = new ProjectOperator(new int[]{0, 6}); List<Integer> hashCustomer = Arrays.asList(0); DataSourceComponent relationCustomer = new DataSourceComponent( "CUSTOMER", dataPath + "customer" + extension, TPCH_Schema.customer, - _queryPlan).setProjection(projectionCustomer) + _queryPlan).addOperator(projectionCustomer) .setHashIndexes(hashCustomer) .setPrintOut(false); //------------------------------------------------------------------------------------- - ProjectionOperator projectionOrders = new ProjectionOperator(new int[]{1}); + ProjectOperator projectionOrders = new ProjectOperator(new int[]{1}); List<Integer> hashOrders = Arrays.asList(0); DataSourceComponent relationOrders = new DataSourceComponent( "ORDERS", dataPath + "orders" + extension, TPCH_Schema.orders, - _queryPlan).setProjection(projectionOrders) + _queryPlan).addOperator(projectionOrders) .setHashIndexes(hashOrders) .setPrintOut(false); diff --git a/src/squall_plan_runner/src/queryPlans/debug/HyracksL3BatchPlan.java b/src/squall_plan_runner/src/queryPlans/debug/HyracksL3BatchPlan.java index f8b5a721..706fe22a 100644 --- a/src/squall_plan_runner/src/queryPlans/debug/HyracksL3BatchPlan.java +++ b/src/squall_plan_runner/src/queryPlans/debug/HyracksL3BatchPlan.java @@ -16,7 +16,7 @@ import operators.AggregateCountOperator; import operators.AggregateOperator; import operators.AggregateSumOperator; -import operators.ProjectionOperator; +import operators.ProjectOperator; import org.apache.log4j.Logger; import queryPlans.QueryPlan; @@ -32,23 +32,23 @@ public class HyracksL3BatchPlan { public HyracksL3BatchPlan(String dataPath, String extension, Map conf){ //------------------------------------------------------------------------------------- // start of query plan filling - ProjectionOperator projectionCustomer = new ProjectionOperator(new int[]{0, 6}); + ProjectOperator projectionCustomer = new ProjectOperator(new int[]{0, 6}); List<Integer> hashCustomer = Arrays.asList(0); DataSourceComponent relationCustomer = new DataSourceComponent( "CUSTOMER", dataPath + "customer" + extension, TPCH_Schema.customer, - _queryPlan).setProjection(projectionCustomer) + _queryPlan).addOperator(projectionCustomer) .setHashIndexes(hashCustomer); //------------------------------------------------------------------------------------- - ProjectionOperator projectionOrders = new ProjectionOperator(new int[]{1}); + ProjectOperator projectionOrders = new ProjectOperator(new int[]{1}); List<Integer> hashOrders = Arrays.asList(0); DataSourceComponent relationOrders = new DataSourceComponent( "ORDERS", dataPath + "orders" + extension, TPCH_Schema.orders, - _queryPlan).setProjection(projectionOrders) + _queryPlan).addOperator(projectionOrders) .setHashIndexes(hashOrders); @@ -59,7 +59,7 @@ public HyracksL3BatchPlan(String dataPath, String extension, Map conf){ EquiJoinComponent CUSTOMER_ORDERSjoin = new EquiJoinComponent( relationCustomer, relationOrders, - _queryPlan).setAggregation(postAgg) + _queryPlan).addOperator(postAgg) .setHashIndexes(hashIndexes) .setBatchOutputMode(1000); @@ -68,7 +68,7 @@ public HyracksL3BatchPlan(String dataPath, String extension, Map conf){ .setGroupByColumns(Arrays.asList(0)); OperatorComponent oc = new OperatorComponent(CUSTOMER_ORDERSjoin, "COUNTAGG", _queryPlan) - .setAggregation(agg) + .addOperator(agg) .setFullHashList(Arrays.asList("FURNITURE", "BUILDING", "MACHINERY", "HOUSEHOLD", "AUTOMOBILE")); //------------------------------------------------------------------------------------- diff --git a/src/squall_plan_runner/src/queryPlans/debug/HyracksL3Plan.java b/src/squall_plan_runner/src/queryPlans/debug/HyracksL3Plan.java index e19c3260..e924394c 100644 --- a/src/squall_plan_runner/src/queryPlans/debug/HyracksL3Plan.java +++ b/src/squall_plan_runner/src/queryPlans/debug/HyracksL3Plan.java @@ -16,7 +16,7 @@ import operators.AggregateCountOperator; import operators.AggregateOperator; import operators.AggregateSumOperator; -import operators.ProjectionOperator; +import operators.ProjectOperator; import org.apache.log4j.Logger; import queryPlans.QueryPlan; @@ -32,23 +32,23 @@ public class HyracksL3Plan { public HyracksL3Plan(String dataPath, String extension, Map conf){ //------------------------------------------------------------------------------------- // start of query plan filling - ProjectionOperator projectionCustomer = new ProjectionOperator(new int[]{0, 6}); + ProjectOperator projectionCustomer = new ProjectOperator(new int[]{0, 6}); List<Integer> hashCustomer = Arrays.asList(0); DataSourceComponent relationCustomer = new DataSourceComponent( "CUSTOMER", dataPath + "customer" + extension, TPCH_Schema.customer, - _queryPlan).setProjection(projectionCustomer) + _queryPlan).addOperator(projectionCustomer) .setHashIndexes(hashCustomer); //------------------------------------------------------------------------------------- - ProjectionOperator projectionOrders = new ProjectionOperator(new int[]{1}); + ProjectOperator projectionOrders = new ProjectOperator(new int[]{1}); List<Integer> hashOrders = Arrays.asList(0); DataSourceComponent relationOrders = new DataSourceComponent( "ORDERS", dataPath + "orders" + extension, TPCH_Schema.orders, - _queryPlan).setProjection(projectionOrders) + _queryPlan).addOperator(projectionOrders) .setHashIndexes(hashOrders); @@ -63,7 +63,7 @@ public HyracksL3Plan(String dataPath, String extension, Map conf){ AggregateCountOperator agg = new AggregateCountOperator(conf).setGroupByColumns(Arrays.asList(1)); OperatorComponent oc = new OperatorComponent(CUSTOMER_ORDERSjoin, "COUNTAGG", _queryPlan) - .setAggregation(agg) + .addOperator(agg) .setFullHashList(Arrays.asList("FURNITURE", "BUILDING", "MACHINERY", "HOUSEHOLD", "AUTOMOBILE")); //------------------------------------------------------------------------------------- diff --git a/src/squall_plan_runner/src/queryPlans/debug/TPCH3L1Plan.java b/src/squall_plan_runner/src/queryPlans/debug/TPCH3L1Plan.java index bc7a2687..1a16dbe7 100644 --- a/src/squall_plan_runner/src/queryPlans/debug/TPCH3L1Plan.java +++ b/src/squall_plan_runner/src/queryPlans/debug/TPCH3L1Plan.java @@ -18,8 +18,8 @@ import java.util.Date; import java.util.List; import java.util.Map; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ProjectOperator; +import operators.SelectOperator; import org.apache.log4j.Logger; import predicates.ComparisonPredicate; import queryPlans.QueryPlan; @@ -42,43 +42,43 @@ public TPCH3L1Plan(String dataPath, String extension, Map conf){ //------------------------------------------------------------------------------------- List<Integer> hashCustomer = Arrays.asList(0); - SelectionOperator selectionCustomer = new SelectionOperator( + SelectOperator selectionCustomer = new SelectOperator( new ComparisonPredicate( new ColumnReference(_sc, 6), new ValueSpecification(_sc, _customerMktSegment) )); - ProjectionOperator projectionCustomer = new ProjectionOperator(new int[]{0}); + ProjectOperator projectionCustomer = new ProjectOperator(new int[]{0}); DataSourceComponent relationCustomer = new DataSourceComponent( "CUSTOMER", dataPath + "customer" + extension, TPCH_Schema.customer, _queryPlan).setHashIndexes(hashCustomer) - .setSelection(selectionCustomer) - .setProjection(projectionCustomer) - .setPrintOut(false); + .addOperator(selectionCustomer) + .addOperator(projectionCustomer) + .setPrintOut(false); //------------------------------------------------------------------------------------- List<Integer> hashOrders = Arrays.asList(1); - SelectionOperator selectionOrders = new SelectionOperator( + SelectOperator selectionOrders = new SelectOperator( new ComparisonPredicate( ComparisonPredicate.LESS_OP, new ColumnReference(_dateConv, 4), new ValueSpecification(_dateConv, _date) )); - ProjectionOperator projectionOrders = new ProjectionOperator(new int[]{0, 1, 4, 7}); + ProjectOperator projectionOrders = new ProjectOperator(new int[]{0, 1, 4, 7}); DataSourceComponent relationOrders = new DataSourceComponent( "ORDERS", dataPath + "orders" + extension, TPCH_Schema.orders, _queryPlan).setHashIndexes(hashOrders) - .setSelection(selectionOrders) - .setProjection(projectionOrders) - .setPrintOut(false); + .addOperator(selectionOrders) + .addOperator(projectionOrders) + .setPrintOut(false); //------------------------------------------------------------------------------------- diff --git a/src/squall_plan_runner/src/queryPlans/debug/TPCH3L23Plan.java b/src/squall_plan_runner/src/queryPlans/debug/TPCH3L23Plan.java index 13c1a48f..0979abdb 100644 --- a/src/squall_plan_runner/src/queryPlans/debug/TPCH3L23Plan.java +++ b/src/squall_plan_runner/src/queryPlans/debug/TPCH3L23Plan.java @@ -19,8 +19,8 @@ import java.util.Date; import java.util.List; import java.util.Map; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ProjectOperator; +import operators.SelectOperator; import org.apache.log4j.Logger; import predicates.ComparisonPredicate; import queryPlans.QueryPlan; @@ -43,68 +43,68 @@ public TPCH3L23Plan(String dataPath, String extension, Map conf){ //------------------------------------------------------------------------------------- List<Integer> hashCustomer = Arrays.asList(0); - SelectionOperator selectionCustomer = new SelectionOperator( + SelectOperator selectionCustomer = new SelectOperator( new ComparisonPredicate( new ColumnReference(_sc, 6), new ValueSpecification(_sc, _customerMktSegment) )); - ProjectionOperator projectionCustomer = new ProjectionOperator(new int[]{0}); + ProjectOperator projectionCustomer = new ProjectOperator(new int[]{0}); DataSourceComponent relationCustomer = new DataSourceComponent( "CUSTOMER", dataPath + "customer" + extension, TPCH_Schema.customer, _queryPlan).setHashIndexes(hashCustomer) - .setSelection(selectionCustomer) - .setProjection(projectionCustomer); + .addOperator(selectionCustomer) + .addOperator(projectionCustomer); //------------------------------------------------------------------------------------- List<Integer> hashOrders = Arrays.asList(1); - SelectionOperator selectionOrders = new SelectionOperator( + SelectOperator selectionOrders = new SelectOperator( new ComparisonPredicate( ComparisonPredicate.LESS_OP, new ColumnReference(_dateConv, 4), new ValueSpecification(_dateConv, _date) )); - ProjectionOperator projectionOrders = new ProjectionOperator(new int[]{0, 1, 4, 7}); + ProjectOperator projectionOrders = new ProjectOperator(new int[]{0, 1, 4, 7}); DataSourceComponent relationOrders = new DataSourceComponent( "ORDERS", dataPath + "orders" + extension, TPCH_Schema.orders, _queryPlan).setHashIndexes(hashOrders) - .setSelection(selectionOrders) - .setProjection(projectionOrders); + .addOperator(selectionOrders) + .addOperator(projectionOrders); //------------------------------------------------------------------------------------- EquiJoinComponent C_Ojoin = new EquiJoinComponent( relationCustomer, relationOrders, - _queryPlan).setProjection(new ProjectionOperator(new int[]{1, 2, 3})) - .setHashIndexes(Arrays.asList(0)); + _queryPlan).addOperator(new ProjectOperator(new int[]{1, 2, 3})) + .setHashIndexes(Arrays.asList(0)); //------------------------------------------------------------------------------------- List<Integer> hashLineitem = Arrays.asList(0); - SelectionOperator selectionLineitem = new SelectionOperator( + SelectOperator selectionLineitem = new SelectOperator( new ComparisonPredicate( ComparisonPredicate.GREATER_OP, new ColumnReference(_dateConv, 10), new ValueSpecification(_dateConv, _date) )); - ProjectionOperator projectionLineitem = new ProjectionOperator(new int[]{0, 5, 6}); + ProjectOperator projectionLineitem = new ProjectOperator(new int[]{0, 5, 6}); DataSourceComponent relationLineitem = new DataSourceComponent( "LINEITEM", dataPath + "lineitem" + extension, TPCH_Schema.lineitem, _queryPlan).setHashIndexes(hashLineitem) - .setSelection(selectionLineitem) - .setProjection(projectionLineitem).setPrintOut(false); + .addOperator(selectionLineitem) + .addOperator(projectionLineitem).setPrintOut(false); //------------------------------------------------------------------------------------- diff --git a/src/squall_plan_runner/src/queryPlans/debug/TPCH3L2Plan.java b/src/squall_plan_runner/src/queryPlans/debug/TPCH3L2Plan.java index e2ad7eb6..abcc6519 100644 --- a/src/squall_plan_runner/src/queryPlans/debug/TPCH3L2Plan.java +++ b/src/squall_plan_runner/src/queryPlans/debug/TPCH3L2Plan.java @@ -19,8 +19,8 @@ import java.util.Date; import java.util.List; import java.util.Map; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ProjectOperator; +import operators.SelectOperator; import org.apache.log4j.Logger; import predicates.ComparisonPredicate; import queryPlans.QueryPlan; @@ -43,48 +43,48 @@ public TPCH3L2Plan(String dataPath, String extension, Map conf){ //------------------------------------------------------------------------------------- List<Integer> hashCustomer = Arrays.asList(0); - SelectionOperator selectionCustomer = new SelectionOperator( + SelectOperator selectionCustomer = new SelectOperator( new ComparisonPredicate( new ColumnReference(_sc, 6), new ValueSpecification(_sc, _customerMktSegment) )); - ProjectionOperator projectionCustomer = new ProjectionOperator(new int[]{0}); + ProjectOperator projectionCustomer = new ProjectOperator(new int[]{0}); DataSourceComponent relationCustomer = new DataSourceComponent( "CUSTOMER", dataPath + "customer" + extension, TPCH_Schema.customer, _queryPlan).setHashIndexes(hashCustomer) - .setSelection(selectionCustomer) - .setProjection(projectionCustomer); + .addOperator(selectionCustomer) + .addOperator(projectionCustomer); //------------------------------------------------------------------------------------- List<Integer> hashOrders = Arrays.asList(1); - SelectionOperator selectionOrders = new SelectionOperator( + SelectOperator selectionOrders = new SelectOperator( new ComparisonPredicate( ComparisonPredicate.LESS_OP, new ColumnReference(_dateConv, 4), new ValueSpecification(_dateConv, _date) )); - ProjectionOperator projectionOrders = new ProjectionOperator(new int[]{0, 1, 4, 7}); + ProjectOperator projectionOrders = new ProjectOperator(new int[]{0, 1, 4, 7}); DataSourceComponent relationOrders = new DataSourceComponent( "ORDERS", dataPath + "orders" + extension, TPCH_Schema.orders, _queryPlan).setHashIndexes(hashOrders) - .setSelection(selectionOrders) - .setProjection(projectionOrders); + .addOperator(selectionOrders) + .addOperator(projectionOrders); //------------------------------------------------------------------------------------- EquiJoinComponent C_Ojoin = new EquiJoinComponent( relationCustomer, relationOrders, - _queryPlan).setProjection(new ProjectionOperator(new int[]{1, 2, 3})) - .setHashIndexes(Arrays.asList(0)).setPrintOut(false); + _queryPlan).addOperator(new ProjectOperator(new int[]{1, 2, 3})) + .setHashIndexes(Arrays.asList(0)).setPrintOut(false); //------------------------------------------------------------------------------------- diff --git a/src/squall_plan_runner/src/stormComponents/StormDataSource.java b/src/squall_plan_runner/src/stormComponents/StormDataSource.java index 1956d80e..c0890005 100755 --- a/src/squall_plan_runner/src/stormComponents/StormDataSource.java +++ b/src/squall_plan_runner/src/stormComponents/StormDataSource.java @@ -29,8 +29,8 @@ import operators.ChainOperator; import operators.DistinctOperator; import operators.Operator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ProjectOperator; +import operators.SelectOperator; import utilities.SystemParameters; import org.apache.log4j.Logger; @@ -80,10 +80,7 @@ public StormDataSource(String componentName, String inputPath, List<Integer> hashIndexes, List<ValueExpression> hashExpressions, - SelectionOperator selection, - DistinctOperator distinct, - ProjectionOperator projection, - AggregateOperator aggregation, + ChainOperator chain, int hierarchyPosition, boolean printOut, long batchOutputMillis, @@ -92,7 +89,7 @@ public StormDataSource(String componentName, TopologyKiller killer, Config conf) { _conf = conf; - _operatorChain = new ChainOperator(selection, distinct, projection, aggregation); + _operatorChain = chain; _hierarchyPosition = hierarchyPosition; _ID=componentName; _componentIndex = String.valueOf(allCompNames.indexOf(componentName)); diff --git a/src/squall_plan_runner/src/stormComponents/StormDstJoin.java b/src/squall_plan_runner/src/stormComponents/StormDstJoin.java index aa9a9976..55e97502 100755 --- a/src/squall_plan_runner/src/stormComponents/StormDstJoin.java +++ b/src/squall_plan_runner/src/stormComponents/StormDstJoin.java @@ -22,8 +22,8 @@ import operators.ChainOperator; import operators.DistinctOperator; import operators.Operator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ProjectOperator; +import operators.SelectOperator; import utilities.SystemParameters; import storage.SquallStorage; @@ -39,7 +39,7 @@ public class StormDstJoin extends BaseRichBolt implements StormJoin, StormCompon private StormEmitter _firstEmitter, _secondEmitter; private SquallStorage _firstSquallStorage, _secondSquallStorage; - private ProjectionOperator _firstPreAggProj, _secondPreAggProj; + private ProjectOperator _firstPreAggProj, _secondPreAggProj; private String _ID; private List<String> _compIds; // a sorted list of all the components private String _componentIndex; //a unique index in a list of all the components @@ -79,14 +79,11 @@ public StormDstJoin(StormEmitter firstEmitter, StormEmitter secondEmitter, String componentName, List<String> allCompNames, - SelectionOperator selection, - DistinctOperator distinct, - ProjectionOperator projection, - AggregateOperator aggregation, + ChainOperator chain, SquallStorage firstPreAggStorage, SquallStorage secondPreAggStorage, - ProjectionOperator firstPreAggProj, - ProjectionOperator secondPreAggProj, + ProjectOperator firstPreAggProj, + ProjectOperator secondPreAggProj, List<Integer> hashIndexes, List<ValueExpression> hashExpressions, int hierarchyPosition, @@ -111,7 +108,7 @@ public StormDstJoin(StormEmitter firstEmitter, // throw new RuntimeException(_componentName + ": Distinct operator cannot be specified for multiThreaded bolts!"); // } - _operatorChain = new ChainOperator(selection, distinct, projection, aggregation); + _operatorChain = chain; _hashIndexes = hashIndexes; _hashExpressions = hashExpressions; @@ -165,7 +162,7 @@ public void execute(Tuple stormTupleRcv) { boolean isFromFirstEmitter = false; SquallStorage affectedStorage, oppositeStorage; - ProjectionOperator projPreAgg; + ProjectOperator projPreAgg; if(_firstEmitterIndex.equals(inputComponentIndex)){ //R update isFromFirstEmitter = true; @@ -201,7 +198,7 @@ protected void performJoin(Tuple stormTupleRcv, String inputTupleHash, boolean isFromFirstEmitter, SquallStorage oppositeStorage, - ProjectionOperator projPreAgg){ + ProjectOperator projPreAgg){ List<String> oppositeStringTupleList = (ArrayList<String>)oppositeStorage.get(inputTupleHash); diff --git a/src/squall_plan_runner/src/stormComponents/StormOperator.java b/src/squall_plan_runner/src/stormComponents/StormOperator.java index ce72ff6e..658a4c06 100755 --- a/src/squall_plan_runner/src/stormComponents/StormOperator.java +++ b/src/squall_plan_runner/src/stormComponents/StormOperator.java @@ -25,8 +25,8 @@ import operators.ChainOperator; import operators.DistinctOperator; import operators.Operator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ProjectOperator; +import operators.SelectOperator; import org.apache.log4j.Logger; import stormComponents.synchronization.TopologyKiller; import utilities.MyUtilities; @@ -69,10 +69,7 @@ public class StormOperator extends BaseRichBolt implements StormEmitter, StormCo public StormOperator(StormEmitter emitter, String componentName, List<String> allCompNames, - SelectionOperator selection, - DistinctOperator distinct, - ProjectionOperator projection, - AggregateOperator aggregation, + ChainOperator chain, List<Integer> hashIndexes, List<ValueExpression> hashExpressions, int hierarchyPosition, @@ -94,7 +91,7 @@ public StormOperator(StormEmitter emitter, // if(parallelism > 1 && distinct != null){ // throw new RuntimeException(_componentName + ": Distinct operator cannot be specified for multiThreaded bolts!"); // } - _operatorChain = new ChainOperator(selection, distinct, projection, aggregation); + _operatorChain = chain; _hashIndexes = hashIndexes; _hashExpressions = hashExpressions; diff --git a/src/squall_plan_runner/src/stormComponents/StormRandomDataSource.java b/src/squall_plan_runner/src/stormComponents/StormRandomDataSource.java index d3f99d42..41167fec 100644 --- a/src/squall_plan_runner/src/stormComponents/StormRandomDataSource.java +++ b/src/squall_plan_runner/src/stormComponents/StormRandomDataSource.java @@ -27,8 +27,8 @@ import operators.ChainOperator; import operators.DistinctOperator; import operators.Operator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ProjectOperator; +import operators.SelectOperator; import utilities.SystemParameters; import org.apache.log4j.Logger; @@ -91,9 +91,9 @@ public StormRandomDataSource(String componentName, String inputPath, List<Integer> hashIndexes, List<ValueExpression> hashExpressions, - SelectionOperator selection, + SelectOperator selection, DistinctOperator distinct, - ProjectionOperator projection, + ProjectOperator projection, AggregateOperator aggregation, int hierarchyPosition, boolean printOut, diff --git a/src/squall_plan_runner/src/stormComponents/StormSrcJoin.java b/src/squall_plan_runner/src/stormComponents/StormSrcJoin.java index 22dd9828..98a40c23 100755 --- a/src/squall_plan_runner/src/stormComponents/StormSrcJoin.java +++ b/src/squall_plan_runner/src/stormComponents/StormSrcJoin.java @@ -8,9 +8,8 @@ import expressions.ValueExpression; import java.io.Serializable; import java.util.List; -import operators.AggregateOperator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ChainOperator; +import operators.ProjectOperator; import org.apache.log4j.Logger; @@ -30,13 +29,11 @@ public StormSrcJoin(StormEmitter firstEmitter, StormEmitter secondEmitter, String componentName, List<String> allCompNames, - SelectionOperator selection, - ProjectionOperator projection, - AggregateOperator aggregation, + ChainOperator chain, SquallStorage firstPreAggStorage, SquallStorage secondPreAggStorage, - ProjectionOperator firstPreAggProj, - ProjectionOperator secondPreAggProj, + ProjectOperator firstPreAggProj, + ProjectOperator secondPreAggProj, List<Integer> hashIndexes, List<ValueExpression> hashExpressions, int hierarchyPosition, @@ -66,9 +63,7 @@ public StormSrcJoin(StormEmitter firstEmitter, _harmonizer, joinParams, true, - selection, - projection, - aggregation, + chain, firstPreAggStorage, firstPreAggProj, hashIndexes, @@ -86,9 +81,7 @@ public StormSrcJoin(StormEmitter firstEmitter, _harmonizer, joinParams, false, - selection, - projection, - aggregation, + chain, secondPreAggStorage, secondPreAggProj, hashIndexes, diff --git a/src/squall_plan_runner/src/stormComponents/StormSrcStorage.java b/src/squall_plan_runner/src/stormComponents/StormSrcStorage.java index 7a5e40cd..9ae9bc26 100755 --- a/src/squall_plan_runner/src/stormComponents/StormSrcStorage.java +++ b/src/squall_plan_runner/src/stormComponents/StormSrcStorage.java @@ -21,8 +21,8 @@ import operators.AggregateOperator; import operators.ChainOperator; import operators.Operator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ProjectOperator; +import operators.SelectOperator; import utilities.SystemParameters; import storage.SquallStorage; @@ -49,7 +49,7 @@ public class StormSrcStorage extends BaseRichBolt implements StormEmitter, Storm private ChainOperator _operatorChain; private SquallStorage _joinStorage; - private ProjectionOperator _preAggProj; + private ProjectOperator _preAggProj; private StormSrcHarmonizer _harmonizer; private OutputCollector _collector; @@ -75,11 +75,9 @@ public StormSrcStorage(StormEmitter firstEmitter, StormSrcHarmonizer harmonizer, List<Integer> joinParams, boolean isFromFirstEmitter, - SelectionOperator selection, - ProjectionOperator projection, - AggregateOperator aggregation, + ChainOperator chain, SquallStorage preAggStorage, - ProjectionOperator preAggProj, + ProjectOperator preAggProj, List<Integer> hashIndexes, List<ValueExpression> hashExpressions, int hierarchyPosition, @@ -101,7 +99,7 @@ public StormSrcStorage(StormEmitter firstEmitter, _harmonizer = harmonizer; _batchOutputMillis = batchOutputMillis; - _operatorChain = new ChainOperator(selection, projection, aggregation); + _operatorChain = chain; _hashIndexes=hashIndexes; _hashExpressions = hashExpressions; _hierarchyPosition=hierarchyPosition; diff --git a/src/squall_plan_runner/src/stormComponents/StormThetaJoin.java b/src/squall_plan_runner/src/stormComponents/StormThetaJoin.java index 3b659b94..2ef9ae65 100644 --- a/src/squall_plan_runner/src/stormComponents/StormThetaJoin.java +++ b/src/squall_plan_runner/src/stormComponents/StormThetaJoin.java @@ -28,8 +28,8 @@ import operators.ChainOperator; import operators.DistinctOperator; import operators.Operator; -import operators.ProjectionOperator; -import operators.SelectionOperator; +import operators.ProjectOperator; +import operators.SelectOperator; import utilities.SystemParameters; import storage.TupleStorage; @@ -93,10 +93,7 @@ public StormThetaJoin(StormEmitter firstEmitter, StormEmitter secondEmitter, String componentName, List<String> allCompNames, - SelectionOperator selection, - DistinctOperator distinct, - ProjectionOperator projection, - AggregateOperator aggregation, + ChainOperator chain, List<Integer> hashIndexes, List<ValueExpression> hashExpressions, Predicate joinPredicate, @@ -125,7 +122,7 @@ public StormThetaJoin(StormEmitter firstEmitter, // throw new RuntimeException(_componentName + ": Distinct operator cannot be specified for multiThreaded bolts!"); // } - _operatorChain = new ChainOperator(selection, distinct, projection, aggregation); + _operatorChain = chain; _hashIndexes = hashIndexes; _hashExpressions = hashExpressions; diff --git a/src/squall_plan_runner/src/utilities/MyUtilities.java b/src/squall_plan_runner/src/utilities/MyUtilities.java index f1aba51d..9ceec5d2 100755 --- a/src/squall_plan_runner/src/utilities/MyUtilities.java +++ b/src/squall_plan_runner/src/utilities/MyUtilities.java @@ -18,7 +18,6 @@ import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Map; diff --git a/src/squall_plan_runner/src/visitors/OperatorVisitor.java b/src/squall_plan_runner/src/visitors/OperatorVisitor.java new file mode 100644 index 00000000..9ea40edd --- /dev/null +++ b/src/squall_plan_runner/src/visitors/OperatorVisitor.java @@ -0,0 +1,27 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package visitors; + +import operators.AggregateOperator; +import operators.DistinctOperator; +import operators.Operator; +import operators.ProjectOperator; +import operators.SelectOperator; + + +public interface OperatorVisitor { + + public void visit(SelectOperator selection); + + public void visit(DistinctOperator distinct); + + public void visit(ProjectOperator projection); + + public void visit(AggregateOperator aggregation); + + public void visit(Operator operator); + +}
e948e9e92e5a88f165d35bfe2fb0fd19b04fd103
Vala
gtk+-2.0: Add many missing type arguments Partially fixes bug 609875.
c
https://github.com/GNOME/vala/
diff --git a/vapi/gtk+-2.0.vapi b/vapi/gtk+-2.0.vapi index c4a0e72749..d9446367d5 100644 --- a/vapi/gtk+-2.0.vapi +++ b/vapi/gtk+-2.0.vapi @@ -158,7 +158,7 @@ namespace Gtk { public unowned string get_icon_name (); public bool get_is_important (); public unowned string get_label (); - public unowned GLib.SList get_proxies (); + public unowned GLib.SList<Gtk.Widget> get_proxies (); public bool get_sensitive (); public unowned string get_short_label (); public unowned string get_stock_id (); @@ -218,7 +218,7 @@ namespace Gtk { public virtual unowned Gtk.Action get_action (string action_name); public bool get_sensitive (); public bool get_visible (); - public unowned GLib.List list_actions (); + public GLib.List<weak Gtk.Action> list_actions (); public void remove_action (Gtk.Action action); public void set_sensitive (bool sensitive); public void set_translate_func (Gtk.TranslateFunc func, void* data, GLib.DestroyNotify notify); @@ -373,21 +373,18 @@ namespace Gtk { public weak Gtk.BindingEntry set_next; public weak Gtk.BindingSignal signals; public static void add_signal (Gtk.BindingSet binding_set, uint keyval, Gdk.ModifierType modifiers, string signal_name, uint n_args); - public static void add_signall (Gtk.BindingSet binding_set, uint keyval, Gdk.ModifierType modifiers, string signal_name, GLib.SList binding_args); + public static void add_signall (Gtk.BindingSet binding_set, uint keyval, Gdk.ModifierType modifiers, string signal_name, GLib.SList<Gtk.BindingArg> binding_args); public static void remove (Gtk.BindingSet binding_set, uint keyval, Gdk.ModifierType modifiers); public static void skip (Gtk.BindingSet binding_set, uint keyval, Gdk.ModifierType modifiers); } [Compact] [CCode (cheader_filename = "gtk/gtk.h")] public class BindingSet { - public weak GLib.SList class_branch_pspecs; public weak Gtk.BindingEntry current; public weak Gtk.BindingEntry entries; public uint parsed; public int priority; public weak string set_name; - public weak GLib.SList widget_class_pspecs; - public weak GLib.SList widget_path_pspecs; [CCode (has_construct_function = false)] public BindingSet (string set_name); public bool activate (uint keyval, Gdk.ModifierType modifiers, Gtk.Object object); @@ -405,7 +402,7 @@ namespace Gtk { } [CCode (cheader_filename = "gtk/gtk.h")] public class Box : Gtk.Container, Atk.Implementor, Gtk.Buildable, Gtk.Orientable { - public weak GLib.List children; + public weak GLib.List<Gtk.Widget> children; public bool get_homogeneous (); public int get_spacing (); public void pack_end (Gtk.Widget child, bool expand, bool fill, uint padding); @@ -440,7 +437,7 @@ namespace Gtk { public void connect_signals_full (Gtk.BuilderConnectFunc func); public static GLib.Quark error_quark (); public unowned GLib.Object get_object (string name); - public unowned GLib.SList get_objects (); + public GLib.SList<weak GLib.Object> get_objects (); public unowned string get_translation_domain (); public virtual GLib.Type get_type_from_name (string type_name); public void set_translation_domain (string domain); @@ -1075,7 +1072,7 @@ namespace Gtk { [NoWrapper] public virtual void get_child_property (Gtk.Widget child, uint property_id, GLib.Value value, GLib.ParamSpec pspec); public GLib.List<weak Gtk.Widget> get_children (); - public bool get_focus_chain (GLib.List focusable_widgets); + public bool get_focus_chain (out GLib.List<Gtk.Widget> focusable_widgets); public unowned Gtk.Widget get_focus_child (); public unowned Gtk.Adjustment get_focus_hadjustment (); public unowned Gtk.Adjustment get_focus_vadjustment (); @@ -1087,7 +1084,7 @@ namespace Gtk { public void set_border_width (uint border_width); [NoWrapper] public virtual void set_child_property (Gtk.Widget child, uint property_id, GLib.Value value, GLib.ParamSpec pspec); - public void set_focus_chain (GLib.List focusable_widgets); + public void set_focus_chain (GLib.List<Gtk.Widget> focusable_widgets); public void set_focus_hadjustment (Gtk.Adjustment adjustment); public void set_focus_vadjustment (Gtk.Adjustment adjustment); public void set_reallocate_redraws (bool needs_redraws); @@ -1499,7 +1496,7 @@ namespace Gtk { } [CCode (cheader_filename = "gtk/gtk.h")] public class Fixed : Gtk.Container, Atk.Implementor, Gtk.Buildable { - public weak GLib.List children; + public weak GLib.List<Gtk.Widget> children; [CCode (type = "GtkWidget*", has_construct_function = false)] public Fixed (); public bool get_has_window (); @@ -1839,8 +1836,8 @@ namespace Gtk { public int get_icon_sizes (string icon_name); public void get_search_path (string path, int n_elements); public bool has_icon (string icon_name); - public unowned GLib.List list_contexts (); - public unowned GLib.List list_icons (string context); + public GLib.List<string> list_contexts (); + public GLib.List<string> list_icons (string context); public unowned Gdk.Pixbuf load_icon (string icon_name, int size, Gtk.IconLookupFlags flags) throws GLib.Error; public Gtk.IconInfo lookup_by_gicon (GLib.Icon icon, int size, Gtk.IconLookupFlags flags); public Gtk.IconInfo lookup_icon (string icon_name, int size, Gtk.IconLookupFlags flags); @@ -2223,7 +2220,7 @@ namespace Gtk { [CCode (cheader_filename = "gtk/gtk.h")] public class Layout : Gtk.Container, Atk.Implementor, Gtk.Buildable { public weak Gdk.Window bin_window; - public weak GLib.List children; + public weak GLib.List<Gtk.Widget> children; public uint freeze_count; public int scroll_x; public int scroll_y; @@ -2339,7 +2336,7 @@ namespace Gtk { public unowned string get_accel_path (); public unowned Gtk.Widget get_active (); public unowned Gtk.Widget get_attach_widget (); - public static unowned GLib.List get_for_attach_widget (Gtk.Widget widget); + public static unowned GLib.List<Gtk.Menu> get_for_attach_widget (Gtk.Widget widget); public int get_monitor (); public bool get_reserve_toggle_size (); public bool get_tearoff_state (); @@ -2734,7 +2731,7 @@ namespace Gtk { public unowned string get_display_name (); public double get_height (Gtk.Unit unit); public unowned string get_name (); - public static unowned GLib.List get_paper_sizes (bool include_custom); + public static GLib.List<Gtk.PaperSize> get_paper_sizes (bool include_custom); public unowned string get_ppd_name (); public double get_width (Gtk.Unit unit); public bool is_custom (); @@ -2968,9 +2965,9 @@ namespace Gtk { [CCode (has_construct_function = false)] public RadioAction (string name, string? label, string? tooltip, string? stock_id, int value); public int get_current_value (); - public unowned GLib.SList get_group (); + public unowned GLib.SList<Gtk.RadioAction> get_group (); public void set_current_value (int current_value); - public void set_group (GLib.SList group); + public void set_group (GLib.SList<Gtk.RadioAction> group); public int current_value { get; set; } public Gtk.RadioAction group { set; } [NoAccessorMethod] @@ -2980,17 +2977,17 @@ namespace Gtk { [CCode (cheader_filename = "gtk/gtk.h")] public class RadioButton : Gtk.CheckButton, Atk.Implementor, Gtk.Buildable, Gtk.Activatable { [CCode (type = "GtkWidget*", has_construct_function = false)] - public RadioButton (GLib.SList? group); + public RadioButton (GLib.SList<Gtk.RadioButton>? group); [CCode (type = "GtkWidget*", has_construct_function = false)] public RadioButton.from_widget (Gtk.RadioButton radio_group_member); - public unowned GLib.SList get_group (); - public void set_group (GLib.SList group); + public unowned GLib.SList<Gtk.RadioButton> get_group (); + public void set_group (GLib.SList<Gtk.RadioButton> group); [CCode (type = "GtkWidget*", has_construct_function = false)] - public RadioButton.with_label (GLib.SList? group, string label); + public RadioButton.with_label (GLib.SList<Gtk.RadioButton>? group, string label); [CCode (type = "GtkWidget*", has_construct_function = false)] public RadioButton.with_label_from_widget (Gtk.RadioButton radio_group_member, string label); [CCode (type = "GtkWidget*", has_construct_function = false)] - public RadioButton.with_mnemonic (GLib.SList? group, string label); + public RadioButton.with_mnemonic (GLib.SList<Gtk.RadioButton>? group, string label); [CCode (type = "GtkWidget*", has_construct_function = false)] public RadioButton.with_mnemonic_from_widget (Gtk.RadioButton radio_group_member, string label); public Gtk.RadioButton group { set; } @@ -2999,17 +2996,17 @@ namespace Gtk { [CCode (cheader_filename = "gtk/gtk.h")] public class RadioMenuItem : Gtk.CheckMenuItem, Atk.Implementor, Gtk.Buildable, Gtk.Activatable { [CCode (type = "GtkWidget*", has_construct_function = false)] - public RadioMenuItem (GLib.SList group); + public RadioMenuItem (GLib.SList<Gtk.RadioMenuItem> group); [CCode (type = "GtkWidget*", has_construct_function = false)] public RadioMenuItem.from_widget (Gtk.RadioMenuItem group); - public unowned GLib.SList get_group (); - public void set_group (GLib.SList group); + public unowned GLib.SList<Gtk.RadioMenuItem> get_group (); + public void set_group (GLib.SList<Gtk.RadioMenuItem> group); [CCode (type = "GtkWidget*", has_construct_function = false)] - public RadioMenuItem.with_label (GLib.SList group, string label); + public RadioMenuItem.with_label (GLib.SList<Gtk.RadioMenuItem> group, string label); [CCode (type = "GtkWidget*", has_construct_function = false)] public RadioMenuItem.with_label_from_widget (Gtk.RadioMenuItem group, string label); [CCode (type = "GtkWidget*", has_construct_function = false)] - public RadioMenuItem.with_mnemonic (GLib.SList group, string label); + public RadioMenuItem.with_mnemonic (GLib.SList<Gtk.RadioMenuItem> group, string label); [CCode (type = "GtkWidget*", has_construct_function = false)] public RadioMenuItem.with_mnemonic_from_widget (Gtk.RadioMenuItem group, string label); public Gtk.RadioMenuItem group { set; } @@ -3018,16 +3015,16 @@ namespace Gtk { [CCode (cheader_filename = "gtk/gtk.h")] public class RadioToolButton : Gtk.ToggleToolButton, Atk.Implementor, Gtk.Buildable, Gtk.Activatable { [CCode (type = "GtkToolItem*", has_construct_function = false)] - public RadioToolButton (GLib.SList? group); + public RadioToolButton (GLib.SList<Gtk.RadioToolButton>? group); [CCode (type = "GtkToolItem*", has_construct_function = false)] - public RadioToolButton.from_stock (GLib.SList group, string stock_id); + public RadioToolButton.from_stock (GLib.SList<Gtk.RadioToolButton>? group, string stock_id); [CCode (type = "GtkToolItem*", has_construct_function = false)] public RadioToolButton.from_widget (Gtk.RadioToolButton group); - public unowned GLib.SList get_group (); - public void set_group (GLib.SList group); + public unowned GLib.SList<Gtk.RadioToolButton> get_group (); + public void set_group (GLib.SList<Gtk.RadioToolButton> group); [CCode (type = "GtkToolItem*", has_construct_function = false)] public RadioToolButton.with_stock_from_widget (Gtk.RadioToolButton group, string stock_id); - public Gtk.RadioToolButton group { set; } + public Gtk.RadioToolButton<Gtk.RadioMenuItem> group { set; } } [CCode (cheader_filename = "gtk/gtk.h")] public class Range : Gtk.Widget, Atk.Implementor, Gtk.Buildable, Gtk.Orientable { @@ -3250,7 +3247,7 @@ namespace Gtk { public bool add_item (string uri); public static GLib.Quark error_quark (); public static unowned Gtk.RecentManager get_default (); - public unowned GLib.List get_items (); + public GLib.List<Gtk.RecentInfo> get_items (); public int get_limit (); public bool has_item (string uri); public unowned Gtk.RecentInfo lookup_item (string uri) throws GLib.Error; @@ -3445,7 +3442,7 @@ namespace Gtk { public void set_property_value (string name, Gtk.SettingsValue svalue); public void set_string_property (string name, string v_string, string origin); [NoAccessorMethod] - public GLib.HashTable color_hash { owned get; } + public GLib.HashTable<string,Gdk.Color> color_hash { owned get; } [NoAccessorMethod] public bool gtk_alternative_button_order { get; set; } [NoAccessorMethod] @@ -3570,7 +3567,7 @@ namespace Gtk { public void add_widget (Gtk.Widget widget); public bool get_ignore_hidden (); public Gtk.SizeGroupMode get_mode (); - public unowned GLib.SList get_widgets (); + public unowned GLib.SList<Gtk.Widget> get_widgets (); public void remove_widget (Gtk.Widget widget); public void set_ignore_hidden (bool ignore_hidden); public void set_mode (Gtk.SizeGroupMode mode); @@ -3925,7 +3922,7 @@ namespace Gtk { [Compact] [CCode (ref_function = "gtk_target_list_ref", unref_function = "gtk_target_list_unref", type_id = "GTK_TYPE_TARGET_LIST", cheader_filename = "gtk/gtk.h")] public class TargetList { - public weak GLib.List list; + public weak GLib.List<Gtk.TargetPair> list; public uint ref_count; [CCode (has_construct_function = false)] public TargetList (Gtk.TargetEntry[] targets); @@ -4116,7 +4113,7 @@ namespace Gtk { [CCode (has_construct_function = false)] public TextChildAnchor (); public bool get_deleted (); - public unowned GLib.List get_widgets (); + public GLib.List<weak Gtk.Widget> get_widgets (); } [Compact] [CCode (cheader_filename = "gtk/gtk.h")] @@ -4994,9 +4991,9 @@ namespace Gtk { public void ensure_update (); public unowned Gtk.AccelGroup get_accel_group (); public virtual unowned Gtk.Action get_action (string path); - public unowned GLib.List get_action_groups (); + public unowned GLib.List<Gtk.ActionGroup> get_action_groups (); public bool get_add_tearoffs (); - public unowned GLib.SList get_toplevels (Gtk.UIManagerItemType types); + public GLib.SList<weak Gtk.Widget> get_toplevels (Gtk.UIManagerItemType types); public unowned string get_ui (); public virtual unowned Gtk.Widget get_widget (string path); public void insert_action_group (Gtk.ActionGroup action_group, int pos); @@ -5173,8 +5170,8 @@ namespace Gtk { public bool is_sensitive (); [CCode (cname = "GTK_WIDGET_TOPLEVEL")] public bool is_toplevel (); - public unowned GLib.List list_accel_closures (); - public unowned GLib.List list_mnemonic_labels (); + public GLib.List<GLib.Closure> list_accel_closures (); + public GLib.List<weak Gtk.Widget> list_mnemonic_labels (); [CCode (cname = "gtk_widget_class_list_style_properties")] public class unowned GLib.ParamSpec list_style_properties (uint n_properties); public void modify_base (Gtk.StateType state, Gdk.Color? color); @@ -5417,7 +5414,7 @@ namespace Gtk { public void fullscreen (); public bool get_accept_focus (); public bool get_decorated (); - public static unowned GLib.List get_default_icon_list (); + public static GLib.List<weak Gdk.Pixbuf> get_default_icon_list (); public static unowned string get_default_icon_name (); public void get_default_size (out int width, out int height); public unowned Gtk.Widget get_default_widget (); @@ -5430,7 +5427,7 @@ namespace Gtk { public unowned Gtk.WindowGroup get_group (); public bool get_has_frame (); public unowned Gdk.Pixbuf get_icon (); - public unowned GLib.List get_icon_list (); + public GLib.List<weak Gdk.Pixbuf> get_icon_list (); public unowned string get_icon_name (); public Gdk.ModifierType get_mnemonic_modifier (); public bool get_modal (); @@ -5447,7 +5444,7 @@ namespace Gtk { public Gdk.WindowTypeHint get_type_hint (); public bool get_urgency_hint (); public void iconify (); - public static unowned GLib.List list_toplevels (); + public static GLib.List<weak Gtk.Window> list_toplevels (); public void maximize (); public bool mnemonic_activate (uint keyval, Gdk.ModifierType modifier); public void move (int x, int y); @@ -5468,7 +5465,7 @@ namespace Gtk { public void set_default (Gtk.Widget default_widget); public static void set_default_icon (Gdk.Pixbuf icon); public static bool set_default_icon_from_file (string filename) throws GLib.Error; - public static void set_default_icon_list (GLib.List list); + public static void set_default_icon_list (GLib.List<Gdk.Pixbuf> list); public static void set_default_icon_name (string name); public void set_default_size (int width, int height); public void set_deletable (bool setting); @@ -5480,7 +5477,7 @@ namespace Gtk { public void set_has_frame (bool setting); public void set_icon (Gdk.Pixbuf icon); public bool set_icon_from_file (string filename) throws GLib.Error; - public void set_icon_list (GLib.List list); + public void set_icon_list (GLib.List<Gdk.Pixbuf> list); public void set_icon_name (string name); public void set_keep_above (bool setting); public void set_keep_below (bool setting); @@ -5556,7 +5553,7 @@ namespace Gtk { [CCode (has_construct_function = false)] public WindowGroup (); public void add_window (Gtk.Window window); - public unowned GLib.List list_windows (); + public GLib.List<weak Gtk.Window> list_windows (); public void remove_window (Gtk.Window window); } [CCode (cheader_filename = "gtk/gtk.h")] @@ -5595,7 +5592,7 @@ namespace Gtk { public abstract void add_attribute (Gtk.CellRenderer cell, string attribute, int column); public abstract void clear (); public abstract void clear_attributes (Gtk.CellRenderer cell); - public abstract unowned GLib.List get_cells (); + public abstract GLib.List<weak Gtk.CellRenderer> get_cells (); public abstract void pack_end (Gtk.CellRenderer cell, bool expand); public abstract void pack_start (Gtk.CellRenderer cell, bool expand); public abstract void reorder (Gtk.CellRenderer cell, int position); @@ -5655,9 +5652,9 @@ namespace Gtk { public string get_uri (); public GLib.SList<string> get_uris (); public bool get_use_preview_label (); - public unowned GLib.SList list_filters (); - public unowned GLib.SList list_shortcut_folder_uris (); - public unowned GLib.SList list_shortcut_folders (); + public GLib.SList<weak Gtk.FileFilter> list_filters (); + public GLib.SList<string>? list_shortcut_folder_uris (); + public GLib.SList<string>? list_shortcut_folders (); public void remove_filter (Gtk.FileFilter filter); public bool remove_shortcut_folder (string folder) throws GLib.Error; public bool remove_shortcut_folder_uri (string uri) throws GLib.Error; @@ -5728,7 +5725,7 @@ namespace Gtk { public unowned Gtk.RecentInfo get_current_item (); public abstract unowned string get_current_uri (); public unowned Gtk.RecentFilter get_filter (); - public abstract unowned GLib.List get_items (); + public abstract GLib.List<Gtk.RecentInfo> get_items (); public int get_limit (); public bool get_local_only (); [NoWrapper] @@ -5740,7 +5737,7 @@ namespace Gtk { public bool get_show_tips (); public Gtk.RecentSortType get_sort_type (); public unowned string get_uris (size_t length); - public abstract unowned GLib.SList list_filters (); + public abstract GLib.SList<weak Gtk.RecentFilter> list_filters (); public abstract void remove_filter (Gtk.RecentFilter filter); public abstract void select_all (); public abstract bool select_uri (string uri) throws GLib.Error; @@ -5981,13 +5978,13 @@ namespace Gtk { public int get_line (); public int get_line_index (); public int get_line_offset (); - public unowned GLib.SList get_marks (); + public GLib.SList<weak Gtk.TextMark> get_marks (); public int get_offset (); public unowned Gdk.Pixbuf get_pixbuf (); public unowned string get_slice (Gtk.TextIter end); - public unowned GLib.SList get_tags (); + public GLib.SList<weak Gtk.TextTag> get_tags (); public unowned string get_text (Gtk.TextIter end); - public unowned GLib.SList get_toggled_tags (bool toggled_on); + public GLib.SList<weak Gtk.TextTag> get_toggled_tags (bool toggled_on); public int get_visible_line_index (); public int get_visible_line_offset (); public unowned string get_visible_slice (Gtk.TextIter end); @@ -7422,7 +7419,7 @@ namespace Gtk { [CCode (cheader_filename = "gtk/gtk.h")] public static bool accel_groups_activate (GLib.Object object, uint accel_key, Gdk.ModifierType accel_mods); [CCode (cheader_filename = "gtk/gtk.h")] - public static unowned GLib.SList accel_groups_from_object (GLib.Object object); + public static unowned GLib.SList<Gtk.AccelGroup> accel_groups_from_object (GLib.Object object); [CCode (cheader_filename = "gtk/gtk.h")] public static uint accelerator_get_default_mod_mask (); [CCode (cheader_filename = "gtk/gtk.h")] @@ -7708,7 +7705,7 @@ namespace Gtk { [CCode (cheader_filename = "gtk/gtk.h")] public static void stock_add_static (Gtk.StockItem[] items); [CCode (cheader_filename = "gtk/gtk.h")] - public static unowned GLib.SList stock_list_ids (); + public static GLib.SList<string> stock_list_ids (); [CCode (cheader_filename = "gtk/gtk.h")] public static bool stock_lookup (string stock_id, Gtk.StockItem item); [CCode (cheader_filename = "gtk/gtk.h")] diff --git a/vapi/packages/gtk+-2.0/gtk+-2.0-custom.vala b/vapi/packages/gtk+-2.0/gtk+-2.0-custom.vala index 3eeb798293..8e2d3085be 100644 --- a/vapi/packages/gtk+-2.0/gtk+-2.0-custom.vala +++ b/vapi/packages/gtk+-2.0/gtk+-2.0-custom.vala @@ -29,7 +29,6 @@ namespace Gtk { } public class Container { - public GLib.List<weak Gtk.Widget> get_children (); [CCode (vfunc_name = "forall")] public virtual void forall_internal(bool include_internal, Gtk.Callback callback); } @@ -43,10 +42,6 @@ namespace Gtk { public void position_menu (Gtk.Menu menu, out int x, out int y, out bool push_in); } - public class TreeView { - public GLib.List<weak Gtk.TreeViewColumn> get_columns (); - } - public class UIManager { public uint new_merge_id (); } diff --git a/vapi/packages/gtk+-2.0/gtk+-2.0.metadata b/vapi/packages/gtk+-2.0/gtk+-2.0.metadata index 7c4920ed54..59db8f1397 100644 --- a/vapi/packages/gtk+-2.0/gtk+-2.0.metadata +++ b/vapi/packages/gtk+-2.0/gtk+-2.0.metadata @@ -10,8 +10,10 @@ gtk_about_dialog_set_url_hook.func transfer_ownership="1" gtk_about_dialog_set_url_hook.data hidden="1" gtk_about_dialog_set_url_hook.destroy hidden="1" gtk_about_dialog_set_url_hook type_name="void" +gtk_accel_groups_from_object type_arguments="AccelGroup" gtk_accelerator_parse.accelerator_key is_out="1" gtk_accelerator_parse.accelerator_mods is_out="1" +gtk_action_get_proxies type_arguments="Widget" gtk_action_new.label nullable="1" gtk_action_new.tooltip nullable="1" gtk_action_new.stock_id nullable="1" @@ -28,6 +30,7 @@ gtk_action_group_add_radio_actions_full.destroy nullable="1" gtk_action_group_add_toggle_actions.user_data hidden="0" gtk_action_group_add_toggle_actions_full.user_data hidden="0" gtk_action_group_add_toggle_actions_full.destroy nullable="1" +gtk_action_group_list_actions transfer_ownership="1" type_arguments="unowned Action" GtkAdjustment::changed has_emitter="1" GtkAdjustment::value_changed has_emitter="1" gtk_alignment_get_padding.padding_top is_out="1" @@ -43,7 +46,12 @@ gtk_assistant_set_forward_page_func.page_func transfer_ownership="1" gtk_assistant_set_forward_page_func.data hidden="1" gtk_assistant_set_forward_page_func.destroy hidden="1" GtkBindingArg.d hidden="1" +gtk_binding_entry_add_signall.binding_args type_arguments="BindingArg" +GtkBindingSet.class_branch_pspecs hidden="1" +GtkBindingSet.widget_class_pspecs hidden="1" +GtkBindingSet.widget_path_pspecs hidden="1" GtkBorder is_value_type="1" +GtkBox.children type_arguments="Widget" gtk_box_query_child_packing.expand is_out="1" gtk_box_query_child_packing.fill is_out="1" gtk_box_query_child_packing.padding is_out="1" @@ -57,6 +65,7 @@ gtk_buildable_custom_tag_start.parser is_out="1" gtk_buildable_custom_tag_start.data is_out="1" gtk_builder_add_objects_from_file.object_ids no_array_length="1" is_array="1" gtk_builder_add_objects_from_string.object_ids no_array_length="1" is_array="1" +gtk_builder_get_objects transfer_ownership="1" type_arguments="unowned GLib.Object" GtkBuilderError errordomain="1" gtk_button_get_alignment.xalign is_out="1" gtk_button_get_alignment.yalign is_out="1" @@ -77,6 +86,7 @@ GtkCell.u hidden="1" GtkCellEditable::editing_done has_emitter="1" GtkCellEditable::remove_widget has_emitter="1" GtkCellEditable::start_editing has_emitter="1" +gtk_cell_layout_get_cells transfer_ownership="1" type_arguments="unowned CellRenderer" gtk_cell_layout_set_attributes ellipsis="1" gtk_cell_layout_set_cell_data_func.func transfer_ownership="1" gtk_cell_layout_set_cell_data_func.func_data hidden="1" @@ -114,7 +124,9 @@ GtkContainer::remove has_emitter="1" GtkContainer::set_focus_child has_emitter="1" gtk_container_forall.callback_data hidden="1" gtk_container_foreach.callback_data hidden="1" -gtk_container_get_children hidden="1" +gtk_container_get_children transfer_ownership="1" type_arguments="unowned Widget" +gtk_container_get_focus_chain.focusable_widgets is_out="1" takes_ownership="1" type_arguments="Widget" +gtk_container_set_focus_chain.focusable_widgets type_arguments="Widget" GtkContainerClass name="pointer" GtkDestroyNotify has_target="0" gtk_dialog_new_with_buttons.title nullable="1" @@ -155,6 +167,10 @@ gtk_file_chooser_dialog_new.title nullable="1" gtk_file_chooser_dialog_new.parent nullable="1" gtk_file_chooser_dialog_new_with_backend.title nullable="1" gtk_file_chooser_dialog_new_with_backend.parent nullable="1" +gtk_file_chooser_list_filters transfer_ownership="1" type_arguments="unowned FileFilter" +gtk_file_chooser_list_shortcut_folder_uris nullable="1" transfer_ownership="1" type_arguments="string" +gtk_file_chooser_list_shortcut_folders nullable="1" transfer_ownership="1" type_arguments="string" +GtkFixed.children type_arguments="Widget" gtk_frame_new.label nullable="1" GtkHandleBox.child_detached hidden="1" GtkHandleBox::child_detached hidden="1" @@ -174,6 +190,8 @@ gtk_icon_view_get_tooltip_context.y is_out="1" gtk_icon_view_get_selected_items transfer_ownership="1" type_arguments="TreePath" gtk_icon_set_copy transfer_ownership="1" gtk_icon_source_copy transfer_ownership="1" +gtk_icon_theme_list_contexts transfer_ownership="1" type_arguments="string" +gtk_icon_theme_list_icons transfer_ownership="1" type_arguments="string" gtk_icon_theme_lookup_icon transfer_ownership="1" gtk_icon_theme_choose_icon transfer_ownership="1" gtk_icon_theme_lookup_by_gicon transfer_ownership="1" @@ -207,6 +225,7 @@ GtkLabel.text hidden="1" gtk_label_new.str nullable="1" GtkList::select_child has_emitter="1" GtkList::unselect_child has_emitter="1" +GtkLayout.children type_arguments="Widget" gtk_layout_get_size.width is_out="1" gtk_layout_get_size.height is_out="1" gtk_list_store_new ellipsis="1" @@ -235,6 +254,7 @@ gtk_link_button_set_uri_hook.func transfer_ownership="1" gtk_link_button_set_uri_hook.data hidden="1" gtk_link_button_set_uri_hook.destroy hidden="1" gtk_link_button_set_uri_hook type_name="void" +gtk_menu_get_for_attach_widget type_arguments="Menu" gtk_menu_popup.data hidden="1" gtk_menu_popup.func nullable="1" gtk_menu_popup.parent_menu_shell nullable="1" @@ -345,6 +365,7 @@ gtk_paint_vline.area nullable="1" gtk_paint_vline.widget nullable="1" gtk_paint_vline.detail nullable="1" gtk_paper_size_copy transfer_ownership="1" +gtk_paper_size_get_paper_sizes transfer_ownership="1" type_arguments="PaperSize" GtkPlug::embedded hidden="1" gtk_print_settings_copy transfer_ownership="1" gtk_printer_accepts_pdf hidden="1" experimental="1" @@ -357,11 +378,27 @@ gtk_quit_add_full hidden="1" gtk_radio_action_new.label nullable="1" gtk_radio_action_new.tooltip nullable="1" gtk_radio_action_new.stock_id nullable="1" +gtk_radio_action_get_group type_arguments="RadioAction" +gtk_radio_action_set_group.group type_arguments="RadioAction" GtkRadioActionEntry is_value_type="1" -gtk_radio_button_new.group nullable="1" -gtk_radio_button_new_with_label.group nullable="1" -gtk_radio_button_new_with_mnemonic.group nullable="1" -gtk_radio_tool_button_new.group nullable="1" +gtk_radio_button_get_group type_arguments="RadioButton" +gtk_radio_button_new.group nullable="1" type_arguments="RadioButton" +gtk_radio_button_new_with_label.group nullable="1" type_arguments="RadioButton" +gtk_radio_button_new_with_mnemonic.group nullable="1" type_arguments="RadioButton" +gtk_radio_button_set_group.group type_arguments="RadioButton" +gtk_radio_menu_item_get_group type_arguments="RadioMenuItem" +gtk_radio_menu_item_new.group type_arguments="RadioMenuItem" +gtk_radio_menu_item_new_with_label.group type_arguments="RadioMenuItem" +gtk_radio_menu_item_new_with_mnemonic.group type_arguments="RadioMenuItem" +gtk_radio_menu_item_set_group.group type_arguments="RadioMenuItem" +GtkRadioToolButton:group type_arguments="RadioMenuItem" +gtk_radio_tool_button_get_group type_arguments="RadioToolButton" +gtk_radio_tool_button_new.group nullable="1" type_arguments="RadioToolButton" +gtk_radio_tool_button_new_from_stock.group nullable="1" type_arguments="RadioToolButton" +gtk_radio_tool_button_set_group.group type_arguments="RadioToolButton" +gtk_recent_chooser_get_items transfer_ownership="1" type_arguments="RecentInfo" +gtk_recent_chooser_list_filters transfer_ownership="1" type_arguments="unowned RecentFilter" +gtk_recent_manager_get_items transfer_ownership="1" type_arguments="RecentInfo" GtkRecentData is_value_type="1" has_copy_function="0" has_destroy_function="0" GtkRecentData.display_name weak="0" GtkRecentData.description weak="0" @@ -390,9 +427,11 @@ gtk_selection_data_get_uris is_array="1" transfer_ownership="1" array_null_termi gtk_selection_data_set.length hidden="1" gtk_selection_data_set_uris.uris is_array="1" no_array_length="1" GtkSettings.queued_settings hidden="1" +GtkSettings:color-hash type_arguments="string,Gdk.Color" gtk_show_about_dialog ellipsis="1" gtk_show_about_dialog.parent nullable="1" gtk_show_uri.screen nullable="1" +gtk_size_group_get_widgets type_arguments="Widget" gtk_spin_button_get_range.min is_out="1" gtk_spin_button_get_range.max is_out="1" GtkStatusIcon::button_press_event.event namespace_name="Gdk" type_name="EventButton" @@ -400,6 +439,7 @@ GtkStatusIcon::button_release_event.event namespace_name="Gdk" type_name="EventB gtk_status_icon_get_geometry.area is_out="1" gtk_status_icon_get_geometry.orientation is_out="1" gtk_status_icon_position_menu hidden="1" +gtk_stock_list_ids transfer_ownership="1" type_arguments="string" GtkStockItem is_value_type="1" GtkStyle.fg weak="0" GtkStyle.bg weak="0" @@ -421,10 +461,12 @@ GtkStyle.bg_pixmap weak="0" gtk_style_lookup_color.color is_out="1" GtkTable:row-spacing accessor_method="0" GtkTargetEntry is_value_type="1" +GtkTargetList.list type_arguments="TargetPair" gtk_target_list_add_table.targets is_array="1" gtk_target_list_new.targets is_array="1" gtk_target_list_new.ntargets hidden="1" gtk_text_attributes_copy transfer_ownership="1" +gtk_text_child_anchor_get_widgets transfer_ownership="1" type_arguments="unowned Widget" GtkTextBuffer::apply_tag has_emitter="1" GtkTextBuffer::begin_user_action has_emitter="1" GtkTextBuffer::end_user_action has_emitter="1" @@ -448,6 +490,9 @@ gtk_text_buffer_get_start_iter.iter is_out="1" gtk_text_buffer_paste_clipboard.override_location nullable="1" gtk_text_buffer_new.table nullable="1" GtkTextIter is_value_type="1" +gtk_text_iter_get_marks transfer_ownership="1" type_arguments="unowned TextMark" +gtk_text_iter_get_tags transfer_ownership="1" type_arguments="unowned TextTag" +gtk_text_iter_get_toggled_tags transfer_ownership="1" type_arguments="unowned TextTag" GtkTextTag::event has_emitter="1" GtkTextView.layout hidden="1" gtk_text_iter_backward_search.match_start is_out="1" @@ -589,7 +634,7 @@ gtk_tree_view_get_background_area.column nullable="1" gtk_tree_view_get_cell_area.rect is_out="1" gtk_tree_view_get_cell_area.path nullable="1" gtk_tree_view_get_cell_area.column nullable="1" -gtk_tree_view_get_columns hidden="1" +gtk_tree_view_get_columns transfer_ownership="1" type_arguments="unowned TreeViewColumn" gtk_tree_view_get_cursor.path value_owned="1" nullable="1" gtk_tree_view_get_cursor.focus_column nullable="1" gtk_tree_view_get_path_at_pos.path value_owned="1" nullable="1" @@ -629,6 +674,8 @@ gtk_tree_view_column_set_attributes ellipsis="1" gtk_tree_view_column_set_model.model nullable="1" GtkTreeViewSearchEqualFunc hidden="1" gtk_true hidden="1" +gtk_ui_manager_get_action_groups type_arguments="ActionGroup" +gtk_ui_manager_get_toplevels transfer_ownership="1" type_arguments="unowned Widget" gtk_ui_manager_new_merge_id hidden="1" gtk_viewport_new.hadjustment nullable="1" gtk_viewport_new.vadjustment nullable="1" @@ -652,6 +699,8 @@ gtk_widget_get_size_request.height is_out="1" gtk_widget_input_shape_combine_mask.shape_mask nullable="1" gtk_widget_intersect.intersection nullable="1" gtk_widget_is_focus hidden="1" experimental="1" +gtk_widget_list_accel_closures transfer_ownership="1" type_arguments="GLib.Closure" +gtk_widget_list_mnemonic_labels transfer_ownership="1" type_arguments="unowned Widget" gtk_widget_modify_base.color nullable="1" gtk_widget_modify_bg.color nullable="1" gtk_widget_modify_cursor.primary nullable="1" @@ -690,19 +739,25 @@ GtkWidget::style_set.previous_style nullable="1" GtkWidget::unmap has_emitter="1" GtkWidget::unrealize has_emitter="1" GtkWidgetClass name="pointer" +gtk_window_get_default_icon_list transfer_ownership="1" type_arguments="unowned Gdk.Pixbuf" gtk_window_get_default_size.width is_out="1" gtk_window_get_default_size.height is_out="1" +gtk_window_get_icon_list transfer_ownership="1" type_arguments="unowned Gdk.Pixbuf" gtk_window_get_position.root_x is_out="1" gtk_window_get_position.root_y is_out="1" gtk_window_get_size.width is_out="1" gtk_window_get_size.height is_out="1" gtk_window_has_toplevel_focus hidden="1" experimental="1" gtk_window_is_active hidden="1" experimental="1" +gtk_window_list_toplevels transfer_ownership="1" type_arguments="unowned Window" +gtk_window_set_default_icon_list.list type_arguments="Gdk.Pixbuf" +gtk_window_set_icon_list.list type_arguments="Gdk.Pixbuf" gtk_widget_new hidden="1" GtkWindow::activate_default name="default_activated" experimental="1" GtkWindow::activate_focus name="focus_activated" experimental="1" GtkWindow::set_focus has_emitter="1" GtkWindow::set_focus.focus nullable="1" +gtk_window_group_list_windows transfer_ownership="1" type_arguments="unowned Window" GtkWidget::button_press_event.event namespace_name="Gdk" type_name="EventButton" GtkWidget::button_release_event.event namespace_name="Gdk" type_name="EventButton" GtkWidget::client_event.event namespace_name="Gdk" type_name="EventClient"
cede9edfa8f658991f3cca217bd8d18c1a31bb93
apache$maven-plugins
[MASSEMBLY-278] Adding parameter ignoreMissingDescriptor (default value: false) to allow reuse of a single assembly configuration throughout a multimodule build, without failing on submodules that don't contain the assembly descriptor referenced by the configuration...instead, simply don't run for these cases. Patch submitted by: Sejal Patel NOTE: I added two unit tests to DefaultAssemblyReaderTest to test this new functionality. git-svn-id: https://svn.apache.org/repos/asf/maven/plugins/trunk@628867 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/AssemblerConfigurationSource.java b/maven-assembly-plugin/src/main/java/org/apache/maven/plugin/assembly/AssemblerConfigurationSource.java index 77ce16c86c..d6e2df46b3 100644 --- a/maven-assembly-plugin/src/main/java/org/apache/maven/plugin/assembly/AssemblerConfigurationSource.java +++ b/maven-assembly-plugin/src/main/java/org/apache/maven/plugin/assembly/AssemblerConfigurationSource.java @@ -80,4 +80,5 @@ public interface AssemblerConfigurationSource boolean isIgnoreDirFormatExtensions(); + boolean isIgnoreMissingDescriptor(); } diff --git a/maven-assembly-plugin/src/main/java/org/apache/maven/plugin/assembly/io/DefaultAssemblyReader.java b/maven-assembly-plugin/src/main/java/org/apache/maven/plugin/assembly/io/DefaultAssemblyReader.java index f7727950c3..210d80928d 100644 --- a/maven-assembly-plugin/src/main/java/org/apache/maven/plugin/assembly/io/DefaultAssemblyReader.java +++ b/maven-assembly-plugin/src/main/java/org/apache/maven/plugin/assembly/io/DefaultAssemblyReader.java @@ -122,13 +122,13 @@ public List readAssemblies( AssemblerConfigurationSource configSource ) if ( descriptor != null ) { locator.setStrategies( strategies ); - assemblies.add( getAssemblyFromDescriptor( descriptor, locator, configSource ) ); + addAssemblyFromDescriptor( descriptor, locator, configSource, assemblies ); } if ( descriptorId != null ) { locator.setStrategies( refStrategies ); - assemblies.add( getAssemblyForDescriptorReference( descriptorId, configSource ) ); + addAssemblyForDescriptorReference( descriptorId, configSource, assemblies ); } if ( ( descriptors != null ) && ( descriptors.length > 0 ) ) @@ -137,7 +137,7 @@ public List readAssemblies( AssemblerConfigurationSource configSource ) for ( int i = 0; i < descriptors.length; i++ ) { getLogger().info( "Reading assembly descriptor: " + descriptors[i] ); - assemblies.add( getAssemblyFromDescriptor( descriptors[i], locator, configSource ) ); + addAssemblyFromDescriptor( descriptors[i], locator, configSource, assemblies ); } } @@ -146,7 +146,7 @@ public List readAssemblies( AssemblerConfigurationSource configSource ) locator.setStrategies( refStrategies ); for ( int i = 0; i < descriptorRefs.length; i++ ) { - assemblies.add( getAssemblyForDescriptorReference( descriptorRefs[i], configSource ) ); + addAssemblyForDescriptorReference( descriptorRefs[i], configSource, assemblies ); } } @@ -190,14 +190,21 @@ public List readAssemblies( AssemblerConfigurationSource configSource ) { for ( int i = 0; i < paths.length; i++ ) { - assemblies.add( getAssemblyFromDescriptor( paths[i], locator, configSource ) ); + addAssemblyFromDescriptor( paths[i], locator, configSource, assemblies ); } } } if ( assemblies.isEmpty() ) { - throw new AssemblyReadException( "No assembly descriptors found." ); + if ( configSource.isIgnoreMissingDescriptor() ) + { + getLogger().debug( "Ignoring missing assembly descriptors per configuration. See messages above for specifics." ); + } + else + { + throw new AssemblyReadException( "No assembly descriptors found." ); + } } // check unique IDs @@ -216,18 +223,41 @@ public List readAssemblies( AssemblerConfigurationSource configSource ) public Assembly getAssemblyForDescriptorReference( String ref, AssemblerConfigurationSource configSource ) throws AssemblyReadException, InvalidAssemblerConfigurationException + { + return addAssemblyForDescriptorReference( ref, configSource, new ArrayList( 1 ) ); + } + + public Assembly getAssemblyFromDescriptorFile( File file, AssemblerConfigurationSource configSource ) + throws AssemblyReadException, InvalidAssemblerConfigurationException + { + return addAssemblyFromDescriptorFile( file, configSource, new ArrayList( 1 ) ); + } + + private Assembly addAssemblyForDescriptorReference( String ref, AssemblerConfigurationSource configSource, List assemblies ) + throws AssemblyReadException, InvalidAssemblerConfigurationException { InputStream resourceAsStream = getClass().getResourceAsStream( "/assemblies/" + ref + ".xml" ); if ( resourceAsStream == null ) { - throw new AssemblyReadException( "Descriptor with ID '" + ref + "' not found" ); + if ( configSource.isIgnoreMissingDescriptor() ) + { + getLogger().debug( "Ignoring missing assembly descriptor with ID '" + ref + "' per configuration." ); + return null; + } + else + { + throw new AssemblyReadException( "Descriptor with ID '" + ref + "' not found" ); + } } try { // TODO use ReaderFactory.newXmlReader() when plexus-utils is upgraded to 1.4.5+ - return readAssembly( new InputStreamReader( resourceAsStream, "UTF-8" ), ref, configSource ); + Assembly assembly = readAssembly( new InputStreamReader( resourceAsStream, "UTF-8" ), ref, configSource ); + + assemblies.add( assembly ); + return assembly; } catch ( UnsupportedEncodingException e ) { @@ -236,15 +266,32 @@ public Assembly getAssemblyForDescriptorReference( String ref, AssemblerConfigur } } - public Assembly getAssemblyFromDescriptorFile( File descriptor, AssemblerConfigurationSource configSource ) + private Assembly addAssemblyFromDescriptorFile( File descriptor, AssemblerConfigurationSource configSource, List assemblies ) throws AssemblyReadException, InvalidAssemblerConfigurationException { + if ( !descriptor.exists() ) + { + if ( configSource.isIgnoreMissingDescriptor() ) + { + getLogger().debug( "Ignoring missing assembly descriptor: '" + descriptor + "' per configuration." ); + return null; + } + else + { + throw new AssemblyReadException( "Descriptor: '" + descriptor + "' not found" ); + } + } + Reader r = null; try { // TODO use ReaderFactory.newXmlReader() when plexus-utils is upgraded to 1.4.5+ r = new InputStreamReader( new FileInputStream( descriptor ), "UTF-8" ); - return readAssembly( r, descriptor.getAbsolutePath(), configSource ); + Assembly assembly = readAssembly( r, descriptor.getAbsolutePath(), configSource ); + + assemblies.add( assembly ); + + return assembly; } catch ( IOException e ) { @@ -256,14 +303,25 @@ public Assembly getAssemblyFromDescriptorFile( File descriptor, AssemblerConfigu } } - public Assembly getAssemblyFromDescriptor( String spec, Locator locator, AssemblerConfigurationSource configSource ) + private Assembly addAssemblyFromDescriptor( String spec, Locator locator, AssemblerConfigurationSource configSource, List assemblies ) throws AssemblyReadException, InvalidAssemblerConfigurationException { Location location = locator.resolve( spec ); if ( location == null ) { - throw new AssemblyReadException( "Error locating assembly descriptor: " + spec + "\n\n" + locator.getMessageHolder().render() ); + if ( configSource.isIgnoreMissingDescriptor() ) + { + getLogger().debug( "Ignoring missing assembly descriptor with ID '" + spec + + "' per configuration.\nLocator output was:\n\n" + + locator.getMessageHolder().render() ); + return null; + } + else + { + throw new AssemblyReadException( "Error locating assembly descriptor: " + spec + + "\n\n" + locator.getMessageHolder().render() ); + } } Reader r = null; @@ -271,7 +329,11 @@ public Assembly getAssemblyFromDescriptor( String spec, Locator locator, Assembl { // TODO use ReaderFactory.newXmlReader() when plexus-utils is upgraded to 1.4.5+ r = new InputStreamReader( location.getInputStream(), "UTF-8" ); - return readAssembly( r, spec, configSource ); + Assembly assembly = readAssembly( r, spec, configSource ); + + assemblies.add( assembly ); + + return assembly; } catch ( IOException e ) { diff --git a/maven-assembly-plugin/src/main/java/org/apache/maven/plugin/assembly/mojos/AbstractAssemblyMojo.java b/maven-assembly-plugin/src/main/java/org/apache/maven/plugin/assembly/mojos/AbstractAssemblyMojo.java index 2db5f6d0c0..eb14146e8e 100644 --- a/maven-assembly-plugin/src/main/java/org/apache/maven/plugin/assembly/mojos/AbstractAssemblyMojo.java +++ b/maven-assembly-plugin/src/main/java/org/apache/maven/plugin/assembly/mojos/AbstractAssemblyMojo.java @@ -237,6 +237,12 @@ public abstract class AbstractAssemblyMojo */ protected boolean appendAssemblyId; + /** + * Set to true in order to not fail when a descriptor is missing. + * @parameter expression="${ignoreMissingDescriptor}" default-value="false" + */ + protected boolean ignoreMissingDescriptor; + /** * This is a set of instructions to the archive builder, especially for building .jar files. It enables you to * specify a Manifest file for the jar, in addition to other options. @@ -625,4 +631,11 @@ public boolean isIgnoreDirFormatExtensions() return ignoreDirFormatExtensions; } + public boolean isIgnoreMissingDescriptor() { + return ignoreMissingDescriptor; + } + + public void setIgnoreMissingDescriptor(boolean ignoreMissingDescriptor) { + this.ignoreMissingDescriptor = ignoreMissingDescriptor; + } } diff --git a/maven-assembly-plugin/src/test/java/org/apache/maven/plugin/assembly/io/DefaultAssemblyReaderTest.java b/maven-assembly-plugin/src/test/java/org/apache/maven/plugin/assembly/io/DefaultAssemblyReaderTest.java index 13db79e5f4..c9f513ffae 100644 --- a/maven-assembly-plugin/src/test/java/org/apache/maven/plugin/assembly/io/DefaultAssemblyReaderTest.java +++ b/maven-assembly-plugin/src/test/java/org/apache/maven/plugin/assembly/io/DefaultAssemblyReaderTest.java @@ -935,6 +935,57 @@ public void testReadAssemblies_ShouldGetAssemblyDescriptorFromSingleFile() assertEquals( assembly.getId(), result.getId() ); } + public void testReadAssemblies_ShouldFailWhenSingleDescriptorFileMissing() + throws IOException, InvalidAssemblerConfigurationException + { + File basedir = fileManager.createTempDir(); + + File assemblyFile = new File( basedir, "test.xml" ); + assemblyFile.delete(); + + try + { + performReadAssemblies( basedir, + assemblyFile.getAbsolutePath(), + null, + null, + null, + null, + false ); + + fail( "Should fail when descriptor file is missing and ignoreDescriptors == false" ); + } + catch ( AssemblyReadException e ) + { + // expected. + } + } + + public void testReadAssemblies_ShouldIgnoreMissingSingleDescriptorFileWhenIgnoreIsConfigured() + throws IOException, InvalidAssemblerConfigurationException + { + File basedir = fileManager.createTempDir(); + + File assemblyFile = new File( basedir, "test.xml" ); + assemblyFile.delete(); + + try + { + performReadAssemblies( basedir, + assemblyFile.getAbsolutePath(), + null, + null, + null, + null, + true ); + } + catch ( AssemblyReadException e ) + { + e.printStackTrace(); + fail( "Setting ignoreMissingDescriptor == true (true flag in performReadAssemblies, above) should NOT produce an exception." ); + } + } + public void testReadAssemblies_ShouldGetAssemblyDescriptorFromSingleRef() throws IOException, AssemblyReadException, InvalidAssemblerConfigurationException { @@ -1056,7 +1107,9 @@ public void testReadAssemblies_ShouldGetTwoAssemblyDescriptorsFromDirectoryWithT writeAssembliesToFile( assemblies, basedir ); - fileManager.createFile( basedir, "readme.txt", "This is just a readme file, not a descriptor." ); + fileManager.createFile( basedir, + "readme.txt", + "This is just a readme file, not a descriptor." ); List results = performReadAssemblies( basedir, null, null, null, null, basedir ); @@ -1108,6 +1161,24 @@ private List performReadAssemblies( File basedir, String[] descriptorRefs, File descriptorDir ) throws AssemblyReadException, InvalidAssemblerConfigurationException + { + return performReadAssemblies( basedir, + descriptor, + descriptorRef, + descriptors, + descriptorRefs, + descriptorDir, + false ); + } + + private List performReadAssemblies( File basedir, + String descriptor, + String descriptorRef, + String[] descriptors, + String[] descriptorRefs, + File descriptorDir, + boolean ignoreMissing ) + throws AssemblyReadException, InvalidAssemblerConfigurationException { configSource.getDescriptor(); configSourceControl.setReturnValue( descriptor ); @@ -1134,6 +1205,9 @@ private List performReadAssemblies( File basedir, configSource.isSiteIncluded(); configSourceControl.setReturnValue( false, MockControl.ZERO_OR_MORE ); + configSource.isIgnoreMissingDescriptor(); + configSourceControl.setReturnValue( ignoreMissing, MockControl.ZERO_OR_MORE ); + mockManager.replayAll(); List assemblies = new DefaultAssemblyReader().readAssemblies( configSource );
b727e15dffbfa9621bc1b4e80b6b7786e370f5b0
camel
CAMEL-2325: Removed not needed code.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@895568 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/component/bean/BeanProcessor.java b/camel-core/src/main/java/org/apache/camel/component/bean/BeanProcessor.java index fad8a4adb39f6..d550155c693fa 100644 --- a/camel-core/src/main/java/org/apache/camel/component/bean/BeanProcessor.java +++ b/camel-core/src/main/java/org/apache/camel/component/bean/BeanProcessor.java @@ -133,15 +133,6 @@ public void process(Exchange exchange) throws Exception { // remove temporary header in.removeHeader(Exchange.BEAN_MULTI_PARAMETER_ARRAY); - // if there was bean invocation as body and we are invoking the same bean - // then invoke it - if (beanInvoke != null && beanInvoke.getMethod() == invocation.getMethod()) { - beanInvoke.invoke(bean, exchange); - // propagate headers - exchange.getOut().getHeaders().putAll(exchange.getIn().getHeaders()); - return; - } - Object value = null; try { value = invocation.proceed();
afb1efaa343a4341f9883741adeae77589210df6
kotlin
Refactored reference provider logic.--
p
https://github.com/JetBrains/kotlin
diff --git a/.idea/workspace.xml b/.idea/workspace.xml index d0362e355ceec..99bc02b26e7aa 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -8,48 +8,12 @@ </component> <component name="ChangeListManager"> <list default="true" id="f02ef53d-47a4-4f5e-a1aa-3df68aae9b20" name="Default" comment=""> - <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/ExpressionTranslator.java" /> - <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/ExpressionVisitor.java" /> - <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/FunctionTranslator.java" /> - <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/PatternTranslator.java" /> - <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/WhenTranslator.java" /> - <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/AbstractTranslator.java" /> - <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/TranslationContext.java" /> - <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/TranslatorVisitor.java" /> - <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/BindingUtils.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\AbstractTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/AbstractTranslator.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\BinaryOperationTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/operation/BinaryOperationTranslator.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\BindingUtils.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/BindingUtils.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\ExpressionTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/ExpressionTranslator.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\ExpressionVisitor.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/ExpressionVisitor.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\FunctionTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/FunctionTranslator.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\GenerationState.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/GenerationState.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\Namer.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/Namer.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\OperationTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/operation/OperationTranslator.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\OperatorTable.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/operation/OperatorTable.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\PatternTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/PatternTranslator.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\PropertyAccessTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\ReferenceProvider.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\ReferenceTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\Translation.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/Translation.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\TranslationContext.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/TranslationContext.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\TranslationUtils.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\TranslatorVisitor.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/TranslatorVisitor.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\UnaryOperationTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/operation/UnaryOperationTranslator.java" /> - <change type="MOVED" beforePath="C:\Dev\Projects\jet-contrib\k2js\translator\src\org\jetbrains\k2js\translate\WhenTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/WhenTranslator.java" /> <change type="MODIFICATION" beforePath="$PROJECT_DIR$/.idea/workspace.xml" afterPath="$PROJECT_DIR$/.idea/workspace.xml" /> - <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/K2JSTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/K2JSTranslator.java" /> - <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/declarations/ExtractionVisitor.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/declarations/ExtractionVisitor.java" /> - <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/ClassDeclarationTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/ClassDeclarationTranslator.java" /> - <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/ClassTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/ClassTranslator.java" /> - <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/DeclarationBodyVisitor.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/DeclarationBodyVisitor.java" /> - <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/NamespaceTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/NamespaceTranslator.java" /> - <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/PropertyTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/PropertyTranslator.java" /> - <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/initializer/AbstractInitializerTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/initializer/AbstractInitializerTranslator.java" /> - <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/initializer/ClassInitializerTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/initializer/ClassInitializerTranslator.java" /> - <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/initializer/InitializerVisitor.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/initializer/InitializerVisitor.java" /> - <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/initializer/NamespaceInitializerTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/initializer/NamespaceInitializerTranslator.java" /> - <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/utils/ClassSorter.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/utils/ClassSorter.java" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/Translation.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/Translation.java" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java" /> + <change type="MODIFICATION" beforePath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java" afterPath="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java" /> </list> <ignored path="k2js.iws" /> <ignored path=".idea/workspace.xml" /> @@ -160,7 +124,7 @@ <favorites_list name="k2js" /> </component> <component name="FileEditorManager"> - <splitter split-orientation="horizontal" split-proportion="0.3907068"> + <splitter split-orientation="horizontal" split-proportion="0.5281414"> <split-first> <leaf> <file leaf-file-name="UnaryOperationTranslator.java" pinned="false" current="false" current-in-tab="false"> @@ -176,7 +140,9 @@ <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/operation/OperationTranslator.java"> <provider selected="true" editor-type-id="text-editor"> <state line="49" column="0" selection-start="1957" selection-end="1957" vertical-scroll-proportion="0.0"> - <folding /> + <folding> + <element signature="imports" expanded="false" /> + </folding> </state> </provider> </entry> @@ -220,16 +186,34 @@ <file leaf-file-name="ReferenceProvider.java" pinned="false" current="false" current-in-tab="false"> <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java"> <provider selected="true" editor-type-id="text-editor"> - <state line="13" column="19" selection-start="468" selection-end="468" vertical-scroll-proportion="0.0"> + <state line="41" column="59" selection-start="1836" selection-end="1836" vertical-scroll-proportion="0.0"> <folding /> </state> </provider> </entry> </file> - <file leaf-file-name="ReferenceTranslator.java" pinned="false" current="true" current-in-tab="true"> + <file leaf-file-name="ReferenceTranslator.java" pinned="false" current="false" current-in-tab="false"> <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java"> <provider selected="true" editor-type-id="text-editor"> - <state line="30" column="11" selection-start="1117" selection-end="1117" vertical-scroll-proportion="0.30357143"> + <state line="68" column="83" selection-start="2716" selection-end="2716" vertical-scroll-proportion="0.0"> + <folding /> + </state> + </provider> + </entry> + </file> + <file leaf-file-name="PropertyAccessTranslator.java" pinned="false" current="true" current-in-tab="true"> + <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java"> + <provider selected="true" editor-type-id="text-editor"> + <state line="120" column="100" selection-start="5315" selection-end="5315" vertical-scroll-proportion="0.23214285"> + <folding /> + </state> + </provider> + </entry> + </file> + <file leaf-file-name="TraitTest.java" pinned="false" current="false" current-in-tab="false"> + <entry file="file://$PROJECT_DIR$/translator/test/org/jetbrains/k2js/test/TraitTest.java"> + <provider selected="true" editor-type-id="text-editor"> + <state line="58" column="60" selection-start="1296" selection-end="1296" vertical-scroll-proportion="0.0"> <folding /> </state> </provider> @@ -251,10 +235,8 @@ <file leaf-file-name="TranslationUtils.java" pinned="false" current="false" current-in-tab="false"> <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java"> <provider selected="true" editor-type-id="text-editor"> - <state line="105" column="5" selection-start="4607" selection-end="4607" vertical-scroll-proportion="0.0"> - <folding> - <element signature="imports" expanded="false" /> - </folding> + <state line="36" column="0" selection-start="1468" selection-end="1468" vertical-scroll-proportion="0.0"> + <folding /> </state> </provider> </entry> @@ -275,7 +257,9 @@ <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/DeclarationBodyVisitor.java"> <provider selected="true" editor-type-id="text-editor"> <state line="55" column="0" selection-start="2216" selection-end="2216" vertical-scroll-proportion="0.0"> - <folding /> + <folding> + <element signature="imports" expanded="false" /> + </folding> </state> </provider> </entry> @@ -307,19 +291,19 @@ </provider> </entry> </file> - <file leaf-file-name="Translation.java" pinned="false" current="false" current-in-tab="false"> + <file leaf-file-name="Translation.java" pinned="false" current="false" current-in-tab="true"> <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/Translation.java"> <provider selected="true" editor-type-id="text-editor"> - <state line="36" column="56" selection-start="1761" selection-end="1761" vertical-scroll-proportion="0.0"> + <state line="97" column="0" selection-start="4431" selection-end="4431" vertical-scroll-proportion="1.1111112"> <folding /> </state> </provider> </entry> </file> - <file leaf-file-name="ExpressionVisitor.java" pinned="false" current="false" current-in-tab="true"> + <file leaf-file-name="ExpressionVisitor.java" pinned="false" current="false" current-in-tab="false"> <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/ExpressionVisitor.java"> <provider selected="true" editor-type-id="text-editor"> - <state line="159" column="66" selection-start="7163" selection-end="7163" vertical-scroll-proportion="0.3023622"> + <state line="159" column="66" selection-start="7163" selection-end="7163" vertical-scroll-proportion="-7.3846154"> <folding /> </state> </provider> @@ -355,10 +339,6 @@ <component name="IdeDocumentHistory"> <option name="changedFiles"> <list> - <option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/ReferenceTranslator.java" /> - <option value="$PROJECT_DIR$/translator/test/org/jetbrains/k2js/test/BasicClassTest.java" /> - <option value="$PROJECT_DIR$/translator/testFiles/class/out/propertiesAsParametersInitialized.js" /> - <option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/initializer/ClassInitializerTranslator.java" /> <option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/TranslationUtils.java" /> <option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/TranslationContext.java" /> <option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/Translation.java" /> @@ -370,7 +350,11 @@ <option value="$PROJECT_DIR$/translator/testFiles/operatorOverloading/cases/usingModInCaseModAssignNotAvailable.kt" /> <option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/OperatorTable.java" /> <option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/operation/OperatorTable.java" /> + <option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java" /> + <option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java" /> <option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java" /> + <option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/Translation.java" /> + <option value="$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java" /> </list> </option> </component> @@ -985,7 +969,7 @@ </component> <component name="ToolWindowManager"> <frame x="-8" y="-8" width="1936" height="1176" extended-state="6" /> - <editor active="false" /> + <editor active="true" /> <layout> <window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32853025" sideWeight="0.49812934" order="7" side_tool="false" content_ui="tabs" /> <window_info id="Palette" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" /> @@ -1002,8 +986,8 @@ <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="true" content_ui="tabs" /> <window_info id="Maven Projects" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32977018" sideWeight="0.728146" order="4" side_tool="false" content_ui="tabs" /> <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.3997862" sideWeight="0.6705998" order="0" side_tool="false" content_ui="tabs" /> - <window_info id="Project" active="true" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.18332443" sideWeight="0.728146" order="0" side_tool="false" content_ui="tabs" /> - <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.27185398" sideWeight="0.64190274" order="2" side_tool="false" content_ui="tabs" /> + <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.18332443" sideWeight="0.728146" order="0" side_tool="false" content_ui="tabs" /> + <window_info id="Run" active="true" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.27185398" sideWeight="0.64190274" order="2" side_tool="false" content_ui="tabs" /> <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" /> <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" /> <window_info id="Metrics" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.3275862" sideWeight="0.5" order="9" side_tool="false" content_ui="tabs" /> @@ -1047,7 +1031,7 @@ <option name="INCLUDE_TEXT_INTO_SHELF" value="false" /> <option name="CREATE_PATCH_EXPAND_DETAILS_DEFAULT" value="true" /> <option name="FORCE_NON_EMPTY_COMMENT" value="false" /> - <option name="LAST_COMMIT_MESSAGE" value="Added test." /> + <option name="LAST_COMMIT_MESSAGE" value="Reorganised project structure." /> <option name="MAKE_NEW_CHANGELIST_ACTIVE" value="true" /> <option name="OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT" value="true" /> <option name="CHECK_FILES_UP_TO_DATE_BEFORE_COMMIT" value="false" /> @@ -1060,7 +1044,6 @@ <option name="UPDATE_GROUP_BY_CHANGELIST" value="false" /> <option name="SHOW_FILE_HISTORY_AS_TREE" value="false" /> <option name="FILE_HISTORY_SPLITTER_PROPORTION" value="0.6" /> - <MESSAGE value="Rewrote name resolving logic. Improved DeclarationExtractor and renamed to Declarations." /> <MESSAGE value="Added support for basic case of function literal." /> <MESSAGE value="Added tests for simple closure examples." /> <MESSAGE value="Added some tests from jet project." /> @@ -1085,6 +1068,7 @@ <MESSAGE value="Added support for initialization of properties as constructor parameters." /> <MESSAGE value="Refactoring function translator." /> <MESSAGE value="Added test." /> + <MESSAGE value="Reorganised project structure." /> </component> <component name="XDebuggerManager"> <breakpoint-manager /> @@ -1094,29 +1078,6 @@ <option name="FILTER_TARGETS" value="false" /> </component> <component name="editorHistoryManager"> - <entry file="file://$PROJECT_DIR$/translator/testFiles/inheritance/out/valuePassedToAncestorConstructor.js"> - <provider selected="true" editor-type-id="text-editor"> - <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0"> - <folding /> - </state> - </provider> - </entry> - <entry file="file://$PROJECT_DIR$/translator/testFiles/class/out/propertiesAsParametersInitialized.js"> - <provider selected="true" editor-type-id="text-editor"> - <state line="3" column="102" selection-start="97" selection-end="97" vertical-scroll-proportion="0.0"> - <folding /> - </state> - </provider> - </entry> - <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java"> - <provider selected="true" editor-type-id="text-editor"> - <state line="105" column="5" selection-start="4607" selection-end="4607" vertical-scroll-proportion="0.0"> - <folding> - <element signature="imports" expanded="false" /> - </folding> - </state> - </provider> - </entry> <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/TranslationContext.java"> <provider selected="true" editor-type-id="text-editor"> <state line="120" column="29" selection-start="4917" selection-end="4917" vertical-scroll-proportion="0.0"> @@ -1131,13 +1092,6 @@ </state> </provider> </entry> - <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/Translation.java"> - <provider selected="true" editor-type-id="text-editor"> - <state line="36" column="56" selection-start="1761" selection-end="1761" vertical-scroll-proportion="0.0"> - <folding /> - </state> - </provider> - </entry> <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/FunctionTranslator.java"> <provider selected="true" editor-type-id="text-editor"> <state line="70" column="93" selection-start="2680" selection-end="2680" vertical-scroll-proportion="0.0"> @@ -1151,7 +1105,9 @@ <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/declaration/DeclarationBodyVisitor.java"> <provider selected="true" editor-type-id="text-editor"> <state line="55" column="0" selection-start="2216" selection-end="2216" vertical-scroll-proportion="0.0"> - <folding /> + <folding> + <element signature="imports" expanded="false" /> + </folding> </state> </provider> </entry> @@ -1183,30 +1139,58 @@ </state> </provider> </entry> - <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java"> + <entry file="file://$PROJECT_DIR$/translator/testFiles/operatorOverloading/cases/usingModInCaseModAssignNotAvailable.kt"> <provider selected="true" editor-type-id="text-editor"> - <state line="13" column="19" selection-start="468" selection-end="468" vertical-scroll-proportion="0.0"> + <state line="13" column="30" selection-start="201" selection-end="201" vertical-scroll-proportion="0.0"> <folding /> </state> </provider> </entry> - <entry file="file://$PROJECT_DIR$/translator/testFiles/operatorOverloading/cases/usingModInCaseModAssignNotAvailable.kt"> + <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/ExpressionVisitor.java"> <provider selected="true" editor-type-id="text-editor"> - <state line="13" column="30" selection-start="201" selection-end="201" vertical-scroll-proportion="0.0"> + <state line="159" column="66" selection-start="7163" selection-end="7163" vertical-scroll-proportion="-7.3846154"> <folding /> </state> </provider> </entry> - <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/expression/ExpressionVisitor.java"> + <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java"> <provider selected="true" editor-type-id="text-editor"> - <state line="159" column="66" selection-start="7163" selection-end="7163" vertical-scroll-proportion="0.3023622"> + <state line="41" column="59" selection-start="1836" selection-end="1836" vertical-scroll-proportion="0.0"> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java"> <provider selected="true" editor-type-id="text-editor"> - <state line="30" column="11" selection-start="1117" selection-end="1117" vertical-scroll-proportion="0.30357143"> + <state line="68" column="83" selection-start="2716" selection-end="2716" vertical-scroll-proportion="0.0"> + <folding /> + </state> + </provider> + </entry> + <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java"> + <provider selected="true" editor-type-id="text-editor"> + <state line="36" column="0" selection-start="1468" selection-end="1468" vertical-scroll-proportion="0.0"> + <folding /> + </state> + </provider> + </entry> + <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/general/Translation.java"> + <provider selected="true" editor-type-id="text-editor"> + <state line="97" column="0" selection-start="4431" selection-end="4431" vertical-scroll-proportion="1.1111112"> + <folding /> + </state> + </provider> + </entry> + <entry file="file://$PROJECT_DIR$/translator/test/org/jetbrains/k2js/test/TraitTest.java"> + <provider selected="true" editor-type-id="text-editor"> + <state line="58" column="60" selection-start="1296" selection-end="1296" vertical-scroll-proportion="0.0"> + <folding /> + </state> + </provider> + </entry> + <entry file="file://$PROJECT_DIR$/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java"> + <provider selected="true" editor-type-id="text-editor"> + <state line="120" column="100" selection-start="5315" selection-end="5315" vertical-scroll-proportion="0.23214285"> <folding /> </state> </provider> diff --git a/translator/src/org/jetbrains/k2js/translate/general/Translation.java b/translator/src/org/jetbrains/k2js/translate/general/Translation.java index 9e25f9cb70f12..63f32d507de43 100644 --- a/translator/src/org/jetbrains/k2js/translate/general/Translation.java +++ b/translator/src/org/jetbrains/k2js/translate/general/Translation.java @@ -15,7 +15,6 @@ import org.jetbrains.k2js.translate.initializer.ClassInitializerTranslator; import org.jetbrains.k2js.translate.initializer.NamespaceInitializerTranslator; import org.jetbrains.k2js.translate.reference.PropertyAccessTranslator; -import org.jetbrains.k2js.translate.reference.ReferenceProvider; import org.jetbrains.k2js.translate.reference.ReferenceTranslator; /** @@ -96,13 +95,6 @@ static public JsPropertyInitializer generateNamespaceInitializerMethod(@NotNull return (new NamespaceInitializerTranslator(namespace, context)).generateInitializeMethod(); } - @NotNull - static public JsNameRef generateCorrectReference(@NotNull TranslationContext context, - @NotNull JetSimpleNameExpression expression, - @NotNull JsName referencedName) { - return (new ReferenceProvider(context, expression, referencedName)).generateCorrectReference(); - } - public static void generateAst(@NotNull JsProgram result, @NotNull BindingContext bindingContext, @NotNull Declarations declarations, @NotNull JetNamespace namespace) { JsBlock block = result.getFragmentBlock(0); diff --git a/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java b/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java index f1d4d5123de62..44d6f941d0ae3 100644 --- a/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java +++ b/translator/src/org/jetbrains/k2js/translate/reference/PropertyAccessTranslator.java @@ -20,7 +20,6 @@ import org.jetbrains.k2js.translate.general.Translation; import org.jetbrains.k2js.translate.general.TranslationContext; import org.jetbrains.k2js.translate.utils.BindingUtils; -import org.jetbrains.k2js.translate.utils.TranslationUtils; /** * @author Talanov Pavel @@ -94,7 +93,7 @@ private JsInvocation resolveAsPropertyGet(@NotNull JetQualifiedExpression expres @NotNull private JsInvocation resolveAsPropertyGet(@NotNull JetSimpleNameExpression expression) { JsName getterName = getNotNullGetterName(expression); - JsNameRef getterReference = TranslationUtils.getReference(context(), expression, getterName); + JsNameRef getterReference = ReferenceProvider.getReference(getterName, context(), expression); return AstUtil.newInvocation(getterReference); } @@ -118,7 +117,7 @@ private JsInvocation resolveAsPropertySet(@NotNull JetDotQualifiedExpression dot @NotNull private JsInvocation resolveAsPropertySet(@NotNull JetSimpleNameExpression expression) { JsName setterName = getNotNullSetterName(expression); - JsNameRef setterReference = Translation.generateCorrectReference(context(), expression, setterName); + JsNameRef setterReference = ReferenceProvider.getReference(setterName, context(), expression); return AstUtil.newInvocation(setterReference); } diff --git a/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java b/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java index 1262f7f2ad8be..7e4e57f1676fa 100644 --- a/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java +++ b/translator/src/org/jetbrains/k2js/translate/reference/ReferenceProvider.java @@ -17,16 +17,29 @@ public final class ReferenceProvider { private final TranslationContext context; @NotNull private final JsName referencedName; + private boolean isBackingFieldAccess; private boolean requiresThisQualifier; private boolean requiresNamespaceQualifier; + public static JsNameRef getReference(@NotNull JsName referencedName, @NotNull TranslationContext context, + boolean isBackingFieldAccess) { + return (new ReferenceProvider(referencedName, context, isBackingFieldAccess)).generateCorrectReference(); + } + + + public static JsNameRef getReference(@NotNull JsName referencedName, @NotNull TranslationContext context, + JetSimpleNameExpression expression) { + boolean isBackingFieldAccess = expression.getReferencedNameElementType() == JetTokens.FIELD_IDENTIFIER; + return (new ReferenceProvider(referencedName, context, isBackingFieldAccess)) + .generateCorrectReference(); + } - public ReferenceProvider(@NotNull TranslationContext context, - @NotNull JetSimpleNameExpression expression, - @NotNull JsName referencedName) { + private ReferenceProvider(@NotNull JsName referencedName, @NotNull TranslationContext context, + boolean isBackingFieldAccess) { this.context = context; this.referencedName = referencedName; - this.requiresThisQualifier = requiresThisQualifier(expression); + this.isBackingFieldAccess = isBackingFieldAccess; + this.requiresThisQualifier = requiresThisQualifier(); this.requiresNamespaceQualifier = requiresNamespaceQualifier(); } @@ -44,10 +57,9 @@ private boolean requiresNamespaceQualifier() { return context.namespaceScope().ownsName(referencedName); } - private boolean requiresThisQualifier(@NotNull JetSimpleNameExpression expression) { + private boolean requiresThisQualifier() { JsName name = context.enclosingScope().findExistingName(referencedName.getIdent()); boolean isClassMember = context.classScope().ownsName(name); - boolean isBackingFieldAccess = expression.getReferencedNameElementType() == JetTokens.FIELD_IDENTIFIER; return isClassMember || isBackingFieldAccess; } } diff --git a/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java b/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java index e474a95066550..9dd63d6753247 100644 --- a/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java +++ b/translator/src/org/jetbrains/k2js/translate/reference/ReferenceTranslator.java @@ -66,7 +66,7 @@ private JsExpression resolveAsGlobalReference(@NotNull JetSimpleNameExpression e return null; } JsName referencedName = context().getNameForDescriptor(referencedDescriptor); - return TranslationUtils.getReference(context(), expression, referencedName); + return ReferenceProvider.getReference(referencedName, context(), expression); } @Nullable diff --git a/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java b/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java index 2b48825fb9add..26ec095bc35e5 100644 --- a/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java +++ b/translator/src/org/jetbrains/k2js/translate/utils/TranslationUtils.java @@ -7,7 +7,6 @@ import org.jetbrains.jet.lang.descriptors.PropertyDescriptor; import org.jetbrains.jet.lang.psi.JetExpression; import org.jetbrains.jet.lang.psi.JetProperty; -import org.jetbrains.jet.lang.psi.JetSimpleNameExpression; import org.jetbrains.jet.lang.psi.ValueArgument; import org.jetbrains.k2js.translate.general.Translation; import org.jetbrains.k2js.translate.general.TranslationContext; @@ -35,14 +34,6 @@ static public JsBinaryOperation isNullCheck(@NotNull TranslationContext context, return AstUtil.equals(expressionToCheck, nullLiteral); } - @NotNull - static public JsNameRef getReference(@NotNull TranslationContext context, - @NotNull JetSimpleNameExpression expression, - @NotNull JsName referencedName) { - return (new ReferenceProvider(context, expression, referencedName)).generateCorrectReference(); - } - - @Nullable static public JsName getLocalReferencedName(@NotNull TranslationContext context, @NotNull String name) { @@ -69,25 +60,24 @@ static public JsExpression translateArgument(@NotNull TranslationContext context return Translation.translateAsExpression(jetExpression, context); } - //TODO: refactor @NotNull static public JsNameRef backingFieldReference(@NotNull TranslationContext context, @NotNull JetProperty expression) { JsName backingFieldName = getBackingFieldName(getPropertyName(expression), context); - if (BindingUtils.belongsToNamespace(context.bindingContext(), expression)) { - return context.getNamespaceQualifiedReference(backingFieldName); - } - return AstUtil.thisQualifiedReference(backingFieldName); + return generateReference(context, backingFieldName); } @NotNull static public JsNameRef backingFieldReference(@NotNull TranslationContext context, @NotNull PropertyDescriptor descriptor) { JsName backingFieldName = getBackingFieldName(descriptor.getName(), context); - if (BindingUtils.belongsToNamespace(context.bindingContext(), descriptor)) { - return context.getNamespaceQualifiedReference(backingFieldName); - } - return AstUtil.thisQualifiedReference(backingFieldName); + return generateReference(context, backingFieldName); + } + + @NotNull + private static JsNameRef generateReference(@NotNull TranslationContext context, + @NotNull JsName backingFieldName) { + return ReferenceProvider.getReference(backingFieldName, context, true); } @NotNull @@ -100,7 +90,8 @@ static public String getPropertyName(@NotNull JetProperty expression) { } @NotNull - static private JsName getBackingFieldName(@NotNull String propertyName, @NotNull TranslationContext context) { + static private JsName getBackingFieldName(@NotNull String propertyName, + @NotNull TranslationContext context) { String backingFieldName = Namer.getKotlinBackingFieldName(propertyName); return context.enclosingScope().findExistingName(backingFieldName); }
7631ac6f526edf472d1383f7b82171c7ac29f0fb
Delta Spike
DELTASPIKE-378 add getPropertyAwarePropertyValue feel free to propose a better name if you find one :)
a
https://github.com/apache/deltaspike
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java index 05cbc59df..6b3ada263 100644 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java @@ -162,18 +162,110 @@ public static String getPropertyValue(String key) * <p><b>Attention</b> This method must only be used after all ConfigSources * got registered and it also must not be used to determine the ProjectStage itself.</p> * @param key + * @return the configured value or if non found the defaultValue + * + */ + public static String getProjectStageAwarePropertyValue(String key) + { + ProjectStage ps = getProjectStage(); + + String value = getPropertyValue(key + '.' + ps); + if (value == null) + { + value = getPropertyValue(key); + } + + return value; + } + /** + * {@link #getProjectStageAwarePropertyValue(String)} which returns the defaultValue + * if the property is <code>null</code> or empty. + * @param key * @param defaultValue * @return the configured value or if non found the defaultValue * */ public static String getProjectStageAwarePropertyValue(String key, String defaultValue) { - ProjectStage ps = getProjectStage(); + String value = getProjectStageAwarePropertyValue(key); + + if (value == null || value.length() == 0) + { + value = defaultValue; + } + + return value; + } + + /** + * <p>Search for the configured value in all {@link ConfigSource}s and take the + * current {@link org.apache.deltaspike.core.api.projectstage.ProjectStage} + * and the value configured for the given property into account.</p> + * + * <p>The first step is to resolve the value of the given property. This will + * take the current ProjectStage into account. E.g. given the property is 'dbvendor' + * and the ProjectStage is 'UnitTest', the first lookup is + * <ul><li>'dbvendor.UnitTest'</li></ul>. + * If this value is not found then we will do a 2nd lookup for + * <ul><li>'dbvendor'</li></ul></p> + * + * <p>If a value was found for the given property (e.g. dbvendor = 'mysql' + * then we will use this value to lookup in the following order until we + * found a non-null value. If there was no value found for the property + * we will only do the key+ProjectStage and key lookup. + * In the following sample 'dataSource' is used as key parameter: + * + * <ul> + * <li>'datasource.mysql.UnitTest'</li> + * <li>'datasource.mysql'</li> + * <li>'datasource.UnitTest'</li> + * <li>'datasource'</li> + * </ul> + * </p> + * + * + * <p><b>Attention</b> This method must only be used after all ConfigSources + * got registered and it also must not be used to determine the ProjectStage itself.</p> + * @param key + * @param property the property to look up first + * @return the configured value or if non found the defaultValue + * + */ + public static String getPropertyAwarePropertyValue(String key, String property) + { + String propertyValue = getProjectStageAwarePropertyValue(property); + + String value = null; + + if (propertyValue != null && propertyValue.length() > 0) + { + value = getProjectStageAwarePropertyValue(key + '.' + propertyValue); + } - String value = getPropertyValue(key + '.' + ps, defaultValue); if (value == null) { - value = getPropertyValue(key, defaultValue); + value = getProjectStageAwarePropertyValue(key); + } + + return value; + } + + /* + * <p><b>Attention</b> This method must only be used after all ConfigSources + * got registered and it also must not be used to determine the ProjectStage itself.</p> + * @param key + * @param property the property to look up first + * @param defaultValue + * @return the configured value or if non found the defaultValue + * + */ + public static String getPropertyAwarePropertyValue(String key, String property, String defaultValue) + { + String value = getPropertyAwarePropertyValue(key, property); + + if (value == null || value.length() == 0) + { + value = defaultValue; } return value; 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 91ebb22dc..d30e7de52 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 @@ -28,6 +28,7 @@ public class ConfigResolverTest { + private static final String DEFAULT_VALUE = "defaultValue"; @Test public void testOverruledValue() { @@ -60,12 +61,43 @@ public void testGetProjectStageAwarePropertyValue() Assert.assertNull(ConfigResolver.getProjectStageAwarePropertyValue("notexisting", null)); Assert.assertEquals("testvalue", ConfigResolver.getPropertyValue("testkey", null)); + Assert.assertEquals("unittestvalue", ConfigResolver.getProjectStageAwarePropertyValue("testkey")); Assert.assertEquals("unittestvalue", ConfigResolver.getProjectStageAwarePropertyValue("testkey", null)); Assert.assertEquals("testvalue", ConfigResolver.getPropertyValue("testkey2", null)); + Assert.assertEquals("testvalue", ConfigResolver.getProjectStageAwarePropertyValue("testkey2")); Assert.assertEquals("testvalue", ConfigResolver.getProjectStageAwarePropertyValue("testkey2", null)); Assert.assertEquals("testvalue", ConfigResolver.getPropertyValue("testkey3", null)); - Assert.assertEquals("", ConfigResolver.getProjectStageAwarePropertyValue("testkey3", null)); + Assert.assertEquals("", ConfigResolver.getProjectStageAwarePropertyValue("testkey3")); + Assert.assertEquals(DEFAULT_VALUE, ConfigResolver.getProjectStageAwarePropertyValue("testkey3", DEFAULT_VALUE)); + } + + @Test + public void testGetPropertyAwarePropertyValue() { + ProjectStageProducer.setProjectStage(ProjectStage.UnitTest); + + Assert.assertNull(ConfigResolver.getPropertyAwarePropertyValue("notexisting", null)); + + Assert.assertEquals("testvalue", ConfigResolver.getPropertyValue("testkey", null)); + Assert.assertEquals("unittestvalue", ConfigResolver.getPropertyAwarePropertyValue("testkey", "dbvendor")); + Assert.assertEquals("unittestvalue", ConfigResolver.getPropertyAwarePropertyValue("testkey", "dbvendor", null)); + + Assert.assertEquals("testvalue", ConfigResolver.getPropertyValue("testkey2", null)); + Assert.assertEquals("testvalue", ConfigResolver.getPropertyAwarePropertyValue("testkey2", "dbvendor")); + Assert.assertEquals("testvalue", ConfigResolver.getPropertyAwarePropertyValue("testkey2", "dbvendor", null)); + + Assert.assertEquals("testvalue", ConfigResolver.getPropertyValue("testkey3", null)); + Assert.assertEquals("", ConfigResolver.getPropertyAwarePropertyValue("testkey3", "dbvendor")); + Assert.assertEquals(DEFAULT_VALUE, ConfigResolver.getPropertyAwarePropertyValue("testkey3", "dbvendor", DEFAULT_VALUE)); + + Assert.assertEquals("TestDataSource", ConfigResolver.getPropertyAwarePropertyValue("dataSource", "dbvendor")); + Assert.assertEquals("PostgreDataSource", ConfigResolver.getPropertyAwarePropertyValue("dataSource", "dbvendor2")); + Assert.assertEquals("DefaultDataSource", ConfigResolver.getPropertyAwarePropertyValue("dataSource", "dbvendorX")); + + Assert.assertEquals("TestDataSource", ConfigResolver.getPropertyAwarePropertyValue("dataSource", "dbvendor", null)); + Assert.assertEquals("PostgreDataSource", ConfigResolver.getPropertyAwarePropertyValue("dataSource", "dbvendor2", null)); + Assert.assertEquals("DefaultDataSource", ConfigResolver.getPropertyAwarePropertyValue("dataSource", "dbvendorX", null)); + Assert.assertEquals(DEFAULT_VALUE, ConfigResolver.getPropertyAwarePropertyValue("dataSourceX", "dbvendorX", DEFAULT_VALUE)); } } diff --git a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java index e9e066fba..d0f2c938b 100644 --- a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java +++ b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java @@ -48,6 +48,20 @@ public TestConfigSource() // a value which got ProjectStage overloaded to an empty value props.put("testkey3", "testvalue"); props.put("testkey3.UnitTest", ""); + + // now for the PropertyAware tests + props.put("dbvendor.UnitTest", "mysql"); + props.put("dbvendor", "postgresql"); + + props.put("dataSource.mysql.Production", "java:/comp/env/MyDs"); + props.put("dataSource.mysql.UnitTest", "TestDataSource"); + props.put("dataSource.postgresql", "PostgreDataSource"); + props.put("dataSource", "DefaultDataSource"); + + // another one + props.put("dbvendor2.Production", "mysql"); + props.put("dbvendor2", "postgresql"); + } @Override
910b45c395032fda3587998dcbfc15cf07e9a551
drools
[DROOLS-121] detect circular dependencies for- declared types--
c
https://github.com/kiegroup/drools
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 94654c8b30b..a17c203eaa7 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 @@ -3471,16 +3471,31 @@ public Collection<AbstractClassTypeDeclarationDescr> sortByHierarchy( List<Abstr taxonomy.put( name, new ArrayList<QualifiedName>() ); } else { this.results.add( new TypeDeclarationError( tdescr, - "Found duplicate declaration for type " + tdescr.getTypeName() ) ); + "Found duplicate declaration for type " + tdescr.getTypeName() ) ); } Collection<QualifiedName> supers = taxonomy.get( name ); - supers.addAll( tdescr.getSuperTypes() ); + boolean circular = false; + 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() ) ); + break; + } + } + } + if ( circular ) { + tdescr.getSuperTypes().clear(); + } for ( TypeFieldDescr field : tdescr.getFields().values() ) { QualifiedName typeName = new QualifiedName( field.getPattern().getObjectType() ); - if ( ! typeName.equals( name ) && ! hasCircularDependency( name, typeName, taxonomy ) ) { + if ( ! hasCircularDependency( name, typeName, taxonomy ) ) { supers.add( typeName ); } @@ -3497,8 +3512,20 @@ public Collection<AbstractClassTypeDeclarationDescr> sortByHierarchy( List<Abstr } private boolean hasCircularDependency( QualifiedName name, QualifiedName typeName, Map<QualifiedName, Collection<QualifiedName>> taxonomy) { + if ( name.equals( typeName ) ) { + return true; + } if ( taxonomy.containsKey( typeName ) ) { - return taxonomy.get( typeName ).contains( name ); + Collection<QualifiedName> parents = taxonomy.get( typeName ); + if ( parents.contains( name ) ) { + return true; + } else { + for ( QualifiedName ancestor : parents ) { + if ( hasCircularDependency( name, ancestor, taxonomy ) ) { + return true; + } + } + } } return false; } diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/ExtendsTest.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/ExtendsTest.java index 0a313f39e19..d5c7e2735fa 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/ExtendsTest.java +++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/ExtendsTest.java @@ -635,6 +635,45 @@ public void testInheritFromClassWithDefaults() throws Exception { } + @Test + public void testExtendSelf() throws Exception { + String s1 = "package org.drools;\n" + + "global java.util.List list;\n" + + "\n" + + "declare Bean extends Bean \n" + + " foo : int @key\n" + + "end\n"; + + KnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase(); + + KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder( ); + kBuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); + assertTrue( kBuilder.hasErrors() ); + } + @Test + public void testExtendCircular() throws Exception { + String s1 = "package org.drools;\n" + + "global java.util.List list;\n" + + "\n" + + "declare Bean1 extends Bean2 \n" + + " foo : int @key\n" + + "end\n" + + "" + + "declare Bean2 extends Bean3 \n" + + " foo : int @key\n" + + "end\n" + + "" + + "declare Bean3 extends Bean1 \n" + + " foo : int @key\n" + + "end\n"; + + KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder( ); + kBuilder.add( new ByteArrayResource( s1.getBytes() ), ResourceType.DRL ); + assertTrue( kBuilder.hasErrors() ); + + System.out.println( kBuilder.getErrors() ); + assertTrue( kBuilder.getErrors().toString().contains( "circular" ) ); + } }
44a35b5d9accc4ecf7b1bbf762e593540bafe6a3
hadoop
HADOOP-7353. Cleanup FsShell and prevent masking of- RTE stack traces. Contributed by Daryn Sharp.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@1132764 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/hadoop
diff --git a/CHANGES.txt b/CHANGES.txt index 5e21b32de7e84..e2d5828c4aee6 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -280,6 +280,9 @@ Trunk (unreleased changes) HADOOP-7341. Fix options parsing in CommandFormat (Daryn Sharp via todd) + HADOOP-7353. Cleanup FsShell and prevent masking of RTE stack traces. + (Daryn Sharp via todd) + Release 0.22.0 - Unreleased INCOMPATIBLE CHANGES diff --git a/src/java/org/apache/hadoop/fs/FsShell.java b/src/java/org/apache/hadoop/fs/FsShell.java index b50f0b4a6d951..376ea79586b1e 100644 --- a/src/java/org/apache/hadoop/fs/FsShell.java +++ b/src/java/org/apache/hadoop/fs/FsShell.java @@ -18,9 +18,10 @@ package org.apache.hadoop.fs; import java.io.IOException; +import java.io.PrintStream; +import java.util.ArrayList; import java.util.Arrays; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +import java.util.LinkedList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -30,9 +31,6 @@ import org.apache.hadoop.fs.shell.Command; import org.apache.hadoop.fs.shell.CommandFactory; import org.apache.hadoop.fs.shell.FsCommand; -import org.apache.hadoop.fs.shell.PathExceptions.PathNotFoundException; -import org.apache.hadoop.ipc.RPC; -import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; @@ -46,23 +44,31 @@ public class FsShell extends Configured implements Tool { private Trash trash; protected CommandFactory commandFactory; + private final String usagePrefix = + "Usage: hadoop fs [generic options]"; + /** + * Default ctor with no configuration. Be sure to invoke + * {@link #setConf(Configuration)} with a valid configuration prior + * to running commands. */ public FsShell() { this(null); } + /** + * Construct a FsShell with the given configuration. Commands can be + * executed via {@link #run(String[])} + * @param conf the hadoop configuration + */ public FsShell(Configuration conf) { super(conf); - fs = null; - trash = null; - commandFactory = new CommandFactory(); } protected FileSystem getFS() throws IOException { - if(fs == null) + if (fs == null) { fs = FileSystem.get(getConf()); - + } return fs; } @@ -75,93 +81,145 @@ protected Trash getTrash() throws IOException { protected void init() throws IOException { getConf().setQuietMode(true); + if (commandFactory == null) { + commandFactory = new CommandFactory(getConf()); + commandFactory.addObject(new Help(), "-help"); + commandFactory.addObject(new Usage(), "-usage"); + registerCommands(commandFactory); + } } + protected void registerCommands(CommandFactory factory) { + // TODO: DFSAdmin subclasses FsShell so need to protect the command + // registration. This class should morph into a base class for + // commands, and then this method can be abstract + if (this.getClass().equals(FsShell.class)) { + factory.registerCommands(FsCommand.class); + } + } + /** * Returns the Trash object associated with this shell. + * @return Path to the trash + * @throws IOException upon error */ public Path getCurrentTrashDir() throws IOException { return getTrash().getCurrentTrashDir(); } + // NOTE: Usage/Help are inner classes to allow access to outer methods + // that access commandFactory + /** - * Return an abbreviated English-language desc of the byte length - * @deprecated Consider using {@link org.apache.hadoop.util.StringUtils#byteDesc} instead. + * Display help for commands with their short usage and long description */ - @Deprecated - public static String byteDesc(long len) { - return StringUtils.byteDesc(len); - } + protected class Usage extends FsCommand { + public static final String NAME = "usage"; + public static final String USAGE = "[cmd ...]"; + public static final String DESCRIPTION = + "Displays the usage for given command or all commands if none\n" + + "is specified."; + + @Override + protected void processRawArguments(LinkedList<String> args) { + if (args.isEmpty()) { + printUsage(System.out); + } else { + for (String arg : args) printUsage(System.out, arg); + } + } + } /** - * @deprecated Consider using {@link org.apache.hadoop.util.StringUtils#limitDecimalTo2} instead. + * Displays short usage of commands sans the long description */ - @Deprecated - public static synchronized String limitDecimalTo2(double d) { - return StringUtils.limitDecimalTo2(d); + protected class Help extends FsCommand { + public static final String NAME = "help"; + public static final String USAGE = "[cmd ...]"; + public static final String DESCRIPTION = + "Displays help for given command or all commands if none\n" + + "is specified."; + + @Override + protected void processRawArguments(LinkedList<String> args) { + if (args.isEmpty()) { + printHelp(System.out); + } else { + for (String arg : args) printHelp(System.out, arg); + } + } } - private void printHelp(String cmd) { - String summary = "hadoop fs is the command to execute fs commands. " + - "The full syntax is: \n\n" + - "hadoop fs [-fs <local | file system URI>] [-conf <configuration file>]\n\t" + - "[-D <property=value>]\n\t" + - "[-report]"; + /* + * The following are helper methods for getInfo(). They are defined + * outside of the scope of the Help/Usage class because the run() method + * needs to invoke them too. + */ - String conf ="-conf <configuration file>: Specify an application configuration file."; - - String D = "-D <property=value>: Use value for given property."; + // print all usages + private void printUsage(PrintStream out) { + printInfo(out, null, false); + } - String fs = "-fs [local | <file system URI>]: \tSpecify the file system to use.\n" + - "\t\tIf not specified, the current configuration is used, \n" + - "\t\ttaken from the following, in increasing precedence: \n" + - "\t\t\tcore-default.xml inside the hadoop jar file \n" + - "\t\t\tcore-site.xml in $HADOOP_CONF_DIR \n" + - "\t\t'local' means use the local file system as your DFS. \n" + - "\t\t<file system URI> specifies a particular file system to \n" + - "\t\tcontact. This argument is optional but if used must appear\n" + - "\t\tappear first on the command line. Exactly one additional\n" + - "\t\targument must be specified. \n"; + // print one usage + private void printUsage(PrintStream out, String cmd) { + printInfo(out, cmd, false); + } - String help = "-help [cmd]: \tDisplays help for given command or all commands if none\n" + - "\t\tis specified.\n"; + // print all helps + private void printHelp(PrintStream out) { + printInfo(out, null, true); + } - Command instance = commandFactory.getInstance("-" + cmd); - if (instance != null) { - printHelp(instance); - } else if ("fs".equals(cmd)) { - System.out.println(fs); - } else if ("conf".equals(cmd)) { - System.out.println(conf); - } else if ("D".equals(cmd)) { - System.out.println(D); - } else if ("help".equals(cmd)) { - System.out.println(help); + // print one help + private void printHelp(PrintStream out, String cmd) { + printInfo(out, cmd, true); + } + + private void printInfo(PrintStream out, String cmd, boolean showHelp) { + if (cmd != null) { + // display help or usage for one command + Command instance = commandFactory.getInstance("-" + cmd); + if (instance == null) { + throw new UnknownCommandException(cmd); + } + if (showHelp) { + printInstanceHelp(out, instance); + } else { + printInstanceUsage(out, instance); + } } else { - System.out.println(summary); - for (String thisCmdName : commandFactory.getNames()) { - instance = commandFactory.getInstance(thisCmdName); + // display help or usage for all commands + out.println(usagePrefix); + + // display list of short usages + ArrayList<Command> instances = new ArrayList<Command>(); + for (String name : commandFactory.getNames()) { + Command instance = commandFactory.getInstance(name); if (!instance.isDeprecated()) { System.out.println("\t[" + instance.getUsage() + "]"); + instances.add(instance); } } - System.out.println("\t[-help [cmd]]\n"); - - System.out.println(fs); - - for (String thisCmdName : commandFactory.getNames()) { - instance = commandFactory.getInstance(thisCmdName); - if (!instance.isDeprecated()) { - printHelp(instance); + // display long descriptions for each command + if (showHelp) { + for (Command instance : instances) { + out.println(); + printInstanceHelp(out, instance); } } - System.out.println(help); - } + out.println(); + ToolRunner.printGenericCommandUsage(out); + } + } + + private void printInstanceUsage(PrintStream out, Command instance) { + out.println(usagePrefix + " " + instance.getUsage()); } // TODO: will eventually auto-wrap the text, but this matches the expected // output for the hdfs tests... - private void printHelp(Command instance) { + private void printInstanceHelp(PrintStream out, Command instance) { boolean firstLine = true; for (String line : instance.getDescription().split("\n")) { String prefix; @@ -174,120 +232,51 @@ private void printHelp(Command instance) { System.out.println(prefix + line); } } - - /** - * Displays format of commands. - * - */ - private void printUsage(String cmd) { - String prefix = "Usage: java " + FsShell.class.getSimpleName(); - - Command instance = commandFactory.getInstance(cmd); - if (instance != null) { - System.err.println(prefix + " [" + instance.getUsage() + "]"); - } else if ("-fs".equals(cmd)) { - System.err.println("Usage: java FsShell" + - " [-fs <local | file system URI>]"); - } else if ("-conf".equals(cmd)) { - System.err.println("Usage: java FsShell" + - " [-conf <configuration file>]"); - } else if ("-D".equals(cmd)) { - System.err.println("Usage: java FsShell" + - " [-D <[property=value>]"); - } else { - System.err.println("Usage: java FsShell"); - for (String name : commandFactory.getNames()) { - instance = commandFactory.getInstance(name); - if (!instance.isDeprecated()) { - System.err.println(" [" + instance.getUsage() + "]"); - } - } - System.err.println(" [-help [cmd]]"); - System.err.println(); - ToolRunner.printGenericCommandUsage(System.err); - } - } /** * run */ public int run(String argv[]) throws Exception { - // TODO: This isn't the best place, but this class is being abused with - // subclasses which of course override this method. There really needs - // to be a better base class for all commands - commandFactory.setConf(getConf()); - commandFactory.registerCommands(FsCommand.class); - - if (argv.length < 1) { - printUsage(""); - return -1; - } - - int exitCode = -1; - int i = 0; - String cmd = argv[i++]; // initialize FsShell - try { - init(); - } catch (RPC.VersionMismatch v) { - LOG.debug("Version mismatch", v); - System.err.println("Version Mismatch between client and server" + - "... command aborted."); - return exitCode; - } catch (IOException e) { - LOG.debug("Error", e); - System.err.println("Bad connection to FS. Command aborted. Exception: " + - e.getLocalizedMessage()); - return exitCode; - } + init(); - try { - Command instance = commandFactory.getInstance(cmd); - if (instance != null) { - exitCode = instance.run(Arrays.copyOfRange(argv, i, argv.length)); - } else if ("-help".equals(cmd)) { - if (i < argv.length) { - printHelp(argv[i]); - } else { - printHelp(""); + int exitCode = -1; + if (argv.length < 1) { + printUsage(System.err); + } else { + String cmd = argv[0]; + Command instance = null; + try { + instance = commandFactory.getInstance(cmd); + if (instance == null) { + throw new UnknownCommandException(); } - } else { - System.err.println(cmd + ": Unknown command"); - printUsage(""); - } - } catch (Exception e) { - exitCode = 1; - LOG.debug("Error", e); - displayError(cmd, e); - if (e instanceof IllegalArgumentException) { - exitCode = -1; - printUsage(cmd); + exitCode = instance.run(Arrays.copyOfRange(argv, 1, argv.length)); + } catch (IllegalArgumentException e) { + displayError(cmd, e.getLocalizedMessage()); + if (instance != null) { + printInstanceUsage(System.err, instance); + } + } catch (Exception e) { + // instance.run catches IOE, so something is REALLY wrong if here + LOG.debug("Error", e); + displayError(cmd, "Fatal internal error"); + e.printStackTrace(System.err); } } return exitCode; } - - // TODO: this is a quick workaround to accelerate the integration of - // redesigned commands. this will be removed this once all commands are - // converted. this change will avoid having to change the hdfs tests - // every time a command is converted to use path-based exceptions - private static Pattern[] fnfPatterns = { - Pattern.compile("File (.*) does not exist\\."), - Pattern.compile("File does not exist: (.*)"), - Pattern.compile("`(.*)': specified destination directory doest not exist") - }; - private void displayError(String cmd, Exception e) { - String message = e.getLocalizedMessage().split("\n")[0]; - for (Pattern pattern : fnfPatterns) { - Matcher matcher = pattern.matcher(message); - if (matcher.matches()) { - message = new PathNotFoundException(matcher.group(1)).getMessage(); - break; - } + + private void displayError(String cmd, String message) { + for (String line : message.split("\n")) { + System.err.println(cmd.substring(1) + ": " + line); } - System.err.println(cmd.substring(1) + ": " + message); } + /** + * Performs any necessary cleanup + * @throws IOException upon error + */ public void close() throws IOException { if (fs != null) { fs.close(); @@ -297,9 +286,11 @@ public void close() throws IOException { /** * main() has some simple utility methods + * @param argv the command and its arguments + * @throws Exception upon error */ public static void main(String argv[]) throws Exception { - FsShell shell = new FsShell(); + FsShell shell = newShellInstance(); int res; try { res = ToolRunner.run(shell, argv); @@ -308,4 +299,26 @@ public static void main(String argv[]) throws Exception { } System.exit(res); } + + // TODO: this should be abstract in a base class + protected static FsShell newShellInstance() { + return new FsShell(); + } + + /** + * The default ctor signals that the command being executed does not exist, + * while other ctor signals that a specific command does not exist. The + * latter is used by commands that process other commands, ex. -usage/-help + */ + @SuppressWarnings("serial") + static class UnknownCommandException extends IllegalArgumentException { + private final String cmd; + UnknownCommandException() { this(null); } + UnknownCommandException(String cmd) { this.cmd = cmd; } + + @Override + public String getMessage() { + return ((cmd != null) ? "`"+cmd+"': " : "") + "Unknown command"; + } + } } diff --git a/src/java/org/apache/hadoop/fs/shell/Command.java b/src/java/org/apache/hadoop/fs/shell/Command.java index f2507b92c2bce..f9efdfcfb09e1 100644 --- a/src/java/org/apache/hadoop/fs/shell/Command.java +++ b/src/java/org/apache/hadoop/fs/shell/Command.java @@ -42,6 +42,13 @@ @InterfaceStability.Evolving abstract public class Command extends Configured { + /** default name of the command */ + public static String NAME; + /** the command's usage switches and arguments format */ + public static String USAGE; + /** the command's long description */ + public static String DESCRIPTION; + protected String[] args; protected String name; protected int exitCode = 0; @@ -70,14 +77,6 @@ protected Command(Configuration conf) { /** @return the command's name excluding the leading character - */ abstract public String getCommandName(); - /** - * Name the command - * @param cmdName as invoked - */ - public void setCommandName(String cmdName) { - name = cmdName; - } - protected void setRecursive(boolean flag) { recursive = flag; } @@ -120,14 +119,16 @@ public int runAll() { * expand arguments, and then process each argument. * <pre> * run - * \-> {@link #processOptions(LinkedList)} - * \-> {@link #expandArguments(LinkedList)} -> {@link #expandArgument(String)}* - * \-> {@link #processArguments(LinkedList)} - * \-> {@link #processArgument(PathData)}* - * \-> {@link #processPathArgument(PathData)} - * \-> {@link #processPaths(PathData, PathData...)} - * \-> {@link #processPath(PathData)}* - * \-> {@link #processNonexistentPath(PathData)} + * |-> {@link #processOptions(LinkedList)} + * \-> {@link #processRawArguments(LinkedList)} + * |-> {@link #expandArguments(LinkedList)} + * | \-> {@link #expandArgument(String)}* + * \-> {@link #processArguments(LinkedList)} + * |-> {@link #processArgument(PathData)}* + * | |-> {@link #processPathArgument(PathData)} + * | \-> {@link #processPaths(PathData, PathData...)} + * | \-> {@link #processPath(PathData)}* + * \-> {@link #processNonexistentPath(PathData)} * </pre> * Most commands will chose to implement just * {@link #processOptions(LinkedList)} and {@link #processPath(PathData)} @@ -144,7 +145,7 @@ public int run(String...argv) { "DEPRECATED: Please use '"+ getReplacementCommand() + "' instead."); } processOptions(args); - processArguments(expandArguments(args)); + processRawArguments(args); } catch (IOException e) { displayError(e); } @@ -170,6 +171,19 @@ public int run(String...argv) { */ protected void processOptions(LinkedList<String> args) throws IOException {} + /** + * Allows commands that don't use paths to handle the raw arguments. + * Default behavior is to expand the arguments via + * {@link #expandArguments(LinkedList)} and pass the resulting list to + * {@link #processArguments(LinkedList)} + * @param args the list of argument strings + * @throws IOException + */ + protected void processRawArguments(LinkedList<String> args) + throws IOException { + processArguments(expandArguments(args)); + } + /** * Expands a list of arguments into {@link PathData} objects. The default * behavior is to call {@link #expandArgument(String)} on each element @@ -353,7 +367,26 @@ public void displayError(String message) { * @param message warning message to display */ public void displayWarning(String message) { - err.println(getCommandName() + ": " + message); + err.println(getName() + ": " + message); + } + + /** + * The name of the command. Will first try to use the assigned name + * else fallback to the command's preferred name + * @return name of the command + */ + public String getName() { + return (name == null) + ? getCommandField("NAME") + : name.startsWith("-") ? name.substring(1) : name; // this is a historical method + } + + /** + * Define the name of the command. + * @param name as invoked + */ + public void setName(String name) { + this.name = name; } /** @@ -361,7 +394,7 @@ public void displayWarning(String message) { * @return "name options" */ public String getUsage() { - String cmd = "-" + getCommandName(); + String cmd = "-" + getName(); String usage = isDeprecated() ? "" : getCommandField("USAGE"); return usage.isEmpty() ? cmd : cmd + " " + usage; } @@ -400,9 +433,10 @@ public String getReplacementCommand() { private String getCommandField(String field) { String value; try { - value = (String)this.getClass().getField(field).get(null); + value = this.getClass().getField(field).get(this).toString(); } catch (Exception e) { - throw new RuntimeException(StringUtils.stringifyException(e)); + throw new RuntimeException( + "failed to get " + this.getClass().getSimpleName()+"."+field, e); } return value; } diff --git a/src/java/org/apache/hadoop/fs/shell/CommandFactory.java b/src/java/org/apache/hadoop/fs/shell/CommandFactory.java index c8425145cc0df..f5d9d5a801d9f 100644 --- a/src/java/org/apache/hadoop/fs/shell/CommandFactory.java +++ b/src/java/org/apache/hadoop/fs/shell/CommandFactory.java @@ -19,7 +19,8 @@ package org.apache.hadoop.fs.shell; import java.util.Arrays; -import java.util.Hashtable; +import java.util.HashMap; +import java.util.Map; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; @@ -35,8 +36,11 @@ @InterfaceStability.Unstable public class CommandFactory extends Configured implements Configurable { - private Hashtable<String, Class<? extends Command>> classMap = - new Hashtable<String, Class<? extends Command>>(); + private Map<String, Class<? extends Command>> classMap = + new HashMap<String, Class<? extends Command>>(); + + private Map<String, Command> objectMap = + new HashMap<String, Command>(); /** Factory constructor for commands */ public CommandFactory() { @@ -79,16 +83,22 @@ public void addClass(Class<? extends Command> cmdClass, String ... names) { } /** - * Returns the class implementing the given command. The - * class must have been registered via - * {@link #addClass(Class, String...)} - * @param cmd name of the command - * @return instance of the requested command + * Register the given object as handling the given list of command + * names. Avoid calling this method and use + * {@link #addClass(Class, String...)} whenever possible to avoid + * startup overhead from excessive command object instantiations. This + * method is intended only for handling nested non-static classes that + * are re-usable. Namely -help/-usage. + * @param cmdObject the object implementing the command names + * @param names one or more command names that will invoke this class */ - protected Class<? extends Command> getClass(String cmd) { - return classMap.get(cmd); + public void addObject(Command cmdObject, String ... names) { + for (String name : names) { + objectMap.put(name, cmdObject); + classMap.put(name, null); // just so it shows up in the list of commands + } } - + /** * Returns an instance of the class implementing the given command. The * class must have been registered via @@ -109,11 +119,13 @@ public Command getInstance(String cmd) { public Command getInstance(String cmdName, Configuration conf) { if (conf == null) throw new NullPointerException("configuration is null"); - Command instance = null; - Class<? extends Command> cmdClass = getClass(cmdName); - if (cmdClass != null) { - instance = ReflectionUtils.newInstance(cmdClass, conf); - instance.setCommandName(cmdName); + Command instance = objectMap.get(cmdName); + if (instance == null) { + Class<? extends Command> cmdClass = classMap.get(cmdName); + if (cmdClass != null) { + instance = ReflectionUtils.newInstance(cmdClass, conf); + instance.setName(cmdName); + } } return instance; } diff --git a/src/java/org/apache/hadoop/fs/shell/Count.java b/src/java/org/apache/hadoop/fs/shell/Count.java index 891e68a4bf928..219973f25dfc3 100644 --- a/src/java/org/apache/hadoop/fs/shell/Count.java +++ b/src/java/org/apache/hadoop/fs/shell/Count.java @@ -54,9 +54,7 @@ public static void registerCommands(CommandFactory factory) { private boolean showQuotas; /** Constructor */ - public Count() { - setCommandName(NAME); - } + public Count() {} /** Constructor * @deprecated invoke via {@link FsShell} @@ -67,7 +65,6 @@ public Count() { @Deprecated public Count(String[] cmd, int pos, Configuration conf) { super(conf); - setCommandName(NAME); this.args = Arrays.copyOfRange(cmd, pos, cmd.length); } diff --git a/src/java/org/apache/hadoop/fs/shell/Display.java b/src/java/org/apache/hadoop/fs/shell/Display.java index e650b711bc108..8a05a55310eb2 100644 --- a/src/java/org/apache/hadoop/fs/shell/Display.java +++ b/src/java/org/apache/hadoop/fs/shell/Display.java @@ -100,7 +100,7 @@ protected InputStream getInputStream(PathData item) throws IOException { */ public static class Text extends Cat { public static final String NAME = "text"; - public static final String SHORT_USAGE = Cat.USAGE; + public static final String USAGE = Cat.USAGE; public static final String DESCRIPTION = "Takes a source file and outputs the file in text format.\n" + "The allowed formats are zip and TextRecordInputStream."; diff --git a/src/java/org/apache/hadoop/fs/shell/FsCommand.java b/src/java/org/apache/hadoop/fs/shell/FsCommand.java index 32bec37182b9b..3f397327de3e6 100644 --- a/src/java/org/apache/hadoop/fs/shell/FsCommand.java +++ b/src/java/org/apache/hadoop/fs/shell/FsCommand.java @@ -65,8 +65,10 @@ protected FsCommand(Configuration conf) { super(conf); } - public String getCommandName() { - return name.startsWith("-") ? name.substring(1) : name; + // historical abstract method in Command + @Override + public String getCommandName() { + return getName(); } // abstract method that normally is invoked by runall() which is diff --git a/src/test/core/org/apache/hadoop/cli/testConf.xml b/src/test/core/org/apache/hadoop/cli/testConf.xml index 7567719bde963..d8b5785682cba 100644 --- a/src/test/core/org/apache/hadoop/cli/testConf.xml +++ b/src/test/core/org/apache/hadoop/cli/testConf.xml @@ -39,7 +39,7 @@ <comparators> <comparator> <type>SubstringComparator</type> - <expected-output>hadoop fs is the command to execute fs commands. The full syntax is</expected-output> + <expected-output>Usage: hadoop fs [generic options]</expected-output> </comparator> </comparators> </test> @@ -730,7 +730,7 @@ <comparators> <comparator> <type>RegexpComparator</type> - <expected-output>^-help \[cmd\]:( |\t)*Displays help for given command or all commands if none( )*</expected-output> + <expected-output>^-help \[cmd ...\]:( |\t)*Displays help for given command or all commands if none( )*</expected-output> </comparator> <comparator> <type>RegexpComparator</type>
a6fd48ba12e0f82b3ea937227845a63e5c1f8bf7
hbase
HBASE-11499- AsyncProcess.buildDetailedErrorMessage concatenates strings using + in a loop- (Mike Drob)--
p
https://github.com/apache/hbase
diff --git a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/AsyncProcess.java b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/AsyncProcess.java index c184147d59dd..d1bcc0b2a77b 100644 --- a/hbase-client/src/main/java/org/apache/hadoop/hbase/client/AsyncProcess.java +++ b/hbase-client/src/main/java/org/apache/hadoop/hbase/client/AsyncProcess.java @@ -1407,23 +1407,24 @@ private void decActionCounter(int index) { } private String buildDetailedErrorMsg(String string, int index) { - String error = string + "; called for " + index + - ", actionsInProgress " + actionsInProgress.get() + "; replica gets: "; + StringBuilder error = new StringBuilder(128); + error.append(string).append("; called for ").append(index).append(", actionsInProgress ") + .append(actionsInProgress.get()).append("; replica gets: "); if (replicaGetIndices != null) { for (int i = 0; i < replicaGetIndices.length; ++i) { - error += replicaGetIndices[i] + ", "; + error.append(replicaGetIndices[i]).append(", "); } } else { - error += (hasAnyReplicaGets ? "all" : "none"); + error.append(hasAnyReplicaGets ? "all" : "none"); } - error += "; results "; + error.append("; results "); if (results != null) { for (int i = 0; i < results.length; ++i) { Object o = results[i]; - error += ((o == null) ? "null" : o.toString()) + ", "; + error.append(((o == null) ? "null" : o.toString())).append(", "); } } - return error; + return error.toString(); } @Override
70a16e87c18891c9dcea9d0edb06552cd6f2e72e
camel
CAMEL-541: Removed a bad tangle in camel spi. Not- this package has no tangles.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@748992 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/management/InstrumentationErrorHandlerWrappingStrategy.java b/camel-core/src/main/java/org/apache/camel/management/InstrumentationErrorHandlerWrappingStrategy.java index 9b45cb432ea40..a01120191a4d8 100644 --- a/camel-core/src/main/java/org/apache/camel/management/InstrumentationErrorHandlerWrappingStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/management/InstrumentationErrorHandlerWrappingStrategy.java @@ -29,13 +29,14 @@ public class InstrumentationErrorHandlerWrappingStrategy implements ErrorHandlerWrappingStrategy { private Map<ProcessorType, PerformanceCounter> counterMap; + private RouteContext routeContext; - public InstrumentationErrorHandlerWrappingStrategy(Map<ProcessorType, PerformanceCounter> counterMap) { + public InstrumentationErrorHandlerWrappingStrategy(RouteContext routeContext, Map<ProcessorType, PerformanceCounter> counterMap) { this.counterMap = counterMap; + this.routeContext = routeContext; } - public Processor wrapProcessorInErrorHandler(RouteContext routeContext, ProcessorType processorType, - Processor target) throws Exception { + public Processor wrapProcessorInErrorHandler(ProcessorType processorType, Processor target) throws Exception { // don't wrap our instrumentation interceptors if (counterMap.containsKey(processorType)) { diff --git a/camel-core/src/main/java/org/apache/camel/management/InstrumentationLifecycleStrategy.java b/camel-core/src/main/java/org/apache/camel/management/InstrumentationLifecycleStrategy.java index 2a0cdfc5567fe..a01b8c8fc4c12 100644 --- a/camel-core/src/main/java/org/apache/camel/management/InstrumentationLifecycleStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/management/InstrumentationLifecycleStrategy.java @@ -29,7 +29,6 @@ import org.apache.camel.CamelContext; import org.apache.camel.Consumer; import org.apache.camel.Endpoint; -import org.apache.camel.Exchange; import org.apache.camel.Route; import org.apache.camel.Service; import org.apache.camel.impl.DefaultCamelContext; @@ -121,8 +120,7 @@ public void onRoutesAdd(Collection<Route> routes) { // retrieve the per-route intercept for this route InstrumentationProcessor interceptor = interceptorMap.get(route.getEndpoint()); if (interceptor == null) { - LOG.warn("Instrumentation processor not found for route endpoint " - + route.getEndpoint()); + LOG.warn("Instrumentation processor not found for route endpoint: " + route.getEndpoint()); } else { interceptor.setCounter(mr); } @@ -187,9 +185,7 @@ public void onRouteContextCreate(RouteContext routeContext) { } routeContext.addInterceptStrategy(new InstrumentationInterceptStrategy(counterMap)); - - routeContext.setErrorHandlerWrappingStrategy( - new InstrumentationErrorHandlerWrappingStrategy(counterMap)); + routeContext.setErrorHandlerWrappingStrategy(new InstrumentationErrorHandlerWrappingStrategy(routeContext, counterMap)); // Add an InstrumentationProcessor at the beginning of each route and // set up the interceptorMap for onRoutesAdd() method to register the diff --git a/camel-core/src/main/java/org/apache/camel/model/ProcessorType.java b/camel-core/src/main/java/org/apache/camel/model/ProcessorType.java index 542ff889fdec2..cc58a52aad34b 100644 --- a/camel-core/src/main/java/org/apache/camel/model/ProcessorType.java +++ b/camel-core/src/main/java/org/apache/camel/model/ProcessorType.java @@ -1985,7 +1985,7 @@ protected Processor wrapInErrorHandler(RouteContext routeContext, Processor targ ObjectHelper.notNull(target, "target", this); ErrorHandlerWrappingStrategy strategy = routeContext.getErrorHandlerWrappingStrategy(); if (strategy != null) { - return strategy.wrapProcessorInErrorHandler(routeContext, this, target); + return strategy.wrapProcessorInErrorHandler(this, target); } return getErrorHandlerBuilder().createErrorHandler(routeContext, target); } diff --git a/camel-core/src/main/java/org/apache/camel/spi/ErrorHandlerWrappingStrategy.java b/camel-core/src/main/java/org/apache/camel/spi/ErrorHandlerWrappingStrategy.java index af9c8be7dca79..83e9225a95308 100644 --- a/camel-core/src/main/java/org/apache/camel/spi/ErrorHandlerWrappingStrategy.java +++ b/camel-core/src/main/java/org/apache/camel/spi/ErrorHandlerWrappingStrategy.java @@ -33,13 +33,11 @@ public interface ErrorHandlerWrappingStrategy { * to give the implementor an opportunity to wrap the target processor * in a route. * - * @param routeContext the route context * @param processorType the object that invokes this method * @param target the processor to be wrapped * @return processor wrapped with an interceptor or not wrapped * @throws Exception can be thrown */ - Processor wrapProcessorInErrorHandler(RouteContext routeContext, ProcessorType processorType, - Processor target) throws Exception; + Processor wrapProcessorInErrorHandler(ProcessorType processorType, Processor target) throws Exception; }
97a57ec538bf15de51a108ab25cc7a79bcbbe662
coremedia$jangaroo-tools
Now supporting multiple variable declarations for fields and local variables, also inside for-statements. On the fly, merged DeclarationStatement, ExprStatement, and EmptyStatement into SemicolonTerminatedStatement, because they did not really add any value. Also allowed inline function definitions without a trailing semicolon, because it seems to be treated like loops in that it does not need the semicolon (IDEA inspection). To this end, introduced FunctionStatement, because a statement without a semicolon is really not a SemicolonTerminatedStatement! [git-p4: depot-paths = "//coremedia/jangaroo/": change = 147290]
a
https://github.com/coremedia/jangaroo-tools
diff --git a/jooc/src/main/cup/net/jangaroo/jooc/joo.cup b/jooc/src/main/cup/net/jangaroo/jooc/joo.cup index b3896d2cb..a673279cc 100644 --- a/jooc/src/main/cup/net/jangaroo/jooc/joo.cup +++ b/jooc/src/main/cup/net/jangaroo/jooc/joo.cup @@ -132,7 +132,9 @@ nonterminal Expr expr; nonterminal Expr exprOrObjectLiteral; nonterminal Extends extends; nonterminal FieldDeclaration fieldDeclaration; -nonterminal FunctionExpr functionExpr; +nonterminal FieldDeclaration optNextFieldDeclaration; +nonterminal FunctionExpr anonFunctionExpr; +nonterminal FunctionExpr namedFunctionExpr; nonterminal Ide ide; nonterminal Implements implements; nonterminal Implements interfaceExtends; @@ -177,6 +179,7 @@ nonterminal TypeRelation typeRelation; nonterminal Type type; nonterminal CommaSeparatedList typeList; nonterminal VariableDeclaration variableDeclaration; +nonterminal VariableDeclaration optNextVariableDeclaration; // TODO: check precedences with spec; they are from reference http://hell.org.ua/Docs/oreilly/web2/action/ch05_01.htm /* 1 */ @@ -359,7 +362,7 @@ expr ::= {: RESULT = v; :} | lvalue:v {: RESULT = v; :} - | functionExpr:e + | anonFunctionExpr:e {: RESULT = e; :} | THIS:t {: RESULT = new ThisExpr(t); :} @@ -474,6 +477,8 @@ exprOrObjectLiteral ::= {: RESULT = e; :} | objectLiteral:e {: RESULT = e; :} + | namedFunctionExpr:e + {: RESULT = e; :} ; @@ -491,14 +496,23 @@ interfaceExtends ::= ; fieldDeclaration ::= - modifiers:m constOrVar:cov ide:ide optTypeRelation:t optInitializer:init SEMICOLON:s - {: RESULT = new FieldDeclaration((JooSymbol[])m.toArray(new JooSymbol[0]), cov, ide, t, init, s); :} + modifiers:m constOrVar:cov ide:ide optTypeRelation:t optInitializer:init optNextFieldDeclaration:nf SEMICOLON:s + {: RESULT = new FieldDeclaration((JooSymbol[])m.toArray(new JooSymbol[0]), cov, ide, t, init, nf, s); :} + ; + +optNextFieldDeclaration ::= + {: RESULT = null; :} + | COMMA:c ide:ide optTypeRelation:t optInitializer:init optNextFieldDeclaration:nf + {: RESULT = new FieldDeclaration(new JooSymbol[0], c, ide, t, init, nf, null); :} ; -functionExpr ::= +anonFunctionExpr ::= FUNCTION:f LPAREN:lp parameters:params RPAREN:rp optTypeRelation:t block:b {: RESULT = new FunctionExpr(f,null,lp,params,rp,t,b); :} - | FUNCTION:f ide:ide LPAREN:lp parameters:params RPAREN:rp optTypeRelation:t block:b + ; + +namedFunctionExpr ::= + FUNCTION:f ide:ide LPAREN:lp parameters:params RPAREN:rp optTypeRelation:t block:b {: RESULT = new FunctionExpr(f,ide,lp,params,rp,t,b); :} ; @@ -615,7 +629,7 @@ optBody ::= block:b {: RESULT = b; :} | SEMICOLON:s - {: RESULT = new EmptyStatement(s); :} + {: RESULT = new SemicolonTerminatedStatement(s); :} ; optCatches ::= @@ -714,10 +728,10 @@ labelableStatement ::= {: RESULT = new DoStatement(d,s,w,e,sc); :} | FOR:f LPAREN:lp SEMICOLON:s1 optCommaExpr:e1 SEMICOLON:s2 optCommaExpr:e2 RPAREN:rp statement:s {: RESULT = new ForStatement(f,lp,null,s1,e1,s2,e2,rp,s); :} - | FOR:f LPAREN:lp expr:e SEMICOLON:s1 optCommaExpr:e1 SEMICOLON:s2 optCommaExpr:e2 RPAREN:rp statement:s + | FOR:f LPAREN:lp commaExpr:e SEMICOLON:s1 optCommaExpr:e1 SEMICOLON:s2 optCommaExpr:e2 RPAREN:rp statement:s {: RESULT = new ForStatement(f,lp,new ForInitializer(e),s1,e1,s2,e2,rp,s); :} - | FOR:f LPAREN:lp VAR:var ide:ide optTypeRelation:t optInitializer:init SEMICOLON:s1 optCommaExpr:e1 SEMICOLON:s2 optCommaExpr:e2 RPAREN:rp statement:s - {: RESULT = new ForStatement(f,lp,new ForInitializer(new VariableDeclaration(var,ide,t,init)),s1,e1,s2,e2,rp,s); :} + | FOR:f LPAREN:lp VAR:var ide:ide optTypeRelation:t optInitializer:init optNextVariableDeclaration:nv SEMICOLON:s1 optCommaExpr:e1 SEMICOLON:s2 optCommaExpr:e2 RPAREN:rp statement:s + {: RESULT = new ForStatement(f,lp,new ForInitializer(new VariableDeclaration(var,ide,t,init, nv)),s1,e1,s2,e2,rp,s); :} | FOR:f LPAREN:lp ide:ide IN:in expr:e RPAREN:rp statement:s {: RESULT = new ForInStatement(f,null,lp,ide,in,e,rp,s); :} | FOR:f LPAREN:lp VAR:var ide:ide optTypeRelation:t IN:in expr:e RPAREN:rp statement:s @@ -732,17 +746,19 @@ labelableStatement ::= {: RESULT = new TryStatement(t,b,c,f,fb); :} | block:b {: RESULT = b; :} + | namedFunctionExpr:f + {: RESULT = new FunctionStatement(f); :} ; statement ::= SEMICOLON:s - {: RESULT = new EmptyStatement(s); :} + {: RESULT = new SemicolonTerminatedStatement(s); :} | commaExpr:e SEMICOLON:s - {: RESULT = new ExprStatement(e,s); :} + {: RESULT = new SemicolonTerminatedStatement(e,s); :} | ide:ide COLON:c labelableStatement:s {: RESULT = new LabeledStatement(ide,c,s); :} | variableDeclaration:decl SEMICOLON:s - {: RESULT = new DeclarationStatement(decl, s); :} + {: RESULT = new SemicolonTerminatedStatement(decl, s); :} | BREAK:b optIde:ide SEMICOLON:s {: RESULT = new BreakStatement(b,ide,s); :} | CONTINUE:c optIde:ide SEMICOLON:s @@ -807,7 +823,12 @@ typeRelation ::= ; variableDeclaration ::= - constOrVar:cov ide:ide optTypeRelation:t optInitializer:init - {: RESULT = new VariableDeclaration(cov,ide,t,init); :} + constOrVar:cov ide:ide optTypeRelation:t optInitializer:init optNextVariableDeclaration:nv + {: RESULT = new VariableDeclaration(cov,ide,t,init, nv); :} ; +optNextVariableDeclaration ::= + {: RESULT = null; :} + | COMMA:c ide:ide optTypeRelation:t optInitializer:init optNextVariableDeclaration:nv + {: RESULT = new VariableDeclaration(c, ide, t, init, nv); :} + ; diff --git a/jooc/src/main/java/net/jangaroo/jooc/AbstractVariableDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/AbstractVariableDeclaration.java index c4194e39d..84862e33d 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/AbstractVariableDeclaration.java +++ b/jooc/src/main/java/net/jangaroo/jooc/AbstractVariableDeclaration.java @@ -19,42 +19,84 @@ /** * @author Andreas Gawecki + * @author Frank Wienberg */ abstract class AbstractVariableDeclaration extends MemberDeclaration { JooSymbol optSymConstOrVar; Initializer optInitializer; + AbstractVariableDeclaration optNextVariableDeclaration; JooSymbol optSymSemicolon; protected AbstractVariableDeclaration(JooSymbol[] modifiers, int allowedModifiers, JooSymbol optSymConstOrVar, Ide ide, TypeRelation optTypeRelation, Initializer optInitializer, JooSymbol optSymSemicolon) { + this(modifiers, allowedModifiers, optSymConstOrVar, ide, optTypeRelation, optInitializer, null, optSymSemicolon); + } + + protected AbstractVariableDeclaration(JooSymbol[] modifiers, int allowedModifiers, JooSymbol optSymConstOrVar, Ide ide, + TypeRelation optTypeRelation, Initializer optInitializer, AbstractVariableDeclaration optNextVariableDeclaration, JooSymbol optSymSemicolon + ) { super(modifiers, allowedModifiers, ide, optTypeRelation); this.optSymConstOrVar = optSymConstOrVar; this.optInitializer = optInitializer; + this.optNextVariableDeclaration = optNextVariableDeclaration; this.optSymSemicolon = optSymSemicolon; } public void generateCode(JsWriter out) throws IOException { - out.beginComment(); - writeModifiers(out); - out.endComment(); - generateIdeCode(out); + if (hasPreviousVariableDeclaration()) { + Debug.assertTrue(optSymConstOrVar!=null && optSymConstOrVar.sym==sym.COMMA, "Additional variable declarations must start with a COMMA."); + out.writeSymbol(optSymConstOrVar); + } else { + generateStartCode(out); + } + ide.generateCode(out); if (optTypeRelation != null) optTypeRelation.generateCode(out); generateInitializerCode(out); - if (optSymSemicolon != null) - out.writeSymbol(optSymSemicolon); + if (optNextVariableDeclaration != null) + optNextVariableDeclaration.generateCode(out); + generateEndCode(out); } + protected abstract void generateStartCode(JsWriter out) throws IOException; + protected void generateInitializerCode(JsWriter out) throws IOException { if (optInitializer != null) optInitializer.generateCode(out); } - public abstract void generateIdeCode(JsWriter out) throws IOException; + protected void generateEndCode(JsWriter out) throws IOException { + if (optSymSemicolon != null) + out.writeSymbol(optSymSemicolon); + } + + protected boolean hasPreviousVariableDeclaration() { + return parentNode instanceof AbstractVariableDeclaration; + } + + protected AbstractVariableDeclaration getPreviousVariableDeclaration() { + return (AbstractVariableDeclaration)parentNode; + } + + protected AbstractVariableDeclaration getFirstVariableDeclaration() { + AbstractVariableDeclaration firstVariableDeclaration = this; + while (firstVariableDeclaration.hasPreviousVariableDeclaration()) { + firstVariableDeclaration = firstVariableDeclaration.getPreviousVariableDeclaration(); + } + return firstVariableDeclaration; + } + + @Override + protected int getModifiers() { + return hasPreviousVariableDeclaration() + ? getFirstVariableDeclaration().getModifiers() + : super.getModifiers(); + } public boolean isConst() { - return optSymConstOrVar != null && optSymConstOrVar.sym == sym.CONST; + AbstractVariableDeclaration firstVariableDeclaration = getFirstVariableDeclaration(); + return firstVariableDeclaration.optSymConstOrVar != null && firstVariableDeclaration.optSymConstOrVar.sym == sym.CONST; } public Node analyze(Node parentNode, AnalyzeContext context) { @@ -63,6 +105,8 @@ public Node analyze(Node parentNode, AnalyzeContext context) { Jooc.error(optSymConstOrVar, "constant must be initialized"); if (optInitializer != null) optInitializer.analyze(this, context); + if (optNextVariableDeclaration != null) + optNextVariableDeclaration.analyze(this, context); return this; } diff --git a/jooc/src/main/java/net/jangaroo/jooc/AssertStatement.java b/jooc/src/main/java/net/jangaroo/jooc/AssertStatement.java index 8dff365cd..df8808f7e 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/AssertStatement.java +++ b/jooc/src/main/java/net/jangaroo/jooc/AssertStatement.java @@ -37,7 +37,7 @@ public void generateCode(JsWriter out) throws IOException { out.writeToken("assert"); out.writeSymbol(lParen); out.write("("); - optExpr.generateCode(out); + optStatement.generateCode(out); out.write(")"); out.write(", "); out.writeString(symKeyword.getFileName()); @@ -46,7 +46,7 @@ public void generateCode(JsWriter out) throws IOException { out.write(", "); out.writeInt(symKeyword.getColumn()); out.writeSymbol(rParen); - out.writeSymbol(symSemicolon); + out.writeSymbol(optSymSemicolon); } else { out.beginComment(); super.generateCode(out); diff --git a/jooc/src/main/java/net/jangaroo/jooc/Catch.java b/jooc/src/main/java/net/jangaroo/jooc/Catch.java index 66defcc26..3b1c70500 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/Catch.java +++ b/jooc/src/main/java/net/jangaroo/jooc/Catch.java @@ -27,7 +27,6 @@ class Catch extends KeywordStatement { Parameter param; JooSymbol rParen; BlockStatement block; - private boolean first; public Catch(JooSymbol symCatch, JooSymbol lParen, Parameter param, JooSymbol rParen, BlockStatement block) { super(symCatch); @@ -44,7 +43,7 @@ public void generateCode(JsWriter out) throws IOException { Catch firstCatch = catches.get(0); boolean isFirst = equals(firstCatch); boolean isLast = equals(catches.get(catches.size()-1)); - TypeRelation typeRelation = param.getOptTypeRelation(); + TypeRelation typeRelation = param.optTypeRelation; boolean hasCondition = typeRelation != null && typeRelation.getType().getSymbol().sym!=sym.MUL; if (!hasCondition && !isLast) { Jooc.error(rParen, "Only last catch clause may be untyped."); @@ -107,7 +106,4 @@ public Node analyze(Node parentNode, AnalyzeContext context) { return this; } - public void setFirst(boolean first) { - this.first = first; - } } diff --git a/jooc/src/main/java/net/jangaroo/jooc/CompilationUnit.java b/jooc/src/main/java/net/jangaroo/jooc/CompilationUnit.java index 710832d1a..09d8bd4cb 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/CompilationUnit.java +++ b/jooc/src/main/java/net/jangaroo/jooc/CompilationUnit.java @@ -21,6 +21,7 @@ import java.io.File; import java.io.IOException; +import java.util.List; /** * @author Andreas Gawecki @@ -34,7 +35,7 @@ public PackageDeclaration getPackageDeclaration() { PackageDeclaration packageDeclaration; JooSymbol lBrace; - Directives directives; + List<Node> directives; IdeDeclaration primaryDeclaration; JooSymbol rBrace; @@ -43,7 +44,7 @@ public PackageDeclaration getPackageDeclaration() { protected JsWriter out; - public CompilationUnit(PackageDeclaration packageDeclaration, JooSymbol lBrace, Directives directives, IdeDeclaration primaryDeclaration, JooSymbol rBrace) { + public CompilationUnit(PackageDeclaration packageDeclaration, JooSymbol lBrace, List<Node> directives, IdeDeclaration primaryDeclaration, JooSymbol rBrace) { this.packageDeclaration = packageDeclaration; this.lBrace = lBrace; this.directives = directives; @@ -73,7 +74,7 @@ public void generateCode(JsWriter out) throws IOException { packageDeclaration.generateCode(out); out.writeSymbolWhitespace(lBrace); if (directives!=null) { - directives.generateCode(out); + generateCode(directives, out); } primaryDeclaration.generateCode(out); out.writeSymbolWhitespace(rBrace); @@ -112,7 +113,7 @@ public Node analyze(Node parentNode, AnalyzeContext context) { context.enterScope(packageDeclaration); packageDeclaration.analyze(this, context); if (directives!=null) { - directives.analyze(this, context); + analyze(this, directives, context); } primaryDeclaration.analyze(this, context); context.leaveScope(packageDeclaration); diff --git a/jooc/src/main/java/net/jangaroo/jooc/Declaration.java b/jooc/src/main/java/net/jangaroo/jooc/Declaration.java index e57597e42..973a05582 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/Declaration.java +++ b/jooc/src/main/java/net/jangaroo/jooc/Declaration.java @@ -90,27 +90,27 @@ protected int getModifiers() { } public boolean isPublic() { - return (modifiers & MODIFIER_PUBLIC) != 0; + return (getModifiers() & MODIFIER_PUBLIC) != 0; } public boolean isProtected() { - return (modifiers & MODIFIER_PROTECTED) != 0; + return (getModifiers() & MODIFIER_PROTECTED) != 0; } public boolean isPrivate() { - return (modifiers & MODIFIER_PRIVATE) != 0; + return (getModifiers() & MODIFIER_PRIVATE) != 0; } public boolean isStatic() { - return (modifiers & MODIFIER_STATIC) != 0; + return (getModifiers() & MODIFIER_STATIC) != 0; } public boolean isAbstract() { - return (modifiers & MODIFIER_ABSTRACT) != 0; + return (getModifiers() & MODIFIER_ABSTRACT) != 0; } public boolean isFinal() { - return (modifiers & MODIFIER_FINAL) != 0; + return (getModifiers() & MODIFIER_FINAL) != 0; } public ClassDeclaration getClassDeclaration() { @@ -118,8 +118,7 @@ public ClassDeclaration getClassDeclaration() { } protected void writeModifiers(JsWriter out) throws IOException { - for (int i = 0; i < symModifiers.length; i++) { - JooSymbol modifier = symModifiers[i]; + for (JooSymbol modifier : symModifiers) { out.writeSymbol(modifier); } } diff --git a/jooc/src/main/java/net/jangaroo/jooc/EmptyStatement.java b/jooc/src/main/java/net/jangaroo/jooc/EmptyStatement.java deleted file mode 100644 index 87e0f590b..000000000 --- a/jooc/src/main/java/net/jangaroo/jooc/EmptyStatement.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2008 CoreMedia AG - * - * 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 net.jangaroo.jooc; - -/** - * @author Andreas Gawecki - */ -public class EmptyStatement extends ExprStatement { - public EmptyStatement(JooSymbol symSemicolon) { - super(null, symSemicolon); - } - - public JooSymbol getSymbol() { - return symSemicolon; - } - -} diff --git a/jooc/src/main/java/net/jangaroo/jooc/ExprStatement.java b/jooc/src/main/java/net/jangaroo/jooc/ExprStatement.java deleted file mode 100644 index 1c24b440b..000000000 --- a/jooc/src/main/java/net/jangaroo/jooc/ExprStatement.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2008 CoreMedia AG - * - * 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 net.jangaroo.jooc; - -import java.io.IOException; - -/** - * @author Andreas Gawecki - */ -class ExprStatement extends Statement { - - Expr optExpr; - JooSymbol symSemicolon; - - public ExprStatement(Expr optExpr, JooSymbol symSemicolon) { - this.optExpr = optExpr; - this.symSemicolon = symSemicolon; - } - - public void generateCode(JsWriter out) throws IOException { - if (optExpr != null) - optExpr.generateCode(out); - out.writeSymbol(symSemicolon); - } - - public Node analyze(Node parentNode, AnalyzeContext context) { - super.analyze(parentNode, context); - if (optExpr != null) - optExpr = optExpr.analyze(this, context); - return this; - } - - public JooSymbol getSymbol() { - return optExpr == null ? symSemicolon : optExpr.getSymbol(); - } - -} diff --git a/jooc/src/main/java/net/jangaroo/jooc/FieldDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/FieldDeclaration.java index bd2e5b023..590bcb22e 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/FieldDeclaration.java +++ b/jooc/src/main/java/net/jangaroo/jooc/FieldDeclaration.java @@ -19,14 +19,21 @@ /** * @author Andreas Gawecki + * @author Frank Wienberg */ public class FieldDeclaration extends AbstractVariableDeclaration { public FieldDeclaration(JooSymbol[] modifiers, JooSymbol symConstOrVar, Ide ide, - TypeRelation optTypeRelation, Initializer optInitializer, JooSymbol symSemicolon) { + TypeRelation optTypeRelation, Initializer optInitializer, JooSymbol optSymSemicolon) { + this(modifiers, symConstOrVar, ide, optTypeRelation, optInitializer, null, optSymSemicolon); + } + + public FieldDeclaration(JooSymbol[] modifiers, JooSymbol symConstOrVar, Ide ide, + TypeRelation optTypeRelation, Initializer optInitializer, FieldDeclaration optNextFieldDeclaration, JooSymbol optSymSemicolon + ) { super(modifiers, MODIFIERS_SCOPE|MODIFIER_STATIC, - symConstOrVar, ide, optTypeRelation, optInitializer, symSemicolon); + symConstOrVar, ide, optTypeRelation, optInitializer, optNextFieldDeclaration, optSymSemicolon); } @Override @@ -34,15 +41,18 @@ public boolean isField() { return true; } - public void generateCode(JsWriter out) throws IOException { + @Override + protected void generateStartCode(JsWriter out) throws IOException { out.beginString(); writeModifiers(out); - out.writeSymbol(optSymConstOrVar); + if (optSymConstOrVar!=null) + out.writeSymbol(optSymConstOrVar); out.endString(); out.write(",{"); - generateIdeCode(out); - if (optTypeRelation != null) - optTypeRelation.generateCode(out); + } + + @Override + protected void generateInitializerCode(JsWriter out) throws IOException { if (optInitializer != null) { out.writeSymbolWhitespace(optInitializer.symEq); out.write(':'); @@ -57,16 +67,15 @@ public void generateCode(JsWriter out) throws IOException { } else { out.write(": undefined"); } - out.write('}'); - Debug.assertTrue(optSymSemicolon != null, "optSymSemicolon != null"); - out.write(","); } - public void generateIdeCode(JsWriter out) throws IOException { - out.writeSymbolWhitespace(ide.ide); - out.writeSymbolToken(ide.ide); + @Override + protected void generateEndCode(JsWriter out) throws IOException { + if (!hasPreviousVariableDeclaration()) { + out.write('}'); + Debug.assertTrue(optSymSemicolon != null, "optSymSemicolon != null"); + out.writeSymbolWhitespace(optSymSemicolon); + out.writeToken(","); + } } - - - } diff --git a/jooc/src/main/java/net/jangaroo/jooc/ForInStatement.java b/jooc/src/main/java/net/jangaroo/jooc/ForInStatement.java index db7e2ec93..86a15938b 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/ForInStatement.java +++ b/jooc/src/main/java/net/jangaroo/jooc/ForInStatement.java @@ -77,11 +77,12 @@ protected void generateLoopHeaderCode(JsWriter out) throws IOException { if (symEach!=null) { // synthesize assigning the correct index to the variable given in the original for each statement: ArrayIndexExpr indexExpr = new ArrayIndexExpr(expr, new JooSymbol(sym.LBRACK, "["), - new CommaSeparatedList(new IdeExpr(auxIde)), + new CommaSeparatedList<IdeExpr>(new IdeExpr(auxIde)), new JooSymbol(sym.RBRACK, "]")); - Node assignment = decl!=null - ? new DeclarationStatement(new VariableDeclaration(SYM_VAR, decl.ide, decl.optTypeRelation, new Initializer(SYM_EQ, indexExpr)), SYM_SEMICOLON) - : new ExprStatement(new AssignmentOpExpr(new IdeExpr(ide), SYM_EQ, indexExpr), SYM_SEMICOLON); + Node assignment = new SemicolonTerminatedStatement(decl!=null + ? new VariableDeclaration(SYM_VAR, decl.ide, decl.optTypeRelation, new Initializer(SYM_EQ, indexExpr)) + : new AssignmentOpExpr(new IdeExpr(ide), SYM_EQ, indexExpr), + SYM_SEMICOLON); // inject synthesized statement into loop body: if (body instanceof BlockStatement) { ((BlockStatement)body).statements.add(0, assignment); diff --git a/jooc/src/main/java/net/jangaroo/jooc/DeclarationStatement.java b/jooc/src/main/java/net/jangaroo/jooc/FunctionStatement.java similarity index 67% rename from jooc/src/main/java/net/jangaroo/jooc/DeclarationStatement.java rename to jooc/src/main/java/net/jangaroo/jooc/FunctionStatement.java index cf4b833e0..a0c13fbc1 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/DeclarationStatement.java +++ b/jooc/src/main/java/net/jangaroo/jooc/FunctionStatement.java @@ -16,31 +16,32 @@ package net.jangaroo.jooc; import java.io.IOException; +import java.util.List; +import java.util.ArrayList; /** - * @author Andreas Gawecki + * @author Frank Wienberg */ -class DeclarationStatement extends SemicolonTerminatedStatement { +class FunctionStatement extends Statement { - Declaration decl; + private FunctionExpr fun; - public DeclarationStatement(Declaration decl, JooSymbol symSemicolon) { - super(symSemicolon); - this.decl = decl; + FunctionStatement(FunctionExpr fun) { + this.fun = fun; } + @Override public Node analyze(Node parentNode, AnalyzeContext context) { super.analyze(parentNode, context); - decl.analyze(this, context); + fun.analyze(this, context); return this; } - protected void generateStatementCode(JsWriter out) throws IOException { - decl.generateCode(out); + public void generateCode(JsWriter out) throws IOException { + fun.generateCode(out); } public JooSymbol getSymbol() { - return decl.getSymbol(); + return fun.getSymbol(); } - -} +} \ No newline at end of file diff --git a/jooc/src/main/java/net/jangaroo/jooc/IdeDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/IdeDeclaration.java index 20b6d22dd..8309b3ea5 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/IdeDeclaration.java +++ b/jooc/src/main/java/net/jangaroo/jooc/IdeDeclaration.java @@ -66,14 +66,7 @@ public String getQualifiedNameStr() { public Node analyze(Node parentNode, AnalyzeContext context) { super.analyze(parentNode, context); - if (context.getScope().declareIde(getName(), this)!=null) { - String msg = "Duplicate declaration of identifier '" + getName() + "'"; - if (allowDuplicates) { - Jooc.warning(getSymbol(), msg); - } else { - Jooc.error(getSymbol(), msg); - } - } + context.getScope().declareIde(getName(), this, allowDuplicates, getSymbol()); return this; } diff --git a/jooc/src/main/java/net/jangaroo/jooc/KeywordExprStatement.java b/jooc/src/main/java/net/jangaroo/jooc/KeywordExprStatement.java index 818bb2088..4ddc6a1c1 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/KeywordExprStatement.java +++ b/jooc/src/main/java/net/jangaroo/jooc/KeywordExprStatement.java @@ -20,7 +20,7 @@ /** * @author Andreas Gawecki */ -abstract class KeywordExprStatement extends ExprStatement { +abstract class KeywordExprStatement extends SemicolonTerminatedStatement { JooSymbol symKeyword; diff --git a/jooc/src/main/java/net/jangaroo/jooc/Parameter.java b/jooc/src/main/java/net/jangaroo/jooc/Parameter.java index ce15e6d29..e338484d4 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/Parameter.java +++ b/jooc/src/main/java/net/jangaroo/jooc/Parameter.java @@ -21,21 +21,40 @@ * @author Andreas Gawecki * @author Frank Wienberg */ -public class Parameter extends AbstractVariableDeclaration { +public class Parameter extends IdeDeclaration { - public Parameter(JooSymbol optSymConst, Ide ide, TypeRelation typeRelation, Initializer optInitializer) { - super(new JooSymbol[0], 0, optSymConst, ide, typeRelation, optInitializer, null); + JooSymbol optSymConstOrRest; + TypeRelation optTypeRelation; + Initializer optInitializer; + + public Parameter(JooSymbol optSymConst, Ide ide, TypeRelation optTypeRelation, Initializer optInitializer) { + super(new JooSymbol[0], 0, ide); + this.optSymConstOrRest = optSymConst; + this.optTypeRelation = optTypeRelation; + this.optInitializer = optInitializer; + } + + @Override + public Node analyze(Node parentNode, AnalyzeContext context) { + super.analyze(parentNode, context); + if (optTypeRelation!=null) { + optTypeRelation.analyze(this, context); + } + if (optInitializer!=null) { + optInitializer.analyze(this, context); + } + return this; } public boolean isRest() { - return optSymConstOrVar!=null && optSymConstOrVar.sym==sym.REST; + return optSymConstOrRest !=null && optSymConstOrRest.sym==sym.REST; } - public void generateIdeCode(JsWriter out) throws IOException { + public void generateCode(JsWriter out) throws IOException { Debug.assertTrue(getModifiers() == 0, "Parameters must not have any modifiers"); boolean isRest = isRest(); - if (optSymConstOrVar != null) { - out.beginCommentWriteSymbol(optSymConstOrVar); + if (optSymConstOrRest != null) { + out.beginCommentWriteSymbol(optSymConstOrRest); if (isRest) { ide.generateCode(out); } @@ -44,13 +63,10 @@ public void generateIdeCode(JsWriter out) throws IOException { if (!isRest) { ide.generateCode(out); } - } - - @Override - protected void generateInitializerCode(JsWriter out) throws IOException { - // in the method signature, as comment only: + // in the method signature, comment out initializer code. out.beginComment(); - super.generateInitializerCode(out); + if (optTypeRelation!=null) + optTypeRelation.generateCode(out); out.endComment(); } diff --git a/jooc/src/main/java/net/jangaroo/jooc/Scope.java b/jooc/src/main/java/net/jangaroo/jooc/Scope.java index c873dc553..5c68f0e2d 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/Scope.java +++ b/jooc/src/main/java/net/jangaroo/jooc/Scope.java @@ -50,6 +50,19 @@ public Node declareIde(String name, Node decl) { return ides.put(name, decl); } + public Node declareIde(String name, Node node, boolean allowDuplicates, JooSymbol ideSymbol) { + Node oldNode = declareIde(name, node); + if (oldNode!=null) { + String msg = "Duplicate declaration of identifier '" + name + "'"; + if (allowDuplicates) { + Jooc.warning(ideSymbol, msg); + } else { + Jooc.error(ideSymbol, msg); + } + } + return oldNode; + } + public void defineLabel(LabeledStatement labeledStatement) { LabeledStatement s = lookupLabel(labeledStatement.ide); if (s != null) diff --git a/jooc/src/main/java/net/jangaroo/jooc/SemicolonTerminatedStatement.java b/jooc/src/main/java/net/jangaroo/jooc/SemicolonTerminatedStatement.java index a4969240b..7b0c62a99 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/SemicolonTerminatedStatement.java +++ b/jooc/src/main/java/net/jangaroo/jooc/SemicolonTerminatedStatement.java @@ -20,19 +20,46 @@ /** * @author Andreas Gawecki */ -abstract class SemicolonTerminatedStatement extends Statement { +class SemicolonTerminatedStatement extends Statement { - JooSymbol symSemicolon; + Node optStatement; + JooSymbol optSymSemicolon; - SemicolonTerminatedStatement(JooSymbol symSemicolon) { - this.symSemicolon = symSemicolon; + /** + * Empty statement. + */ + SemicolonTerminatedStatement(JooSymbol optSymSemicolon) { + this(null, optSymSemicolon); } - protected abstract void generateStatementCode(JsWriter out) throws IOException; + /** + * Optional statement with optional semicolon, but at least one must be specified (non-null). + */ + SemicolonTerminatedStatement(Node optStatement, JooSymbol optSymSemicolon) { + Debug.assertTrue(optStatement!=null || optSymSemicolon!=null, "Both statement and semicolon not specified in SemicolonTerminatedStatement."); + this.optStatement = optStatement; + this.optSymSemicolon = optSymSemicolon; + } + + protected void generateStatementCode(JsWriter out) throws IOException { + if (optStatement!=null) + optStatement.generateCode(out); + } public void generateCode(JsWriter out) throws IOException { generateStatementCode(out); - out.writeSymbol(symSemicolon); + if (optSymSemicolon !=null) + out.writeSymbol(optSymSemicolon); } + public Node analyze(Node parentNode, AnalyzeContext context) { + super.analyze(parentNode, context); + if (optStatement!=null) + optStatement = optStatement.analyze(this, context); + return this; + } + + public JooSymbol getSymbol() { + return optSymSemicolon==null ? optStatement.getSymbol() : optSymSemicolon; + } } diff --git a/jooc/src/main/java/net/jangaroo/jooc/VariableDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/VariableDeclaration.java index f3bb6b0a0..74b7d2024 100644 --- a/jooc/src/main/java/net/jangaroo/jooc/VariableDeclaration.java +++ b/jooc/src/main/java/net/jangaroo/jooc/VariableDeclaration.java @@ -19,24 +19,35 @@ /** * @author Andreas Gawecki + * @author Frank Wienberg */ class VariableDeclaration extends AbstractVariableDeclaration { public VariableDeclaration(JooSymbol symConstOrVar, Ide ide, TypeRelation optTypeRelation, Initializer optInitializer) { - super(new JooSymbol[]{}, 0, symConstOrVar, ide, optTypeRelation, optInitializer, null); + this(symConstOrVar, ide, optTypeRelation, optInitializer, null); } - public void generateIdeCode(JsWriter out) throws IOException { + public VariableDeclaration(JooSymbol symConstOrVar, Ide ide, + TypeRelation optTypeRelation, Initializer optInitializer, VariableDeclaration optNextVariableDeclaration) { + super(new JooSymbol[]{}, 0, symConstOrVar, ide, optTypeRelation, optInitializer, optNextVariableDeclaration, null); + // It is "worst practice" to redeclare local variables in AS3: + allowDuplicates = true; + } + + protected void generateStartCode(JsWriter out) throws IOException { + out.beginComment(); + writeModifiers(out); + out.endComment(); if (optSymConstOrVar != null) { if (isConst()) { out.beginCommentWriteSymbol(optSymConstOrVar); out.endComment(); - out.write("var"); - } else + out.writeToken("var"); + } else { out.writeSymbol(optSymConstOrVar); + } } - ide.generateCode(out); } } diff --git a/jooc/src/test/java/net/jangaroo/test/integration/JooTest.java b/jooc/src/test/java/net/jangaroo/test/integration/JooTest.java index 34d7cb81a..da3379828 100644 --- a/jooc/src/test/java/net/jangaroo/test/integration/JooTest.java +++ b/jooc/src/test/java/net/jangaroo/test/integration/JooTest.java @@ -377,6 +377,15 @@ public void testBind() throws Exception { expectBoolean(true, "package1.TestBind.testStaticNotBound().call('bar')=='bar'"); } + public void testMultiDeclarations() throws Exception { + loadClass("package1.TestMultiDeclarations"); + eval("obj = new package1.TestMultiDeclarations();"); + String expected = (String)eval("package1.TestMultiDeclarations.EXPECTED_RESULT"); + expectString(expected, "obj.testFields()"); + expectString(expected, "obj.testVariables()"); + expectString("[This is a test]", "obj.testForLoops(['This','is','a','test'])"); + } + public static void main(String args[]) { junit.textui.TestRunner.run(JooTest.class); } diff --git a/jooc/src/test/joo/package1/TestMultiDeclarations.as b/jooc/src/test/joo/package1/TestMultiDeclarations.as new file mode 100644 index 000000000..57cc8ff54 --- /dev/null +++ b/jooc/src/test/joo/package1/TestMultiDeclarations.as @@ -0,0 +1,52 @@ +/* + * Copyright 2008 CoreMedia AG + * + * 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 package1 { + +public class TestMultiDeclarations { + + public var a, b; + public var c=1, d : String, e:String="foo"; + public var f:int=2, g:Object = {toString: function():String{return "bar";}}; + + public static const EXPECTED_RESULT : String = "undefined/undefined/1/undefined/foo/2/bar"; + + public function TestMultiDeclarations() { + } + + public function testFields() : String { + return a+"/"+b+"/"+c+"/"+d+"/"+e+"/"+f+"/"+g; + } + + public function testVariables() : String { + var a, b; + var c=1, d : String, e:String="foo"; + var f:int=2, g:Object = {toString: function():String{return "bar";}}; + return a+"/"+b+"/"+c+"/"+d+"/"+e+"/"+f+"/"+g; + } + + public function testForLoops(arr : Array) : String { + var result : String = "["; + for (var i:int=0, l:int=arr.length; i<l; ++i) { + if (i>0) + result+=" "; + result+=arr[i]; + } + result += "]"; + return result; + } + +} +} \ No newline at end of file
802b12feac01aee375f73227d2fad68c58152ab9
Vala
Add mx-1.0 bindings
a
https://github.com/GNOME/vala/
diff --git a/vapi/Makefile.am b/vapi/Makefile.am index 2349dd0bc8..f5606c86de 100644 --- a/vapi/Makefile.am +++ b/vapi/Makefile.am @@ -162,6 +162,8 @@ dist_vapi_DATA = \ linux.vapi \ loudmouth-1.0.vapi \ lua.vapi \ + mx-1.0.deps \ + mx-1.0.vapi \ mysql.vapi \ orc-0.4.vapi \ pango.deps \ diff --git a/vapi/mx-1.0.deps b/vapi/mx-1.0.deps new file mode 100644 index 0000000000..39ce1f0f0d --- /dev/null +++ b/vapi/mx-1.0.deps @@ -0,0 +1 @@ +clutter-1.0 diff --git a/vapi/mx-1.0.vapi b/vapi/mx-1.0.vapi new file mode 100644 index 0000000000..e370eca378 --- /dev/null +++ b/vapi/mx-1.0.vapi @@ -0,0 +1,879 @@ +/* mx-1.0.vapi generated by vapigen, do not modify. */ + +[CCode (cprefix = "Mx", lower_case_cprefix = "mx_")] +namespace Mx { + [CCode (cheader_filename = "mx/mx.h")] + public class Action : GLib.InitiallyUnowned { + [CCode (has_construct_function = false)] + public Action (); + [CCode (has_construct_function = false)] + public Action.full (string name, string display_name, GLib.Callback activated_cb); + public bool get_active (); + public unowned string get_display_name (); + public unowned string get_icon (); + public unowned string get_name (); + public void set_active (bool active); + public void set_display_name (string name); + public void set_icon (string name); + public void set_name (string name); + public bool active { get; set; } + public string display_name { get; set; } + public string icon { get; set; } + public string name { get; set; } + public virtual signal void activated (); + } + [CCode (cheader_filename = "mx/mx.h")] + public class Adjustment : GLib.Object { + [CCode (has_construct_function = false)] + public Adjustment (); + public bool get_elastic (); + public double get_lower (); + public double get_page_increment (); + public double get_page_size (); + public double get_step_increment (); + public double get_upper (); + public double get_value (); + public void get_values (double value, double lower, double upper, double step_increment, double page_increment, double page_size); + public void interpolate (double value, uint duration, ulong mode); + public void interpolate_relative (double offset, uint duration, ulong mode); + public void set_elastic (bool elastic); + public void set_lower (double lower); + public void set_page_increment (double increment); + public void set_page_size (double page_size); + public void set_step_increment (double increment); + public void set_upper (double upper); + public void set_value (double value); + public void set_values (double value, double lower, double upper, double step_increment, double page_increment, double page_size); + [CCode (has_construct_function = false)] + public Adjustment.with_values (double value, double lower, double upper, double step_increment, double page_increment, double page_size); + public bool elastic { get; set construct; } + public double lower { get; set construct; } + public double page_increment { get; set construct; } + public double page_size { get; set construct; } + public double step_increment { get; set construct; } + public double upper { get; set construct; } + public double value { get; set construct; } + public virtual signal void changed (); + } + [CCode (cheader_filename = "mx/mx.h")] + public class Application : GLib.Object { + [CCode (has_construct_function = false)] + public Application ([CCode (array_length_pos = 0.9)] ref unowned string[] argv, string name, Mx.ApplicationFlags flags); + public void add_action (Mx.Action action); + public void add_window (Mx.Window window); + public virtual unowned Mx.Window create_window (); + public unowned GLib.List get_actions (); + public Mx.ApplicationFlags get_flags (); + public unowned GLib.List get_windows (); + public void invoke_action (string name); + public bool is_running (); + public void quit (); + [NoWrapper] + public virtual void raise (); + public void remove_action (string name); + public void remove_window (Mx.Window window); + public void run (); + [NoAccessorMethod] + public string application_name { owned get; construct; } + public uint flags { get; construct; } + public virtual signal void actions_changed (); + } + [CCode (cheader_filename = "mx/mx.h")] + public class Bin : Mx.Widget, Clutter.Scriptable, Mx.Stylable, Clutter.Container, Mx.Focusable { + public void allocate_child (Clutter.ActorBox box, Clutter.AllocationFlags flags); + public void get_alignment (Mx.Align x_align, Mx.Align y_align); + public unowned Clutter.Actor get_child (); + public void get_fill (bool x_fill, bool y_fill); + public void set_alignment (Mx.Align x_align, Mx.Align y_align); + public void set_child (Clutter.Actor child); + public void set_fill (bool x_fill, bool y_fill); + public Clutter.Actor child { get; set; } + [NoAccessorMethod] + public Mx.Align x_align { get; set; } + [NoAccessorMethod] + public bool x_fill { get; set; } + [NoAccessorMethod] + public Mx.Align y_align { get; set; } + [NoAccessorMethod] + public bool y_fill { get; set; } + } + [Compact] + [CCode (type_id = "MX_TYPE_BORDER_IMAGE", cheader_filename = "mx/mx.h")] + public class BorderImage { + public int bottom; + public int left; + public int right; + public int top; + public weak string uri; + public static void set_from_string (GLib.Value value, string str, string filename); + } + [CCode (cheader_filename = "mx/mx.h")] + public class BoxLayout : Mx.Widget, Clutter.Scriptable, Mx.Stylable, Clutter.Container, Mx.Scrollable, Mx.Focusable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public BoxLayout (); + public void add_actor_with_properties (Clutter.Actor actor, int position, ...); + public bool get_enable_animations (); + public Mx.Orientation get_orientation (); + public uint get_spacing (); + public void set_enable_animations (bool enable_animations); + public void set_orientation (Mx.Orientation orientation); + public void set_spacing (uint spacing); + public bool enable_animations { get; set; } + public Mx.Orientation orientation { get; set; } + public uint spacing { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class BoxLayoutChild : Clutter.ChildMeta { + public static bool get_expand (Mx.BoxLayout box_layout, Clutter.Actor child); + public static Mx.Align get_x_align (Mx.BoxLayout box_layout, Clutter.Actor child); + public static bool get_x_fill (Mx.BoxLayout box_layout, Clutter.Actor child); + public static Mx.Align get_y_align (Mx.BoxLayout box_layout, Clutter.Actor child); + public static bool get_y_fill (Mx.BoxLayout box_layout, Clutter.Actor child); + public static void set_expand (Mx.BoxLayout box_layout, Clutter.Actor child, bool expand); + public static void set_x_align (Mx.BoxLayout box_layout, Clutter.Actor child, Mx.Align x_align); + public static void set_x_fill (Mx.BoxLayout box_layout, Clutter.Actor child, bool x_fill); + public static void set_y_align (Mx.BoxLayout box_layout, Clutter.Actor child, Mx.Align y_align); + public static void set_y_fill (Mx.BoxLayout box_layout, Clutter.Actor child, bool y_fill); + public bool expand { get; set; } + public Mx.Align x_align { get; set; } + public bool x_fill { get; set; } + public Mx.Align y_align { get; set; } + public bool y_fill { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class Button : Mx.Bin, Clutter.Scriptable, Mx.Stylable, Clutter.Container, Mx.Focusable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public Button (); + public bool get_is_toggle (); + public unowned string get_label (); + public bool get_toggled (); + public void set_is_toggle (bool toggle); + public void set_label (string text); + public void set_toggled (bool toggled); + [CCode (type = "ClutterActor*", has_construct_function = false)] + public Button.with_label (string text); + public bool is_toggle { get; set; } + public string label { get; set; } + public bool toggled { get; set; } + public virtual signal void clicked (); + } + [CCode (cheader_filename = "mx/mx.h")] + public class ButtonGroup : GLib.InitiallyUnowned { + [CCode (has_construct_function = false)] + public ButtonGroup (); + public void add (Mx.Button button); + public void @foreach (Clutter.Callback callback); + public unowned Mx.Button get_active_button (); + public bool get_allow_no_active (); + public unowned GLib.SList get_buttons (); + public void remove (Mx.Button button); + public void set_active_button (Mx.Button? button); + public void set_allow_no_active (bool allow_no_active); + public Mx.Button active_button { get; set; } + public bool allow_no_active { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class Clipboard : GLib.Object { + public static unowned Mx.Clipboard get_default (); + public void get_text (Mx.ClipboardCallbackFunc callback); + public void set_text (string text); + } + [CCode (cheader_filename = "mx/mx.h")] + public class ComboBox : Mx.Widget, Clutter.Scriptable, Mx.Stylable, Mx.Focusable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public ComboBox (); + public void append_text (string text); + public unowned string get_active_icon_name (); + public unowned string get_active_text (); + public int get_index (); + public void insert_text (int position, string text); + public void insert_text_with_icon (int position, string text, string icon); + public void prepend_text (string text); + public void remove_text (int position); + public void set_active_icon_name (string icon_name); + public void set_active_text (string text); + public void set_index (int index); + public string active_icon_name { get; set; } + public string active_text { get; set; } + public int index { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class DeformBowTie : Mx.DeformTexture, Clutter.Scriptable, Mx.Stylable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public DeformBowTie (); + public bool get_flip_back (); + public double get_period (); + public void set_flip_back (bool flip_back); + public void set_period (double period); + public bool flip_back { get; set; } + public double period { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class DeformPageTurn : Mx.DeformTexture, Clutter.Scriptable, Mx.Stylable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public DeformPageTurn (); + public double get_angle (); + public double get_period (); + public double get_radius (); + public void set_angle (double angle); + public void set_period (double period); + public void set_radius (double radius); + public double angle { get; set; } + public double period { get; set; } + public double radius { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class DeformTexture : Mx.Widget, Clutter.Scriptable, Mx.Stylable { + [NoWrapper] + public virtual void deform (Cogl.TextureVertex vertex, float width, float height); + public void get_resolution (int tiles_x, int tiles_y); + public void get_textures (out unowned Clutter.Texture front, out unowned Clutter.Texture back); + public void invalidate (); + public void set_resolution (int tiles_x, int tiles_y); + public void set_textures (Clutter.Texture front, Clutter.Texture back); + [NoAccessorMethod] + public Clutter.Texture back { owned get; set; } + [NoAccessorMethod] + public Clutter.Texture front { owned get; set; } + [NoAccessorMethod] + public int tiles_x { get; set; } + [NoAccessorMethod] + public int tiles_y { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class DeformWaves : Mx.DeformTexture, Clutter.Scriptable, Mx.Stylable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public DeformWaves (); + public double get_amplitude (); + public double get_angle (); + public double get_period (); + public double get_radius (); + public void set_amplitude (double amplitude); + public void set_angle (double angle); + public void set_period (double period); + public void set_radius (double radius); + public double amplitude { get; set; } + public double angle { get; set; } + public double period { get; set; } + public double radius { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class Entry : Mx.Widget, Clutter.Scriptable, Mx.Stylable, Mx.Focusable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public Entry (); + public unowned Clutter.Actor get_clutter_text (); + public unowned string get_hint_text (); + public unichar get_password_char (); + public unowned string get_text (); + public void set_hint_text (string text); + public void set_password_char (unichar password_char); + public void set_primary_icon_from_file (string filename); + public void set_secondary_icon_from_file (string filename); + public void set_text (string text); + [CCode (type = "ClutterActor*", has_construct_function = false)] + public Entry.with_text (string text); + public Clutter.Text clutter_text { get; } + public string hint_text { get; set; } + public uint password_char { get; set; } + public string text { get; set; } + public virtual signal void primary_icon_clicked (); + public virtual signal void secondary_icon_clicked (); + } + [CCode (cheader_filename = "mx/mx.h")] + public class Expander : Mx.Bin, Clutter.Scriptable, Mx.Stylable, Clutter.Container, Mx.Focusable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public Expander (); + public bool get_expanded (); + public void set_expanded (bool expanded); + public void set_label (string label); + public bool expanded { get; set; } + [NoAccessorMethod] + public string label { owned get; set; } + public virtual signal void expand_complete (); + } + [CCode (cheader_filename = "mx/mx.h")] + public class FloatingWidget : Mx.Widget, Clutter.Scriptable, Mx.Stylable { + [NoWrapper] + public virtual void floating_paint (Clutter.Actor actor); + [NoWrapper] + public virtual void floating_pick (Clutter.Actor actor, Clutter.Color color); + } + [CCode (cheader_filename = "mx/mx.h")] + public class FocusManager : GLib.Object { + public unowned Mx.Focusable get_focused (); + public static unowned Mx.FocusManager get_for_stage (Clutter.Stage stage); + public unowned Clutter.Stage get_stage (); + public void move_focus (Mx.FocusDirection direction); + public void push_focus (Mx.Focusable focusable); + public Clutter.Actor focused { get; } + public Clutter.Stage stage { get; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class Frame : Mx.Bin, Clutter.Scriptable, Mx.Stylable, Clutter.Container, Mx.Focusable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public Frame (); + } + [CCode (cheader_filename = "mx/mx.h")] + public class Grid : Mx.Widget, Clutter.Scriptable, Mx.Stylable, Clutter.Container, Mx.Scrollable, Mx.Focusable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public Grid (); + public Mx.Align get_child_x_align (); + public Mx.Align get_child_y_align (); + public float get_column_spacing (); + public bool get_homogenous_columns (); + public bool get_homogenous_rows (); + public bool get_line_alignment (); + public int get_max_stride (); + public Mx.Orientation get_orientation (); + public float get_row_spacing (); + public void set_child_x_align (Mx.Align value); + public void set_child_y_align (Mx.Align value); + public void set_column_spacing (float value); + public void set_homogenous_columns (bool value); + public void set_homogenous_rows (bool value); + public void set_line_alignment (Mx.Align value); + public void set_max_stride (int value); + public void set_orientation (Mx.Orientation orientation); + public void set_row_spacing (float value); + public Mx.Align child_x_align { get; set construct; } + public Mx.Align child_y_align { get; set construct; } + public float column_spacing { get; set construct; } + public bool homogenous_columns { get; set construct; } + public bool homogenous_rows { get; set construct; } + public Mx.Align line_alignment { get; set construct; } + public int max_stride { get; set construct; } + public Mx.Orientation orientation { get; set construct; } + public float row_spacing { get; set construct; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class Icon : Mx.Widget, Clutter.Scriptable, Mx.Stylable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public Icon (); + public unowned string get_icon_name (); + public int get_icon_size (); + public void set_icon_name (string icon_name); + public void set_icon_size (int size); + public string icon_name { get; set; } + public int icon_size { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class IconTheme : GLib.Object { + [CCode (has_construct_function = false)] + public IconTheme (); + public static unowned Mx.IconTheme get_default (); + public unowned GLib.List get_search_paths (); + public unowned string get_theme_name (); + public bool has_icon (string icon_name); + public unowned Cogl.Bitmap lookup (string icon_name, int size); + public unowned Clutter.Texture lookup_texture (string icon_name, int size); + public void set_search_paths (GLib.List paths); + public void set_theme_name (string theme_name); + public string theme_name { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class ItemView : Mx.Grid, Clutter.Scriptable, Mx.Stylable, Clutter.Container, Mx.Scrollable, Mx.Focusable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public ItemView (); + public void add_attribute (string attribute, int column); + public void freeze (); + public unowned Mx.ItemFactory get_factory (); + public GLib.Type get_item_type (); + public unowned Clutter.Model get_model (); + public void set_factory (Mx.ItemFactory factory); + public void set_item_type (GLib.Type item_type); + public void set_model (Clutter.Model model); + public void thaw (); + public GLib.Object factory { get; set; } + public GLib.Type item_type { get; set; } + public Clutter.Model model { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class Label : Mx.Widget, Clutter.Scriptable, Mx.Stylable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public Label (); + public unowned Clutter.Actor get_clutter_text (); + public unowned string get_text (); + public Mx.Align get_x_align (); + public Mx.Align get_y_align (); + public void set_text (string text); + public void set_x_align (Mx.Align align); + public void set_y_align (Mx.Align align); + [CCode (type = "ClutterActor*", has_construct_function = false)] + public Label.with_text (string text); + public Clutter.Text clutter_text { get; } + public string text { get; set; } + public Mx.Align x_align { get; set; } + public Mx.Align y_align { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class ListView : Mx.BoxLayout, Clutter.Scriptable, Mx.Stylable, Clutter.Container, Mx.Scrollable, Mx.Focusable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public ListView (); + public void add_attribute (string attribute, int column); + public void freeze (); + public unowned Mx.ItemFactory get_factory (); + public GLib.Type get_item_type (); + public unowned Clutter.Model get_model (); + public void set_factory (Mx.ItemFactory factory); + public void set_item_type (GLib.Type item_type); + public void set_model (Clutter.Model model); + public void thaw (); + public GLib.Object factory { get; set; } + public GLib.Type item_type { get; set; } + public Clutter.Model model { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class Menu : Mx.FloatingWidget, Clutter.Scriptable, Mx.Stylable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public Menu (); + public void add_action (Mx.Action action); + public void remove_action (Mx.Action action); + public void remove_all (); + public void show_with_position (float x, float y); + public virtual signal void action_activated (Mx.Action action); + } + [CCode (cheader_filename = "mx/mx.h")] + public class Notebook : Mx.Widget, Clutter.Scriptable, Mx.Stylable, Clutter.Container { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public Notebook (); + public unowned Clutter.Actor get_current_page (); + public bool get_enable_gestures (); + public void set_current_page (Clutter.Actor page); + public void set_enable_gestures (bool enabled); + public Clutter.Actor current_page { get; set; } + public bool enable_gestures { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class Offscreen : Clutter.Texture, Clutter.Scriptable, Clutter.Container { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public Offscreen (); + public bool get_auto_update (); + public unowned Clutter.Actor get_child (); + public bool get_pick_child (); + [NoWrapper] + public virtual void paint_child (); + public void set_auto_update (bool auto_update); + public void set_child (Clutter.Actor actor); + public void set_pick_child (bool pick); + public void update (); + public bool auto_update { get; set; } + public Clutter.Actor child { get; set; } + public bool pick_child { get; set; } + } + [Compact] + [CCode (type_id = "MX_TYPE_PADDING", cheader_filename = "mx/mx.h")] + public class Padding { + public float bottom; + public float left; + public float right; + public float top; + } + [CCode (cheader_filename = "mx/mx.h")] + public class PathBar : Mx.Widget, Clutter.Scriptable, Mx.Stylable, Mx.Focusable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public PathBar (); + public void clear (); + public bool get_clear_on_change (); + public bool get_editable (); + public unowned Mx.Entry get_entry (); + public unowned string get_label (int level); + public int get_level (); + public unowned string get_text (); + public int pop (); + public int push (string name); + public void set_clear_on_change (bool clear_on_change); + public void set_editable (bool editable); + public void set_label (int level, string label); + public void set_text (string text); + public bool clear_on_change { get; set; } + public bool editable { get; set; } + public Mx.Entry entry { get; } + public int level { get; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class ProgressBar : Mx.Widget, Clutter.Scriptable, Mx.Stylable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public ProgressBar (); + public double get_progress (); + public void set_progress (double progress); + public double progress { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class ScrollBar : Mx.Bin, Clutter.Scriptable, Mx.Stylable, Clutter.Container, Mx.Focusable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public ScrollBar (); + public unowned Mx.Adjustment get_adjustment (); + public Mx.Orientation get_orientation (); + public void set_adjustment (Mx.Adjustment adjustment); + public void set_orientation (Mx.Orientation orientation); + [CCode (type = "ClutterActor*", has_construct_function = false)] + public ScrollBar.with_adjustment (Mx.Adjustment adjustment); + public Mx.Adjustment adjustment { get; set; } + public Mx.Orientation orientation { get; set; } + public virtual signal void scroll_start (); + public virtual signal void scroll_stop (); + } + [CCode (cheader_filename = "mx/mx.h")] + public class ScrollView : Mx.Bin, Clutter.Scriptable, Mx.Stylable, Clutter.Container, Mx.Focusable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public ScrollView (); + public void ensure_visible (Clutter.Geometry geometry); + public bool get_enable_gestures (); + public bool get_enable_mouse_scrolling (); + public Mx.ScrollPolicy get_scroll_policy (); + public void set_enable_gestures (bool enabled); + public void set_enable_mouse_scrolling (bool enabled); + public void set_scroll_policy (Mx.ScrollPolicy policy); + public bool enable_gestures { get; set; } + public bool enable_mouse_scrolling { get; set; } + public Mx.ScrollPolicy scroll_policy { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class Slider : Mx.Widget, Clutter.Scriptable, Mx.Stylable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public Slider (); + public double get_value (); + public void set_value (double value); + public double value { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class Style : GLib.Object { + [CCode (has_construct_function = false)] + public Style (); + public void @get (Mx.Stylable stylable, ...); + public static unowned Mx.Style get_default (); + public void get_property (Mx.Stylable stylable, Clutter.ParamSpecColor pspec, GLib.Value value); + public void get_valist (Mx.Stylable stylable, string first_property_name, void* va_args); + public bool load_from_file (string filename) throws GLib.Error; + public virtual signal void changed (); + } + [CCode (cheader_filename = "mx/mx.h")] + public class Table : Mx.Widget, Clutter.Scriptable, Mx.Stylable, Clutter.Container, Mx.Focusable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public Table (); + public void add_actor_with_properties (Clutter.Actor actor, int row, int column, ...); + public int get_column_count (); + public int get_column_spacing (); + public int get_row_count (); + public int get_row_spacing (); + public void set_column_spacing (int spacing); + public void set_row_spacing (int spacing); + public int column_count { get; } + public int column_spacing { get; set; } + public int row_count { get; } + public int row_spacing { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class TableChild : Clutter.ChildMeta { + public static int get_column (Mx.Table table, Clutter.Actor child); + public static int get_column_span (Mx.Table table, Clutter.Actor child); + public static int get_row (Mx.Table table, Clutter.Actor child); + public static int get_row_span (Mx.Table table, Clutter.Actor child); + public static Mx.Align get_x_align (Mx.Table table, Clutter.Actor child); + public static bool get_x_expand (Mx.Table table, Clutter.Actor child); + public static bool get_x_fill (Mx.Table table, Clutter.Actor child); + public static Mx.Align get_y_align (Mx.Table table, Clutter.Actor child); + public static bool get_y_expand (Mx.Table table, Clutter.Actor child); + public static bool get_y_fill (Mx.Table table, Clutter.Actor child); + public static void set_column (Mx.Table table, Clutter.Actor child, int col); + public static void set_column_span (Mx.Table table, Clutter.Actor child, int span); + public static void set_row (Mx.Table table, Clutter.Actor child, int row); + public static void set_row_span (Mx.Table table, Clutter.Actor child, int span); + public static void set_x_align (Mx.Table table, Clutter.Actor child, Mx.Align align); + public static void set_x_expand (Mx.Table table, Clutter.Actor child, bool expand); + public static void set_x_fill (Mx.Table table, Clutter.Actor child, bool fill); + public static void set_y_align (Mx.Table table, Clutter.Actor child, Mx.Align align); + public static void set_y_expand (Mx.Table table, Clutter.Actor child, bool expand); + public static void set_y_fill (Mx.Table table, Clutter.Actor child, bool fill); + public int column { get; set; } + public int column_span { get; set; } + public int row { get; set; } + public int row_span { get; set; } + public Mx.Align x_align { get; set; } + public bool x_expand { get; set; } + public bool x_fill { get; set; } + public Mx.Align y_align { get; set; } + public bool y_expand { get; set; } + public bool y_fill { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class TextureCache : GLib.Object { + [NoWrapper] + public virtual void error_loading (GLib.Error error); + public unowned Clutter.Actor get_actor (string path); + public unowned Cogl.Bitmap get_cogl_texture (string path); + public static unowned Mx.TextureCache get_default (); + public int get_size (); + public unowned Clutter.Texture get_texture (string path); + public void load_cache (string filename); + [NoWrapper] + public virtual void loaded (string path, Clutter.Texture texture); + } + [CCode (cheader_filename = "mx/mx.h")] + public class TextureFrame : Clutter.Actor, Clutter.Scriptable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public TextureFrame (Clutter.Texture texture, float top, float right, float bottom, float left); + public void get_border_values (float top, float right, float bottom, float left); + public unowned Clutter.Texture get_parent_texture (); + public void set_border_values (float top, float right, float bottom, float left); + public void set_parent_texture (Clutter.Texture texture); + [NoAccessorMethod] + public float bottom { get; set construct; } + [NoAccessorMethod] + public float left { get; set construct; } + public Clutter.Texture parent_texture { get; set construct; } + [NoAccessorMethod] + public float right { get; set construct; } + [NoAccessorMethod] + public float top { get; set construct; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class Toggle : Mx.Widget, Clutter.Scriptable, Mx.Stylable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public Toggle (); + public bool get_active (); + public void set_active (bool active); + public bool active { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class Toolbar : Mx.Bin, Clutter.Scriptable, Mx.Stylable, Clutter.Container, Mx.Focusable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public Toolbar (); + public bool get_has_close_button (); + public void set_has_close_button (bool has_close_button); + public bool has_close_button { get; set; } + public virtual signal bool close_button_clicked (); + } + [CCode (cheader_filename = "mx/mx.h")] + public class Tooltip : Mx.FloatingWidget, Clutter.Scriptable, Mx.Stylable { + public unowned string get_text (); + public Clutter.Geometry get_tip_area (); + public void hide (); + public void set_text (string text); + public void set_tip_area (Clutter.Geometry area); + public void show (); + public string text { get; set; } + public Clutter.Geometry tip_area { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class Viewport : Mx.Bin, Clutter.Scriptable, Mx.Stylable, Clutter.Container, Mx.Focusable, Mx.Scrollable { + [CCode (type = "ClutterActor*", has_construct_function = false)] + public Viewport (); + public void get_origin (float x, float y, float z); + public bool get_sync_adjustments (); + public void set_origin (float x, float y, float z); + public void set_sync_adjustments (bool sync); + public bool sync_adjustments { get; set; } + [NoAccessorMethod] + public float x_origin { get; set; } + [NoAccessorMethod] + public float y_origin { get; set; } + [NoAccessorMethod] + public float z_origin { get; set; } + } + [CCode (cheader_filename = "mx/mx.h")] + public class Widget : Clutter.Actor, Clutter.Scriptable, Mx.Stylable { + public void get_available_area (Clutter.ActorBox allocation, Clutter.ActorBox area); + public unowned Clutter.Actor get_background_image (); + public unowned Clutter.Actor get_border_image (); + public bool get_disabled (); + public unowned Mx.Menu get_menu (); + public void get_padding (Mx.Padding padding); + public unowned string get_tooltip_text (); + public void hide_tooltip (); + public void long_press_cancel (); + public void long_press_query (Clutter.ButtonEvent event); + public virtual void paint_background (); + public void set_disabled (bool disabled); + public void set_menu (Mx.Menu menu); + public void set_tooltip_text (string text); + public void show_tooltip (); + public bool disabled { get; set; } + public Mx.Menu menu { get; set; } + public string tooltip_text { get; set; } + public virtual signal bool long_press (float action, float x, Mx.LongPressAction y); + } + [CCode (cheader_filename = "mx/mx.h")] + public class Window : GLib.Object { + [CCode (has_construct_function = false)] + public Window (); + public unowned Clutter.Actor get_child (); + public unowned Clutter.Stage get_clutter_stage (); + public static unowned Mx.Window get_for_stage (Clutter.Stage stage); + public bool get_has_toolbar (); + public unowned string get_icon_name (); + public bool get_small_screen (); + public unowned Mx.Toolbar get_toolbar (); + public void get_window_position (int x, int y); + public void set_child (Clutter.Actor actor); + public void set_has_toolbar (bool toolbar); + public void set_icon_from_cogl_texture (Cogl.Bitmap texture); + public void set_icon_name (string icon_name); + public void set_small_screen (bool small_screen); + public void set_window_position (int x, int y); + [CCode (has_construct_function = false)] + public Window.with_clutter_stage (Clutter.Stage stage); + public Clutter.Actor child { get; set; } + public Clutter.Stage clutter_stage { get; construct; } + public bool has_toolbar { get; set; } + [NoAccessorMethod] + public string icon_cogl_texture { set; } + public string icon_name { get; set; } + public bool small_screen { get; set; } + public Mx.Toolbar toolbar { get; } + public virtual signal void destroy (); + } + [CCode (cheader_filename = "mx/mx.h")] + public interface Draggable : Clutter.Actor { + public abstract void disable (); + public abstract void enable (); + public Mx.DragAxis get_axis (); + public unowned Clutter.Actor get_drag_actor (); + public uint get_drag_threshold (); + public bool is_enabled (); + public void set_axis (Mx.DragAxis axis); + public void set_drag_actor (Clutter.Actor actor); + public void set_drag_threshold (uint threshold); + public Mx.DragAxis axis { get; set; } + public Clutter.Actor drag_actor { get; set; } + public bool drag_enabled { get; set; } + public uint drag_threshold { get; set; } + public signal void drag_begin (float event_x, float event_y, int event_button, Clutter.ModifierType modifiers); + public signal void drag_end (float event_x, float event_y); + public signal void drag_motion (float delta_x, float delta_y); + } + [CCode (cheader_filename = "mx/mx.h")] + public interface Droppable : Clutter.Actor { + public abstract bool accept_drop (Mx.Draggable draggable); + public abstract void disable (); + public abstract void enable (); + public bool is_enabled (); + public bool drop_enabled { get; set; } + public signal void drop (Clutter.Actor draggable, float event_x, float event_y, int button, Clutter.ModifierType modifiers); + public signal void over_in (Clutter.Actor draggable); + public signal void over_out (Clutter.Actor draggable); + } + [CCode (cheader_filename = "mx/mx.h")] + public interface Focusable { + public abstract unowned Mx.Focusable accept_focus (Mx.FocusHint hint); + public abstract unowned Mx.Focusable move_focus (Mx.FocusDirection direction, Mx.Focusable from); + } + [CCode (cheader_filename = "mx/mx.h")] + public interface ItemFactory { + public abstract unowned Clutter.Actor create (); + } + [CCode (cheader_filename = "mx/mx.h")] + public interface Scrollable { + public abstract void get_adjustments (out unowned Mx.Adjustment hadjustment, out unowned Mx.Adjustment vadjustment); + public abstract void set_adjustments (Mx.Adjustment hadjustment, Mx.Adjustment vadjustment); + } + [CCode (cheader_filename = "mx/mx.h")] + public interface Stylable { + public void apply_clutter_text_attributes (Clutter.Text text); + public void connect_change_notifiers (); + public unowned Clutter.ParamSpecColor find_property (string property_name); + public void @get (...); + public bool get_default_value (string property_name, GLib.Value value_out); + public void get_property (string property_name, GLib.Value value); + public abstract unowned Mx.Style get_style (); + public abstract unowned string get_style_class (); + public abstract unowned string get_style_pseudo_class (); + public unowned Clutter.ParamSpecColor list_properties (uint n_props); + public abstract void set_style (Mx.Style style); + public abstract void set_style_class (string style_class); + public abstract void set_style_pseudo_class (string pseudo_class); + [HasEmitter] + public signal void style_changed (Mx.StyleChangedFlags flags); + } + [CCode (cprefix = "MX_ALIGN_", cheader_filename = "mx/mx.h")] + public enum Align { + START, + MIDDLE, + END + } + [CCode (cprefix = "MX_APPLICATION_", cheader_filename = "mx/mx.h")] + [Flags] + public enum ApplicationFlags { + SINGLE_INSTANCE, + KEEP_ALIVE + } + [CCode (cprefix = "MX_DRAG_AXIS_", cheader_filename = "mx/mx.h")] + public enum DragAxis { + NONE, + X, + Y + } + [CCode (cprefix = "MX_FOCUS_DIRECTION_", cheader_filename = "mx/mx.h")] + public enum FocusDirection { + OUT, + UP, + DOWN, + LEFT, + RIGHT, + NEXT, + PREVIOUS + } + [CCode (cprefix = "MX_FOCUS_HINT_", cheader_filename = "mx/mx.h")] + public enum FocusHint { + FIRST, + LAST, + PRIOR + } + [CCode (cprefix = "MX_FONT_WEIGHT_", cheader_filename = "mx/mx.h")] + public enum FontWeight { + NORMAL, + BOLD, + BOLDER, + LIGHTER + } + [CCode (cprefix = "MX_LONG_PRESS_", cheader_filename = "mx/mx.h")] + public enum LongPressAction { + QUERY, + ACTION, + CANCEL + } + [CCode (cprefix = "MX_ORIENTATION_", cheader_filename = "mx/mx.h")] + public enum Orientation { + HORIZONTAL, + VERTICAL + } + [CCode (cprefix = "MX_SCROLL_POLICY_", cheader_filename = "mx/mx.h")] + public enum ScrollPolicy { + NONE, + HORIZONTAL, + VERTICAL, + BOTH + } + [CCode (cprefix = "MX_STYLE_CHANGED_", cheader_filename = "mx/mx.h")] + [Flags] + public enum StyleChangedFlags { + NONE, + FORCE + } + [CCode (cprefix = "MX_STYLE_ERROR_INVALID_", cheader_filename = "mx/mx.h")] + public enum StyleError { + FILE + } + [CCode (cheader_filename = "mx/mx.h")] + public delegate void ClipboardCallbackFunc (Mx.Clipboard clipboard, string text); + [CCode (cheader_filename = "mx/mx.h")] + public const int MAJOR_VERSION; + [CCode (cheader_filename = "mx/mx.h")] + public const int MICRO_VERSION; + [CCode (cheader_filename = "mx/mx.h")] + public const int MINOR_VERSION; + [CCode (cheader_filename = "mx/mx.h")] + public const int VERSION_HEX; + [CCode (cheader_filename = "mx/mx.h")] + public const string VERSION_S; + [CCode (cheader_filename = "mx/mx.h")] + public static void actor_box_clamp_to_pixels (Clutter.ActorBox box); + [CCode (cheader_filename = "mx/mx.h")] + public static void allocate_align_fill (Clutter.Actor child, Clutter.ActorBox childbox, Mx.Align x_alignment, Mx.Align y_alignment, bool x_fill, bool y_fill); + [CCode (cheader_filename = "mx/mx.h")] + public static void font_weight_set_from_string (GLib.Value value, string str); + [CCode (cheader_filename = "mx/mx.h")] + public static void set_locale (); + [CCode (cheader_filename = "mx/mx.h")] + public static unowned string utils_format_time (GLib.TimeVal time_); +} diff --git a/vapi/packages/mx-1.0/mx-1.0.defines b/vapi/packages/mx-1.0/mx-1.0.defines new file mode 100644 index 0000000000..aaa5198643 --- /dev/null +++ b/vapi/packages/mx-1.0/mx-1.0.defines @@ -0,0 +1,2 @@ +-DMX_H_INSIDE +-D__MX_H__ \ No newline at end of file diff --git a/vapi/packages/mx-1.0/mx-1.0.deps b/vapi/packages/mx-1.0/mx-1.0.deps new file mode 100644 index 0000000000..39ce1f0f0d --- /dev/null +++ b/vapi/packages/mx-1.0/mx-1.0.deps @@ -0,0 +1 @@ +clutter-1.0 diff --git a/vapi/packages/mx-1.0/mx-1.0.excludes b/vapi/packages/mx-1.0/mx-1.0.excludes new file mode 100644 index 0000000000..319e66f775 --- /dev/null +++ b/vapi/packages/mx-1.0/mx-1.0.excludes @@ -0,0 +1,5 @@ +mx.h +mx-gtk.h +mx-gtk-expander.h +mx-gtk-frame.h +mx-gtk-light-switch.h diff --git a/vapi/packages/mx-1.0/mx-1.0.files b/vapi/packages/mx-1.0/mx-1.0.files new file mode 100644 index 0000000000..8a2ae3d22c --- /dev/null +++ b/vapi/packages/mx-1.0/mx-1.0.files @@ -0,0 +1,2 @@ +include/mx-1.0/mx/mx-*.h +lib/libmx-1.0.so diff --git a/vapi/packages/mx-1.0/mx-1.0.gi b/vapi/packages/mx-1.0/mx-1.0.gi new file mode 100644 index 0000000000..65f00ad1c8 --- /dev/null +++ b/vapi/packages/mx-1.0/mx-1.0.gi @@ -0,0 +1,3379 @@ +<?xml version="1.0"?> +<api version="1.0"> + <namespace name="Mx"> + <function name="actor_box_clamp_to_pixels" symbol="mx_actor_box_clamp_to_pixels"> + <return-type type="void"/> + <parameters> + <parameter name="box" type="ClutterActorBox*"/> + </parameters> + </function> + <function name="allocate_align_fill" symbol="mx_allocate_align_fill"> + <return-type type="void"/> + <parameters> + <parameter name="child" type="ClutterActor*"/> + <parameter name="childbox" type="ClutterActorBox*"/> + <parameter name="x_alignment" type="MxAlign"/> + <parameter name="y_alignment" type="MxAlign"/> + <parameter name="x_fill" type="gboolean"/> + <parameter name="y_fill" type="gboolean"/> + </parameters> + </function> + <function name="font_weight_set_from_string" symbol="mx_font_weight_set_from_string"> + <return-type type="void"/> + <parameters> + <parameter name="value" type="GValue*"/> + <parameter name="str" type="gchar*"/> + </parameters> + </function> + <function name="set_locale" symbol="mx_set_locale"> + <return-type type="void"/> + </function> + <function name="utils_format_time" symbol="mx_utils_format_time"> + <return-type type="gchar*"/> + <parameters> + <parameter name="time_" type="GTimeVal*"/> + </parameters> + </function> + <callback name="MxClipboardCallbackFunc"> + <return-type type="void"/> + <parameters> + <parameter name="clipboard" type="MxClipboard*"/> + <parameter name="text" type="gchar*"/> + <parameter name="user_data" type="gpointer"/> + </parameters> + </callback> + <boxed name="MxBorderImage" type-name="MxBorderImage" get-type="mx_border_image_get_type"> + <method name="set_from_string" symbol="mx_border_image_set_from_string"> + <return-type type="void"/> + <parameters> + <parameter name="value" type="GValue*"/> + <parameter name="str" type="gchar*"/> + <parameter name="filename" type="gchar*"/> + </parameters> + </method> + <field name="uri" type="gchar*"/> + <field name="top" type="gint"/> + <field name="right" type="gint"/> + <field name="bottom" type="gint"/> + <field name="left" type="gint"/> + </boxed> + <boxed name="MxPadding" type-name="MxPadding" get-type="mx_padding_get_type"> + <field name="top" type="gfloat"/> + <field name="right" type="gfloat"/> + <field name="bottom" type="gfloat"/> + <field name="left" type="gfloat"/> + </boxed> + <enum name="MxAlign" type-name="MxAlign" get-type="mx_align_get_type"> + <member name="MX_ALIGN_START" value="0"/> + <member name="MX_ALIGN_MIDDLE" value="1"/> + <member name="MX_ALIGN_END" value="2"/> + </enum> + <enum name="MxDragAxis" type-name="MxDragAxis" get-type="mx_drag_axis_get_type"> + <member name="MX_DRAG_AXIS_NONE" value="0"/> + <member name="MX_DRAG_AXIS_X" value="1"/> + <member name="MX_DRAG_AXIS_Y" value="2"/> + </enum> + <enum name="MxFocusDirection" type-name="MxFocusDirection" get-type="mx_focus_direction_get_type"> + <member name="MX_FOCUS_DIRECTION_OUT" value="0"/> + <member name="MX_FOCUS_DIRECTION_UP" value="1"/> + <member name="MX_FOCUS_DIRECTION_DOWN" value="2"/> + <member name="MX_FOCUS_DIRECTION_LEFT" value="3"/> + <member name="MX_FOCUS_DIRECTION_RIGHT" value="4"/> + <member name="MX_FOCUS_DIRECTION_NEXT" value="5"/> + <member name="MX_FOCUS_DIRECTION_PREVIOUS" value="6"/> + </enum> + <enum name="MxFocusHint" type-name="MxFocusHint" get-type="mx_focus_hint_get_type"> + <member name="MX_FOCUS_HINT_FIRST" value="0"/> + <member name="MX_FOCUS_HINT_LAST" value="1"/> + <member name="MX_FOCUS_HINT_PRIOR" value="2"/> + </enum> + <enum name="MxFontWeight" type-name="MxFontWeight" get-type="mx_font_weight_get_type"> + <member name="MX_FONT_WEIGHT_NORMAL" value="0"/> + <member name="MX_FONT_WEIGHT_BOLD" value="1"/> + <member name="MX_FONT_WEIGHT_BOLDER" value="2"/> + <member name="MX_FONT_WEIGHT_LIGHTER" value="3"/> + </enum> + <enum name="MxLongPressAction" type-name="MxLongPressAction" get-type="mx_long_press_action_get_type"> + <member name="MX_LONG_PRESS_QUERY" value="0"/> + <member name="MX_LONG_PRESS_ACTION" value="1"/> + <member name="MX_LONG_PRESS_CANCEL" value="2"/> + </enum> + <enum name="MxOrientation" type-name="MxOrientation" get-type="mx_orientation_get_type"> + <member name="MX_ORIENTATION_HORIZONTAL" value="0"/> + <member name="MX_ORIENTATION_VERTICAL" value="1"/> + </enum> + <enum name="MxScrollPolicy" type-name="MxScrollPolicy" get-type="mx_scroll_policy_get_type"> + <member name="MX_SCROLL_POLICY_NONE" value="0"/> + <member name="MX_SCROLL_POLICY_HORIZONTAL" value="1"/> + <member name="MX_SCROLL_POLICY_VERTICAL" value="2"/> + <member name="MX_SCROLL_POLICY_BOTH" value="3"/> + </enum> + <enum name="MxStyleError" type-name="MxStyleError" get-type="mx_style_error_get_type"> + <member name="MX_STYLE_ERROR_INVALID_FILE" value="0"/> + </enum> + <flags name="MxApplicationFlags" type-name="MxApplicationFlags" get-type="mx_application_flags_get_type"> + <member name="MX_APPLICATION_SINGLE_INSTANCE" value="1"/> + <member name="MX_APPLICATION_KEEP_ALIVE" value="4"/> + </flags> + <flags name="MxStyleChangedFlags" type-name="MxStyleChangedFlags" get-type="mx_style_changed_flags_get_type"> + <member name="MX_STYLE_CHANGED_NONE" value="0"/> + <member name="MX_STYLE_CHANGED_FORCE" value="1"/> + </flags> + <object name="MxAction" parent="GInitiallyUnowned" type-name="MxAction" get-type="mx_action_get_type"> + <method name="get_active" symbol="mx_action_get_active"> + <return-type type="gboolean"/> + <parameters> + <parameter name="action" type="MxAction*"/> + </parameters> + </method> + <method name="get_display_name" symbol="mx_action_get_display_name"> + <return-type type="gchar*"/> + <parameters> + <parameter name="action" type="MxAction*"/> + </parameters> + </method> + <method name="get_icon" symbol="mx_action_get_icon"> + <return-type type="gchar*"/> + <parameters> + <parameter name="action" type="MxAction*"/> + </parameters> + </method> + <method name="get_name" symbol="mx_action_get_name"> + <return-type type="gchar*"/> + <parameters> + <parameter name="action" type="MxAction*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_action_new"> + <return-type type="MxAction*"/> + </constructor> + <constructor name="new_full" symbol="mx_action_new_full"> + <return-type type="MxAction*"/> + <parameters> + <parameter name="name" type="gchar*"/> + <parameter name="display_name" type="gchar*"/> + <parameter name="activated_cb" type="GCallback"/> + <parameter name="user_data" type="gpointer"/> + </parameters> + </constructor> + <method name="set_active" symbol="mx_action_set_active"> + <return-type type="void"/> + <parameters> + <parameter name="action" type="MxAction*"/> + <parameter name="active" type="gboolean"/> + </parameters> + </method> + <method name="set_display_name" symbol="mx_action_set_display_name"> + <return-type type="void"/> + <parameters> + <parameter name="action" type="MxAction*"/> + <parameter name="name" type="gchar*"/> + </parameters> + </method> + <method name="set_icon" symbol="mx_action_set_icon"> + <return-type type="void"/> + <parameters> + <parameter name="action" type="MxAction*"/> + <parameter name="name" type="gchar*"/> + </parameters> + </method> + <method name="set_name" symbol="mx_action_set_name"> + <return-type type="void"/> + <parameters> + <parameter name="action" type="MxAction*"/> + <parameter name="name" type="gchar*"/> + </parameters> + </method> + <property name="active" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="display-name" type="char*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="icon" type="char*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="name" type="char*" readable="1" writable="1" construct="0" construct-only="0"/> + <signal name="activated" when="LAST"> + <return-type type="void"/> + <parameters> + <parameter name="action" type="MxAction*"/> + </parameters> + </signal> + </object> + <object name="MxAdjustment" parent="GObject" type-name="MxAdjustment" get-type="mx_adjustment_get_type"> + <method name="get_elastic" symbol="mx_adjustment_get_elastic"> + <return-type type="gboolean"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + </parameters> + </method> + <method name="get_lower" symbol="mx_adjustment_get_lower"> + <return-type type="gdouble"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + </parameters> + </method> + <method name="get_page_increment" symbol="mx_adjustment_get_page_increment"> + <return-type type="gdouble"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + </parameters> + </method> + <method name="get_page_size" symbol="mx_adjustment_get_page_size"> + <return-type type="gdouble"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + </parameters> + </method> + <method name="get_step_increment" symbol="mx_adjustment_get_step_increment"> + <return-type type="gdouble"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + </parameters> + </method> + <method name="get_upper" symbol="mx_adjustment_get_upper"> + <return-type type="gdouble"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + </parameters> + </method> + <method name="get_value" symbol="mx_adjustment_get_value"> + <return-type type="gdouble"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + </parameters> + </method> + <method name="get_values" symbol="mx_adjustment_get_values"> + <return-type type="void"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + <parameter name="value" type="gdouble*"/> + <parameter name="lower" type="gdouble*"/> + <parameter name="upper" type="gdouble*"/> + <parameter name="step_increment" type="gdouble*"/> + <parameter name="page_increment" type="gdouble*"/> + <parameter name="page_size" type="gdouble*"/> + </parameters> + </method> + <method name="interpolate" symbol="mx_adjustment_interpolate"> + <return-type type="void"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + <parameter name="value" type="gdouble"/> + <parameter name="duration" type="guint"/> + <parameter name="mode" type="gulong"/> + </parameters> + </method> + <method name="interpolate_relative" symbol="mx_adjustment_interpolate_relative"> + <return-type type="void"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + <parameter name="offset" type="gdouble"/> + <parameter name="duration" type="guint"/> + <parameter name="mode" type="gulong"/> + </parameters> + </method> + <constructor name="new" symbol="mx_adjustment_new"> + <return-type type="MxAdjustment*"/> + </constructor> + <constructor name="new_with_values" symbol="mx_adjustment_new_with_values"> + <return-type type="MxAdjustment*"/> + <parameters> + <parameter name="value" type="gdouble"/> + <parameter name="lower" type="gdouble"/> + <parameter name="upper" type="gdouble"/> + <parameter name="step_increment" type="gdouble"/> + <parameter name="page_increment" type="gdouble"/> + <parameter name="page_size" type="gdouble"/> + </parameters> + </constructor> + <method name="set_elastic" symbol="mx_adjustment_set_elastic"> + <return-type type="void"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + <parameter name="elastic" type="gboolean"/> + </parameters> + </method> + <method name="set_lower" symbol="mx_adjustment_set_lower"> + <return-type type="void"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + <parameter name="lower" type="gdouble"/> + </parameters> + </method> + <method name="set_page_increment" symbol="mx_adjustment_set_page_increment"> + <return-type type="void"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + <parameter name="increment" type="gdouble"/> + </parameters> + </method> + <method name="set_page_size" symbol="mx_adjustment_set_page_size"> + <return-type type="void"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + <parameter name="page_size" type="gdouble"/> + </parameters> + </method> + <method name="set_step_increment" symbol="mx_adjustment_set_step_increment"> + <return-type type="void"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + <parameter name="increment" type="gdouble"/> + </parameters> + </method> + <method name="set_upper" symbol="mx_adjustment_set_upper"> + <return-type type="void"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + <parameter name="upper" type="gdouble"/> + </parameters> + </method> + <method name="set_value" symbol="mx_adjustment_set_value"> + <return-type type="void"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + <parameter name="value" type="gdouble"/> + </parameters> + </method> + <method name="set_values" symbol="mx_adjustment_set_values"> + <return-type type="void"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + <parameter name="value" type="gdouble"/> + <parameter name="lower" type="gdouble"/> + <parameter name="upper" type="gdouble"/> + <parameter name="step_increment" type="gdouble"/> + <parameter name="page_increment" type="gdouble"/> + <parameter name="page_size" type="gdouble"/> + </parameters> + </method> + <property name="elastic" type="gboolean" readable="1" writable="1" construct="1" construct-only="0"/> + <property name="lower" type="gdouble" readable="1" writable="1" construct="1" construct-only="0"/> + <property name="page-increment" type="gdouble" readable="1" writable="1" construct="1" construct-only="0"/> + <property name="page-size" type="gdouble" readable="1" writable="1" construct="1" construct-only="0"/> + <property name="step-increment" type="gdouble" readable="1" writable="1" construct="1" construct-only="0"/> + <property name="upper" type="gdouble" readable="1" writable="1" construct="1" construct-only="0"/> + <property name="value" type="gdouble" readable="1" writable="1" construct="1" construct-only="0"/> + <signal name="changed" when="LAST"> + <return-type type="void"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + </parameters> + </signal> + </object> + <object name="MxApplication" parent="GObject" type-name="MxApplication" get-type="mx_application_get_type"> + <method name="add_action" symbol="mx_application_add_action"> + <return-type type="void"/> + <parameters> + <parameter name="application" type="MxApplication*"/> + <parameter name="action" type="MxAction*"/> + </parameters> + </method> + <method name="add_window" symbol="mx_application_add_window"> + <return-type type="void"/> + <parameters> + <parameter name="application" type="MxApplication*"/> + <parameter name="window" type="MxWindow*"/> + </parameters> + </method> + <method name="create_window" symbol="mx_application_create_window"> + <return-type type="MxWindow*"/> + <parameters> + <parameter name="application" type="MxApplication*"/> + </parameters> + </method> + <method name="get_actions" symbol="mx_application_get_actions"> + <return-type type="GList*"/> + <parameters> + <parameter name="application" type="MxApplication*"/> + </parameters> + </method> + <method name="get_flags" symbol="mx_application_get_flags"> + <return-type type="MxApplicationFlags"/> + <parameters> + <parameter name="application" type="MxApplication*"/> + </parameters> + </method> + <method name="get_windows" symbol="mx_application_get_windows"> + <return-type type="GList*"/> + <parameters> + <parameter name="application" type="MxApplication*"/> + </parameters> + </method> + <method name="invoke_action" symbol="mx_application_invoke_action"> + <return-type type="void"/> + <parameters> + <parameter name="application" type="MxApplication*"/> + <parameter name="name" type="gchar*"/> + </parameters> + </method> + <method name="is_running" symbol="mx_application_is_running"> + <return-type type="gboolean"/> + <parameters> + <parameter name="application" type="MxApplication*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_application_new"> + <return-type type="MxApplication*"/> + <parameters> + <parameter name="argc" type="gint*"/> + <parameter name="argv" type="gchar***"/> + <parameter name="name" type="gchar*"/> + <parameter name="flags" type="MxApplicationFlags"/> + </parameters> + </constructor> + <method name="quit" symbol="mx_application_quit"> + <return-type type="void"/> + <parameters> + <parameter name="application" type="MxApplication*"/> + </parameters> + </method> + <method name="remove_action" symbol="mx_application_remove_action"> + <return-type type="void"/> + <parameters> + <parameter name="application" type="MxApplication*"/> + <parameter name="name" type="gchar*"/> + </parameters> + </method> + <method name="remove_window" symbol="mx_application_remove_window"> + <return-type type="void"/> + <parameters> + <parameter name="application" type="MxApplication*"/> + <parameter name="window" type="MxWindow*"/> + </parameters> + </method> + <method name="run" symbol="mx_application_run"> + <return-type type="void"/> + <parameters> + <parameter name="application" type="MxApplication*"/> + </parameters> + </method> + <property name="application-name" type="char*" readable="1" writable="1" construct="0" construct-only="1"/> + <property name="flags" type="guint" readable="1" writable="1" construct="0" construct-only="1"/> + <signal name="actions-changed" when="LAST"> + <return-type type="void"/> + <parameters> + <parameter name="app" type="MxApplication*"/> + </parameters> + </signal> + <vfunc name="create_window"> + <return-type type="MxWindow*"/> + <parameters> + <parameter name="app" type="MxApplication*"/> + </parameters> + </vfunc> + <vfunc name="raise"> + <return-type type="void"/> + <parameters> + <parameter name="app" type="MxApplication*"/> + </parameters> + </vfunc> + </object> + <object name="MxBin" parent="MxWidget" type-name="MxBin" get-type="mx_bin_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + <interface name="ClutterContainer"/> + <interface name="MxFocusable"/> + </implements> + <method name="allocate_child" symbol="mx_bin_allocate_child"> + <return-type type="void"/> + <parameters> + <parameter name="bin" type="MxBin*"/> + <parameter name="box" type="ClutterActorBox*"/> + <parameter name="flags" type="ClutterAllocationFlags"/> + </parameters> + </method> + <method name="get_alignment" symbol="mx_bin_get_alignment"> + <return-type type="void"/> + <parameters> + <parameter name="bin" type="MxBin*"/> + <parameter name="x_align" type="MxAlign*"/> + <parameter name="y_align" type="MxAlign*"/> + </parameters> + </method> + <method name="get_child" symbol="mx_bin_get_child"> + <return-type type="ClutterActor*"/> + <parameters> + <parameter name="bin" type="MxBin*"/> + </parameters> + </method> + <method name="get_fill" symbol="mx_bin_get_fill"> + <return-type type="void"/> + <parameters> + <parameter name="bin" type="MxBin*"/> + <parameter name="x_fill" type="gboolean*"/> + <parameter name="y_fill" type="gboolean*"/> + </parameters> + </method> + <method name="set_alignment" symbol="mx_bin_set_alignment"> + <return-type type="void"/> + <parameters> + <parameter name="bin" type="MxBin*"/> + <parameter name="x_align" type="MxAlign"/> + <parameter name="y_align" type="MxAlign"/> + </parameters> + </method> + <method name="set_child" symbol="mx_bin_set_child"> + <return-type type="void"/> + <parameters> + <parameter name="bin" type="MxBin*"/> + <parameter name="child" type="ClutterActor*"/> + </parameters> + </method> + <method name="set_fill" symbol="mx_bin_set_fill"> + <return-type type="void"/> + <parameters> + <parameter name="bin" type="MxBin*"/> + <parameter name="x_fill" type="gboolean"/> + <parameter name="y_fill" type="gboolean"/> + </parameters> + </method> + <property name="child" type="ClutterActor*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="x-align" type="MxAlign" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="x-fill" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="y-align" type="MxAlign" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="y-fill" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxBoxLayout" parent="MxWidget" type-name="MxBoxLayout" get-type="mx_box_layout_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + <interface name="ClutterContainer"/> + <interface name="MxScrollable"/> + <interface name="MxFocusable"/> + </implements> + <method name="add_actor" symbol="mx_box_layout_add_actor"> + <return-type type="void"/> + <parameters> + <parameter name="box" type="MxBoxLayout*"/> + <parameter name="actor" type="ClutterActor*"/> + <parameter name="position" type="gint"/> + </parameters> + </method> + <method name="add_actor_with_properties" symbol="mx_box_layout_add_actor_with_properties"> + <return-type type="void"/> + <parameters> + <parameter name="box" type="MxBoxLayout*"/> + <parameter name="actor" type="ClutterActor*"/> + <parameter name="position" type="gint"/> + <parameter name="first_property" type="char*"/> + </parameters> + </method> + <method name="get_enable_animations" symbol="mx_box_layout_get_enable_animations"> + <return-type type="gboolean"/> + <parameters> + <parameter name="box" type="MxBoxLayout*"/> + </parameters> + </method> + <method name="get_orientation" symbol="mx_box_layout_get_orientation"> + <return-type type="MxOrientation"/> + <parameters> + <parameter name="box" type="MxBoxLayout*"/> + </parameters> + </method> + <method name="get_spacing" symbol="mx_box_layout_get_spacing"> + <return-type type="guint"/> + <parameters> + <parameter name="box" type="MxBoxLayout*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_box_layout_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="set_enable_animations" symbol="mx_box_layout_set_enable_animations"> + <return-type type="void"/> + <parameters> + <parameter name="box" type="MxBoxLayout*"/> + <parameter name="enable_animations" type="gboolean"/> + </parameters> + </method> + <method name="set_orientation" symbol="mx_box_layout_set_orientation"> + <return-type type="void"/> + <parameters> + <parameter name="box" type="MxBoxLayout*"/> + <parameter name="orientation" type="MxOrientation"/> + </parameters> + </method> + <method name="set_spacing" symbol="mx_box_layout_set_spacing"> + <return-type type="void"/> + <parameters> + <parameter name="box" type="MxBoxLayout*"/> + <parameter name="spacing" type="guint"/> + </parameters> + </method> + <property name="enable-animations" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="orientation" type="MxOrientation" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="spacing" type="guint" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxBoxLayoutChild" parent="ClutterChildMeta" type-name="MxBoxLayoutChild" get-type="mx_box_layout_child_get_type"> + <method name="get_expand" symbol="mx_box_layout_child_get_expand"> + <return-type type="gboolean"/> + <parameters> + <parameter name="box_layout" type="MxBoxLayout*"/> + <parameter name="child" type="ClutterActor*"/> + </parameters> + </method> + <method name="get_x_align" symbol="mx_box_layout_child_get_x_align"> + <return-type type="MxAlign"/> + <parameters> + <parameter name="box_layout" type="MxBoxLayout*"/> + <parameter name="child" type="ClutterActor*"/> + </parameters> + </method> + <method name="get_x_fill" symbol="mx_box_layout_child_get_x_fill"> + <return-type type="gboolean"/> + <parameters> + <parameter name="box_layout" type="MxBoxLayout*"/> + <parameter name="child" type="ClutterActor*"/> + </parameters> + </method> + <method name="get_y_align" symbol="mx_box_layout_child_get_y_align"> + <return-type type="MxAlign"/> + <parameters> + <parameter name="box_layout" type="MxBoxLayout*"/> + <parameter name="child" type="ClutterActor*"/> + </parameters> + </method> + <method name="get_y_fill" symbol="mx_box_layout_child_get_y_fill"> + <return-type type="gboolean"/> + <parameters> + <parameter name="box_layout" type="MxBoxLayout*"/> + <parameter name="child" type="ClutterActor*"/> + </parameters> + </method> + <method name="set_expand" symbol="mx_box_layout_child_set_expand"> + <return-type type="void"/> + <parameters> + <parameter name="box_layout" type="MxBoxLayout*"/> + <parameter name="child" type="ClutterActor*"/> + <parameter name="expand" type="gboolean"/> + </parameters> + </method> + <method name="set_x_align" symbol="mx_box_layout_child_set_x_align"> + <return-type type="void"/> + <parameters> + <parameter name="box_layout" type="MxBoxLayout*"/> + <parameter name="child" type="ClutterActor*"/> + <parameter name="x_align" type="MxAlign"/> + </parameters> + </method> + <method name="set_x_fill" symbol="mx_box_layout_child_set_x_fill"> + <return-type type="void"/> + <parameters> + <parameter name="box_layout" type="MxBoxLayout*"/> + <parameter name="child" type="ClutterActor*"/> + <parameter name="x_fill" type="gboolean"/> + </parameters> + </method> + <method name="set_y_align" symbol="mx_box_layout_child_set_y_align"> + <return-type type="void"/> + <parameters> + <parameter name="box_layout" type="MxBoxLayout*"/> + <parameter name="child" type="ClutterActor*"/> + <parameter name="y_align" type="MxAlign"/> + </parameters> + </method> + <method name="set_y_fill" symbol="mx_box_layout_child_set_y_fill"> + <return-type type="void"/> + <parameters> + <parameter name="box_layout" type="MxBoxLayout*"/> + <parameter name="child" type="ClutterActor*"/> + <parameter name="y_fill" type="gboolean"/> + </parameters> + </method> + <property name="expand" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="x-align" type="MxAlign" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="x-fill" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="y-align" type="MxAlign" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="y-fill" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <field name="expand" type="gboolean"/> + <field name="x_fill" type="gboolean"/> + <field name="y_fill" type="gboolean"/> + <field name="x_align" type="MxAlign"/> + <field name="y_align" type="MxAlign"/> + </object> + <object name="MxButton" parent="MxBin" type-name="MxButton" get-type="mx_button_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + <interface name="ClutterContainer"/> + <interface name="MxFocusable"/> + </implements> + <method name="get_is_toggle" symbol="mx_button_get_is_toggle"> + <return-type type="gboolean"/> + <parameters> + <parameter name="button" type="MxButton*"/> + </parameters> + </method> + <method name="get_label" symbol="mx_button_get_label"> + <return-type type="gchar*"/> + <parameters> + <parameter name="button" type="MxButton*"/> + </parameters> + </method> + <method name="get_toggled" symbol="mx_button_get_toggled"> + <return-type type="gboolean"/> + <parameters> + <parameter name="button" type="MxButton*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_button_new"> + <return-type type="ClutterActor*"/> + </constructor> + <constructor name="new_with_label" symbol="mx_button_new_with_label"> + <return-type type="ClutterActor*"/> + <parameters> + <parameter name="text" type="gchar*"/> + </parameters> + </constructor> + <method name="set_is_toggle" symbol="mx_button_set_is_toggle"> + <return-type type="void"/> + <parameters> + <parameter name="button" type="MxButton*"/> + <parameter name="toggle" type="gboolean"/> + </parameters> + </method> + <method name="set_label" symbol="mx_button_set_label"> + <return-type type="void"/> + <parameters> + <parameter name="button" type="MxButton*"/> + <parameter name="text" type="gchar*"/> + </parameters> + </method> + <method name="set_toggled" symbol="mx_button_set_toggled"> + <return-type type="void"/> + <parameters> + <parameter name="button" type="MxButton*"/> + <parameter name="toggled" type="gboolean"/> + </parameters> + </method> + <property name="is-toggle" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="label" type="char*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="toggled" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <signal name="clicked" when="LAST"> + <return-type type="void"/> + <parameters> + <parameter name="button" type="MxButton*"/> + </parameters> + </signal> + </object> + <object name="MxButtonGroup" parent="GInitiallyUnowned" type-name="MxButtonGroup" get-type="mx_button_group_get_type"> + <method name="add" symbol="mx_button_group_add"> + <return-type type="void"/> + <parameters> + <parameter name="group" type="MxButtonGroup*"/> + <parameter name="button" type="MxButton*"/> + </parameters> + </method> + <method name="foreach" symbol="mx_button_group_foreach"> + <return-type type="void"/> + <parameters> + <parameter name="group" type="MxButtonGroup*"/> + <parameter name="callback" type="ClutterCallback"/> + <parameter name="userdata" type="gpointer"/> + </parameters> + </method> + <method name="get_active_button" symbol="mx_button_group_get_active_button"> + <return-type type="MxButton*"/> + <parameters> + <parameter name="group" type="MxButtonGroup*"/> + </parameters> + </method> + <method name="get_allow_no_active" symbol="mx_button_group_get_allow_no_active"> + <return-type type="gboolean"/> + <parameters> + <parameter name="group" type="MxButtonGroup*"/> + </parameters> + </method> + <method name="get_buttons" symbol="mx_button_group_get_buttons"> + <return-type type="GSList*"/> + <parameters> + <parameter name="group" type="MxButtonGroup*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_button_group_new"> + <return-type type="MxButtonGroup*"/> + </constructor> + <method name="remove" symbol="mx_button_group_remove"> + <return-type type="void"/> + <parameters> + <parameter name="group" type="MxButtonGroup*"/> + <parameter name="button" type="MxButton*"/> + </parameters> + </method> + <method name="set_active_button" symbol="mx_button_group_set_active_button"> + <return-type type="void"/> + <parameters> + <parameter name="group" type="MxButtonGroup*"/> + <parameter name="button" type="MxButton*"/> + </parameters> + </method> + <method name="set_allow_no_active" symbol="mx_button_group_set_allow_no_active"> + <return-type type="void"/> + <parameters> + <parameter name="group" type="MxButtonGroup*"/> + <parameter name="allow_no_active" type="gboolean"/> + </parameters> + </method> + <property name="active-button" type="MxButton*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="allow-no-active" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxClipboard" parent="GObject" type-name="MxClipboard" get-type="mx_clipboard_get_type"> + <method name="get_default" symbol="mx_clipboard_get_default"> + <return-type type="MxClipboard*"/> + </method> + <method name="get_text" symbol="mx_clipboard_get_text"> + <return-type type="void"/> + <parameters> + <parameter name="clipboard" type="MxClipboard*"/> + <parameter name="callback" type="MxClipboardCallbackFunc"/> + <parameter name="user_data" type="gpointer"/> + </parameters> + </method> + <method name="set_text" symbol="mx_clipboard_set_text"> + <return-type type="void"/> + <parameters> + <parameter name="clipboard" type="MxClipboard*"/> + <parameter name="text" type="gchar*"/> + </parameters> + </method> + </object> + <object name="MxComboBox" parent="MxWidget" type-name="MxComboBox" get-type="mx_combo_box_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + <interface name="MxFocusable"/> + </implements> + <method name="append_text" symbol="mx_combo_box_append_text"> + <return-type type="void"/> + <parameters> + <parameter name="box" type="MxComboBox*"/> + <parameter name="text" type="gchar*"/> + </parameters> + </method> + <method name="get_active_icon_name" symbol="mx_combo_box_get_active_icon_name"> + <return-type type="gchar*"/> + <parameters> + <parameter name="box" type="MxComboBox*"/> + </parameters> + </method> + <method name="get_active_text" symbol="mx_combo_box_get_active_text"> + <return-type type="gchar*"/> + <parameters> + <parameter name="box" type="MxComboBox*"/> + </parameters> + </method> + <method name="get_index" symbol="mx_combo_box_get_index"> + <return-type type="gint"/> + <parameters> + <parameter name="box" type="MxComboBox*"/> + </parameters> + </method> + <method name="insert_text" symbol="mx_combo_box_insert_text"> + <return-type type="void"/> + <parameters> + <parameter name="box" type="MxComboBox*"/> + <parameter name="position" type="gint"/> + <parameter name="text" type="gchar*"/> + </parameters> + </method> + <method name="insert_text_with_icon" symbol="mx_combo_box_insert_text_with_icon"> + <return-type type="void"/> + <parameters> + <parameter name="box" type="MxComboBox*"/> + <parameter name="position" type="gint"/> + <parameter name="text" type="gchar*"/> + <parameter name="icon" type="gchar*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_combo_box_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="prepend_text" symbol="mx_combo_box_prepend_text"> + <return-type type="void"/> + <parameters> + <parameter name="box" type="MxComboBox*"/> + <parameter name="text" type="gchar*"/> + </parameters> + </method> + <method name="remove_text" symbol="mx_combo_box_remove_text"> + <return-type type="void"/> + <parameters> + <parameter name="box" type="MxComboBox*"/> + <parameter name="position" type="gint"/> + </parameters> + </method> + <method name="set_active_icon_name" symbol="mx_combo_box_set_active_icon_name"> + <return-type type="void"/> + <parameters> + <parameter name="box" type="MxComboBox*"/> + <parameter name="icon_name" type="gchar*"/> + </parameters> + </method> + <method name="set_active_text" symbol="mx_combo_box_set_active_text"> + <return-type type="void"/> + <parameters> + <parameter name="box" type="MxComboBox*"/> + <parameter name="text" type="gchar*"/> + </parameters> + </method> + <method name="set_index" symbol="mx_combo_box_set_index"> + <return-type type="void"/> + <parameters> + <parameter name="box" type="MxComboBox*"/> + <parameter name="index" type="gint"/> + </parameters> + </method> + <property name="active-icon-name" type="char*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="active-text" type="char*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="index" type="gint" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxDeformBowTie" parent="MxDeformTexture" type-name="MxDeformBowTie" get-type="mx_deform_bow_tie_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + </implements> + <method name="get_flip_back" symbol="mx_deform_bow_tie_get_flip_back"> + <return-type type="gboolean"/> + <parameters> + <parameter name="bow_tie" type="MxDeformBowTie*"/> + </parameters> + </method> + <method name="get_period" symbol="mx_deform_bow_tie_get_period"> + <return-type type="gdouble"/> + <parameters> + <parameter name="bow_tie" type="MxDeformBowTie*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_deform_bow_tie_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="set_flip_back" symbol="mx_deform_bow_tie_set_flip_back"> + <return-type type="void"/> + <parameters> + <parameter name="bow_tie" type="MxDeformBowTie*"/> + <parameter name="flip_back" type="gboolean"/> + </parameters> + </method> + <method name="set_period" symbol="mx_deform_bow_tie_set_period"> + <return-type type="void"/> + <parameters> + <parameter name="bow_tie" type="MxDeformBowTie*"/> + <parameter name="period" type="gdouble"/> + </parameters> + </method> + <property name="flip-back" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="period" type="gdouble" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxDeformPageTurn" parent="MxDeformTexture" type-name="MxDeformPageTurn" get-type="mx_deform_page_turn_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + </implements> + <method name="get_angle" symbol="mx_deform_page_turn_get_angle"> + <return-type type="gdouble"/> + <parameters> + <parameter name="page_turn" type="MxDeformPageTurn*"/> + </parameters> + </method> + <method name="get_period" symbol="mx_deform_page_turn_get_period"> + <return-type type="gdouble"/> + <parameters> + <parameter name="page_turn" type="MxDeformPageTurn*"/> + </parameters> + </method> + <method name="get_radius" symbol="mx_deform_page_turn_get_radius"> + <return-type type="gdouble"/> + <parameters> + <parameter name="page_turn" type="MxDeformPageTurn*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_deform_page_turn_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="set_angle" symbol="mx_deform_page_turn_set_angle"> + <return-type type="void"/> + <parameters> + <parameter name="page_turn" type="MxDeformPageTurn*"/> + <parameter name="angle" type="gdouble"/> + </parameters> + </method> + <method name="set_period" symbol="mx_deform_page_turn_set_period"> + <return-type type="void"/> + <parameters> + <parameter name="page_turn" type="MxDeformPageTurn*"/> + <parameter name="period" type="gdouble"/> + </parameters> + </method> + <method name="set_radius" symbol="mx_deform_page_turn_set_radius"> + <return-type type="void"/> + <parameters> + <parameter name="page_turn" type="MxDeformPageTurn*"/> + <parameter name="radius" type="gdouble"/> + </parameters> + </method> + <property name="angle" type="gdouble" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="period" type="gdouble" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="radius" type="gdouble" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxDeformTexture" parent="MxWidget" type-name="MxDeformTexture" get-type="mx_deform_texture_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + </implements> + <method name="get_resolution" symbol="mx_deform_texture_get_resolution"> + <return-type type="void"/> + <parameters> + <parameter name="texture" type="MxDeformTexture*"/> + <parameter name="tiles_x" type="gint*"/> + <parameter name="tiles_y" type="gint*"/> + </parameters> + </method> + <method name="get_textures" symbol="mx_deform_texture_get_textures"> + <return-type type="void"/> + <parameters> + <parameter name="texture" type="MxDeformTexture*"/> + <parameter name="front" type="ClutterTexture**"/> + <parameter name="back" type="ClutterTexture**"/> + </parameters> + </method> + <method name="invalidate" symbol="mx_deform_texture_invalidate"> + <return-type type="void"/> + <parameters> + <parameter name="texture" type="MxDeformTexture*"/> + </parameters> + </method> + <method name="set_resolution" symbol="mx_deform_texture_set_resolution"> + <return-type type="void"/> + <parameters> + <parameter name="texture" type="MxDeformTexture*"/> + <parameter name="tiles_x" type="gint"/> + <parameter name="tiles_y" type="gint"/> + </parameters> + </method> + <method name="set_textures" symbol="mx_deform_texture_set_textures"> + <return-type type="void"/> + <parameters> + <parameter name="texture" type="MxDeformTexture*"/> + <parameter name="front" type="ClutterTexture*"/> + <parameter name="back" type="ClutterTexture*"/> + </parameters> + </method> + <property name="back" type="ClutterTexture*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="front" type="ClutterTexture*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="tiles-x" type="gint" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="tiles-y" type="gint" readable="1" writable="1" construct="0" construct-only="0"/> + <vfunc name="deform"> + <return-type type="void"/> + <parameters> + <parameter name="texture" type="MxDeformTexture*"/> + <parameter name="vertex" type="CoglTextureVertex*"/> + <parameter name="width" type="gfloat"/> + <parameter name="height" type="gfloat"/> + </parameters> + </vfunc> + </object> + <object name="MxDeformWaves" parent="MxDeformTexture" type-name="MxDeformWaves" get-type="mx_deform_waves_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + </implements> + <method name="get_amplitude" symbol="mx_deform_waves_get_amplitude"> + <return-type type="gdouble"/> + <parameters> + <parameter name="waves" type="MxDeformWaves*"/> + </parameters> + </method> + <method name="get_angle" symbol="mx_deform_waves_get_angle"> + <return-type type="gdouble"/> + <parameters> + <parameter name="waves" type="MxDeformWaves*"/> + </parameters> + </method> + <method name="get_period" symbol="mx_deform_waves_get_period"> + <return-type type="gdouble"/> + <parameters> + <parameter name="waves" type="MxDeformWaves*"/> + </parameters> + </method> + <method name="get_radius" symbol="mx_deform_waves_get_radius"> + <return-type type="gdouble"/> + <parameters> + <parameter name="waves" type="MxDeformWaves*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_deform_waves_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="set_amplitude" symbol="mx_deform_waves_set_amplitude"> + <return-type type="void"/> + <parameters> + <parameter name="waves" type="MxDeformWaves*"/> + <parameter name="amplitude" type="gdouble"/> + </parameters> + </method> + <method name="set_angle" symbol="mx_deform_waves_set_angle"> + <return-type type="void"/> + <parameters> + <parameter name="waves" type="MxDeformWaves*"/> + <parameter name="angle" type="gdouble"/> + </parameters> + </method> + <method name="set_period" symbol="mx_deform_waves_set_period"> + <return-type type="void"/> + <parameters> + <parameter name="waves" type="MxDeformWaves*"/> + <parameter name="period" type="gdouble"/> + </parameters> + </method> + <method name="set_radius" symbol="mx_deform_waves_set_radius"> + <return-type type="void"/> + <parameters> + <parameter name="waves" type="MxDeformWaves*"/> + <parameter name="radius" type="gdouble"/> + </parameters> + </method> + <property name="amplitude" type="gdouble" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="angle" type="gdouble" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="period" type="gdouble" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="radius" type="gdouble" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxEntry" parent="MxWidget" type-name="MxEntry" get-type="mx_entry_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + <interface name="MxFocusable"/> + </implements> + <method name="get_clutter_text" symbol="mx_entry_get_clutter_text"> + <return-type type="ClutterActor*"/> + <parameters> + <parameter name="entry" type="MxEntry*"/> + </parameters> + </method> + <method name="get_hint_text" symbol="mx_entry_get_hint_text"> + <return-type type="gchar*"/> + <parameters> + <parameter name="entry" type="MxEntry*"/> + </parameters> + </method> + <method name="get_password_char" symbol="mx_entry_get_password_char"> + <return-type type="gunichar"/> + <parameters> + <parameter name="entry" type="MxEntry*"/> + </parameters> + </method> + <method name="get_text" symbol="mx_entry_get_text"> + <return-type type="gchar*"/> + <parameters> + <parameter name="entry" type="MxEntry*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_entry_new"> + <return-type type="ClutterActor*"/> + </constructor> + <constructor name="new_with_text" symbol="mx_entry_new_with_text"> + <return-type type="ClutterActor*"/> + <parameters> + <parameter name="text" type="gchar*"/> + </parameters> + </constructor> + <method name="set_hint_text" symbol="mx_entry_set_hint_text"> + <return-type type="void"/> + <parameters> + <parameter name="entry" type="MxEntry*"/> + <parameter name="text" type="gchar*"/> + </parameters> + </method> + <method name="set_password_char" symbol="mx_entry_set_password_char"> + <return-type type="void"/> + <parameters> + <parameter name="entry" type="MxEntry*"/> + <parameter name="password_char" type="gunichar"/> + </parameters> + </method> + <method name="set_primary_icon_from_file" symbol="mx_entry_set_primary_icon_from_file"> + <return-type type="void"/> + <parameters> + <parameter name="entry" type="MxEntry*"/> + <parameter name="filename" type="gchar*"/> + </parameters> + </method> + <method name="set_secondary_icon_from_file" symbol="mx_entry_set_secondary_icon_from_file"> + <return-type type="void"/> + <parameters> + <parameter name="entry" type="MxEntry*"/> + <parameter name="filename" type="gchar*"/> + </parameters> + </method> + <method name="set_text" symbol="mx_entry_set_text"> + <return-type type="void"/> + <parameters> + <parameter name="entry" type="MxEntry*"/> + <parameter name="text" type="gchar*"/> + </parameters> + </method> + <property name="clutter-text" type="ClutterText*" readable="1" writable="0" construct="0" construct-only="0"/> + <property name="hint-text" type="char*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="password-char" type="guint" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="text" type="char*" readable="1" writable="1" construct="0" construct-only="0"/> + <signal name="primary-icon-clicked" when="LAST"> + <return-type type="void"/> + <parameters> + <parameter name="entry" type="MxEntry*"/> + </parameters> + </signal> + <signal name="secondary-icon-clicked" when="LAST"> + <return-type type="void"/> + <parameters> + <parameter name="entry" type="MxEntry*"/> + </parameters> + </signal> + </object> + <object name="MxExpander" parent="MxBin" type-name="MxExpander" get-type="mx_expander_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + <interface name="ClutterContainer"/> + <interface name="MxFocusable"/> + </implements> + <method name="get_expanded" symbol="mx_expander_get_expanded"> + <return-type type="gboolean"/> + <parameters> + <parameter name="expander" type="MxExpander*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_expander_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="set_expanded" symbol="mx_expander_set_expanded"> + <return-type type="void"/> + <parameters> + <parameter name="expander" type="MxExpander*"/> + <parameter name="expanded" type="gboolean"/> + </parameters> + </method> + <method name="set_label" symbol="mx_expander_set_label"> + <return-type type="void"/> + <parameters> + <parameter name="expander" type="MxExpander*"/> + <parameter name="label" type="gchar*"/> + </parameters> + </method> + <property name="expanded" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="label" type="char*" readable="1" writable="1" construct="0" construct-only="0"/> + <signal name="expand-complete" when="LAST"> + <return-type type="void"/> + <parameters> + <parameter name="expander" type="MxExpander*"/> + </parameters> + </signal> + </object> + <object name="MxFloatingWidget" parent="MxWidget" type-name="MxFloatingWidget" get-type="mx_floating_widget_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + </implements> + <vfunc name="floating_paint"> + <return-type type="void"/> + <parameters> + <parameter name="actor" type="ClutterActor*"/> + </parameters> + </vfunc> + <vfunc name="floating_pick"> + <return-type type="void"/> + <parameters> + <parameter name="actor" type="ClutterActor*"/> + <parameter name="color" type="ClutterColor*"/> + </parameters> + </vfunc> + </object> + <object name="MxFocusManager" parent="GObject" type-name="MxFocusManager" get-type="mx_focus_manager_get_type"> + <method name="get_focused" symbol="mx_focus_manager_get_focused"> + <return-type type="MxFocusable*"/> + <parameters> + <parameter name="manager" type="MxFocusManager*"/> + </parameters> + </method> + <method name="get_for_stage" symbol="mx_focus_manager_get_for_stage"> + <return-type type="MxFocusManager*"/> + <parameters> + <parameter name="stage" type="ClutterStage*"/> + </parameters> + </method> + <method name="get_stage" symbol="mx_focus_manager_get_stage"> + <return-type type="ClutterStage*"/> + <parameters> + <parameter name="manager" type="MxFocusManager*"/> + </parameters> + </method> + <method name="move_focus" symbol="mx_focus_manager_move_focus"> + <return-type type="void"/> + <parameters> + <parameter name="manager" type="MxFocusManager*"/> + <parameter name="direction" type="MxFocusDirection"/> + </parameters> + </method> + <method name="push_focus" symbol="mx_focus_manager_push_focus"> + <return-type type="void"/> + <parameters> + <parameter name="manager" type="MxFocusManager*"/> + <parameter name="focusable" type="MxFocusable*"/> + </parameters> + </method> + <property name="focused" type="ClutterActor*" readable="1" writable="0" construct="0" construct-only="0"/> + <property name="stage" type="ClutterStage*" readable="1" writable="0" construct="0" construct-only="0"/> + </object> + <object name="MxFrame" parent="MxBin" type-name="MxFrame" get-type="mx_frame_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + <interface name="ClutterContainer"/> + <interface name="MxFocusable"/> + </implements> + <constructor name="new" symbol="mx_frame_new"> + <return-type type="ClutterActor*"/> + </constructor> + </object> + <object name="MxGrid" parent="MxWidget" type-name="MxGrid" get-type="mx_grid_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + <interface name="ClutterContainer"/> + <interface name="MxScrollable"/> + <interface name="MxFocusable"/> + </implements> + <method name="get_child_x_align" symbol="mx_grid_get_child_x_align"> + <return-type type="MxAlign"/> + <parameters> + <parameter name="self" type="MxGrid*"/> + </parameters> + </method> + <method name="get_child_y_align" symbol="mx_grid_get_child_y_align"> + <return-type type="MxAlign"/> + <parameters> + <parameter name="self" type="MxGrid*"/> + </parameters> + </method> + <method name="get_column_spacing" symbol="mx_grid_get_column_spacing"> + <return-type type="gfloat"/> + <parameters> + <parameter name="self" type="MxGrid*"/> + </parameters> + </method> + <method name="get_homogenous_columns" symbol="mx_grid_get_homogenous_columns"> + <return-type type="gboolean"/> + <parameters> + <parameter name="self" type="MxGrid*"/> + </parameters> + </method> + <method name="get_homogenous_rows" symbol="mx_grid_get_homogenous_rows"> + <return-type type="gboolean"/> + <parameters> + <parameter name="self" type="MxGrid*"/> + </parameters> + </method> + <method name="get_line_alignment" symbol="mx_grid_get_line_alignment"> + <return-type type="gboolean"/> + <parameters> + <parameter name="self" type="MxGrid*"/> + </parameters> + </method> + <method name="get_max_stride" symbol="mx_grid_get_max_stride"> + <return-type type="gint"/> + <parameters> + <parameter name="self" type="MxGrid*"/> + </parameters> + </method> + <method name="get_orientation" symbol="mx_grid_get_orientation"> + <return-type type="MxOrientation"/> + <parameters> + <parameter name="grid" type="MxGrid*"/> + </parameters> + </method> + <method name="get_row_spacing" symbol="mx_grid_get_row_spacing"> + <return-type type="gfloat"/> + <parameters> + <parameter name="self" type="MxGrid*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_grid_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="set_child_x_align" symbol="mx_grid_set_child_x_align"> + <return-type type="void"/> + <parameters> + <parameter name="self" type="MxGrid*"/> + <parameter name="value" type="MxAlign"/> + </parameters> + </method> + <method name="set_child_y_align" symbol="mx_grid_set_child_y_align"> + <return-type type="void"/> + <parameters> + <parameter name="self" type="MxGrid*"/> + <parameter name="value" type="MxAlign"/> + </parameters> + </method> + <method name="set_column_spacing" symbol="mx_grid_set_column_spacing"> + <return-type type="void"/> + <parameters> + <parameter name="self" type="MxGrid*"/> + <parameter name="value" type="gfloat"/> + </parameters> + </method> + <method name="set_homogenous_columns" symbol="mx_grid_set_homogenous_columns"> + <return-type type="void"/> + <parameters> + <parameter name="self" type="MxGrid*"/> + <parameter name="value" type="gboolean"/> + </parameters> + </method> + <method name="set_homogenous_rows" symbol="mx_grid_set_homogenous_rows"> + <return-type type="void"/> + <parameters> + <parameter name="self" type="MxGrid*"/> + <parameter name="value" type="gboolean"/> + </parameters> + </method> + <method name="set_line_alignment" symbol="mx_grid_set_line_alignment"> + <return-type type="void"/> + <parameters> + <parameter name="self" type="MxGrid*"/> + <parameter name="value" type="MxAlign"/> + </parameters> + </method> + <method name="set_max_stride" symbol="mx_grid_set_max_stride"> + <return-type type="void"/> + <parameters> + <parameter name="self" type="MxGrid*"/> + <parameter name="value" type="gint"/> + </parameters> + </method> + <method name="set_orientation" symbol="mx_grid_set_orientation"> + <return-type type="void"/> + <parameters> + <parameter name="grid" type="MxGrid*"/> + <parameter name="orientation" type="MxOrientation"/> + </parameters> + </method> + <method name="set_row_spacing" symbol="mx_grid_set_row_spacing"> + <return-type type="void"/> + <parameters> + <parameter name="self" type="MxGrid*"/> + <parameter name="value" type="gfloat"/> + </parameters> + </method> + <property name="child-x-align" type="MxAlign" readable="1" writable="1" construct="1" construct-only="0"/> + <property name="child-y-align" type="MxAlign" readable="1" writable="1" construct="1" construct-only="0"/> + <property name="column-spacing" type="gfloat" readable="1" writable="1" construct="1" construct-only="0"/> + <property name="homogenous-columns" type="gboolean" readable="1" writable="1" construct="1" construct-only="0"/> + <property name="homogenous-rows" type="gboolean" readable="1" writable="1" construct="1" construct-only="0"/> + <property name="line-alignment" type="MxAlign" readable="1" writable="1" construct="1" construct-only="0"/> + <property name="max-stride" type="gint" readable="1" writable="1" construct="1" construct-only="0"/> + <property name="orientation" type="MxOrientation" readable="1" writable="1" construct="1" construct-only="0"/> + <property name="row-spacing" type="gfloat" readable="1" writable="1" construct="1" construct-only="0"/> + </object> + <object name="MxIcon" parent="MxWidget" type-name="MxIcon" get-type="mx_icon_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + </implements> + <method name="get_icon_name" symbol="mx_icon_get_icon_name"> + <return-type type="gchar*"/> + <parameters> + <parameter name="icon" type="MxIcon*"/> + </parameters> + </method> + <method name="get_icon_size" symbol="mx_icon_get_icon_size"> + <return-type type="gint"/> + <parameters> + <parameter name="icon" type="MxIcon*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_icon_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="set_icon_name" symbol="mx_icon_set_icon_name"> + <return-type type="void"/> + <parameters> + <parameter name="icon" type="MxIcon*"/> + <parameter name="icon_name" type="gchar*"/> + </parameters> + </method> + <method name="set_icon_size" symbol="mx_icon_set_icon_size"> + <return-type type="void"/> + <parameters> + <parameter name="icon" type="MxIcon*"/> + <parameter name="size" type="gint"/> + </parameters> + </method> + <property name="icon-name" type="char*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="icon-size" type="gint" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxIconTheme" parent="GObject" type-name="MxIconTheme" get-type="mx_icon_theme_get_type"> + <method name="get_default" symbol="mx_icon_theme_get_default"> + <return-type type="MxIconTheme*"/> + </method> + <method name="get_search_paths" symbol="mx_icon_theme_get_search_paths"> + <return-type type="GList*"/> + <parameters> + <parameter name="theme" type="MxIconTheme*"/> + </parameters> + </method> + <method name="get_theme_name" symbol="mx_icon_theme_get_theme_name"> + <return-type type="gchar*"/> + <parameters> + <parameter name="theme" type="MxIconTheme*"/> + </parameters> + </method> + <method name="has_icon" symbol="mx_icon_theme_has_icon"> + <return-type type="gboolean"/> + <parameters> + <parameter name="theme" type="MxIconTheme*"/> + <parameter name="icon_name" type="gchar*"/> + </parameters> + </method> + <method name="lookup" symbol="mx_icon_theme_lookup"> + <return-type type="CoglHandle"/> + <parameters> + <parameter name="theme" type="MxIconTheme*"/> + <parameter name="icon_name" type="gchar*"/> + <parameter name="size" type="gint"/> + </parameters> + </method> + <method name="lookup_texture" symbol="mx_icon_theme_lookup_texture"> + <return-type type="ClutterTexture*"/> + <parameters> + <parameter name="theme" type="MxIconTheme*"/> + <parameter name="icon_name" type="gchar*"/> + <parameter name="size" type="gint"/> + </parameters> + </method> + <constructor name="new" symbol="mx_icon_theme_new"> + <return-type type="MxIconTheme*"/> + </constructor> + <method name="set_search_paths" symbol="mx_icon_theme_set_search_paths"> + <return-type type="void"/> + <parameters> + <parameter name="theme" type="MxIconTheme*"/> + <parameter name="paths" type="GList*"/> + </parameters> + </method> + <method name="set_theme_name" symbol="mx_icon_theme_set_theme_name"> + <return-type type="void"/> + <parameters> + <parameter name="theme" type="MxIconTheme*"/> + <parameter name="theme_name" type="gchar*"/> + </parameters> + </method> + <property name="theme-name" type="char*" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxItemView" parent="MxGrid" type-name="MxItemView" get-type="mx_item_view_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + <interface name="ClutterContainer"/> + <interface name="MxScrollable"/> + <interface name="MxFocusable"/> + </implements> + <method name="add_attribute" symbol="mx_item_view_add_attribute"> + <return-type type="void"/> + <parameters> + <parameter name="item_view" type="MxItemView*"/> + <parameter name="attribute" type="gchar*"/> + <parameter name="column" type="gint"/> + </parameters> + </method> + <method name="freeze" symbol="mx_item_view_freeze"> + <return-type type="void"/> + <parameters> + <parameter name="item_view" type="MxItemView*"/> + </parameters> + </method> + <method name="get_factory" symbol="mx_item_view_get_factory"> + <return-type type="MxItemFactory*"/> + <parameters> + <parameter name="item_view" type="MxItemView*"/> + </parameters> + </method> + <method name="get_item_type" symbol="mx_item_view_get_item_type"> + <return-type type="GType"/> + <parameters> + <parameter name="item_view" type="MxItemView*"/> + </parameters> + </method> + <method name="get_model" symbol="mx_item_view_get_model"> + <return-type type="ClutterModel*"/> + <parameters> + <parameter name="item_view" type="MxItemView*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_item_view_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="set_factory" symbol="mx_item_view_set_factory"> + <return-type type="void"/> + <parameters> + <parameter name="item_view" type="MxItemView*"/> + <parameter name="factory" type="MxItemFactory*"/> + </parameters> + </method> + <method name="set_item_type" symbol="mx_item_view_set_item_type"> + <return-type type="void"/> + <parameters> + <parameter name="item_view" type="MxItemView*"/> + <parameter name="item_type" type="GType"/> + </parameters> + </method> + <method name="set_model" symbol="mx_item_view_set_model"> + <return-type type="void"/> + <parameters> + <parameter name="item_view" type="MxItemView*"/> + <parameter name="model" type="ClutterModel*"/> + </parameters> + </method> + <method name="thaw" symbol="mx_item_view_thaw"> + <return-type type="void"/> + <parameters> + <parameter name="item_view" type="MxItemView*"/> + </parameters> + </method> + <property name="factory" type="GObject*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="item-type" type="GType" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="model" type="ClutterModel*" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxLabel" parent="MxWidget" type-name="MxLabel" get-type="mx_label_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + </implements> + <method name="get_clutter_text" symbol="mx_label_get_clutter_text"> + <return-type type="ClutterActor*"/> + <parameters> + <parameter name="label" type="MxLabel*"/> + </parameters> + </method> + <method name="get_text" symbol="mx_label_get_text"> + <return-type type="gchar*"/> + <parameters> + <parameter name="label" type="MxLabel*"/> + </parameters> + </method> + <method name="get_x_align" symbol="mx_label_get_x_align"> + <return-type type="MxAlign"/> + <parameters> + <parameter name="label" type="MxLabel*"/> + </parameters> + </method> + <method name="get_y_align" symbol="mx_label_get_y_align"> + <return-type type="MxAlign"/> + <parameters> + <parameter name="label" type="MxLabel*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_label_new"> + <return-type type="ClutterActor*"/> + </constructor> + <constructor name="new_with_text" symbol="mx_label_new_with_text"> + <return-type type="ClutterActor*"/> + <parameters> + <parameter name="text" type="gchar*"/> + </parameters> + </constructor> + <method name="set_text" symbol="mx_label_set_text"> + <return-type type="void"/> + <parameters> + <parameter name="label" type="MxLabel*"/> + <parameter name="text" type="gchar*"/> + </parameters> + </method> + <method name="set_x_align" symbol="mx_label_set_x_align"> + <return-type type="void"/> + <parameters> + <parameter name="label" type="MxLabel*"/> + <parameter name="align" type="MxAlign"/> + </parameters> + </method> + <method name="set_y_align" symbol="mx_label_set_y_align"> + <return-type type="void"/> + <parameters> + <parameter name="label" type="MxLabel*"/> + <parameter name="align" type="MxAlign"/> + </parameters> + </method> + <property name="clutter-text" type="ClutterText*" readable="1" writable="0" construct="0" construct-only="0"/> + <property name="text" type="char*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="x-align" type="MxAlign" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="y-align" type="MxAlign" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxListView" parent="MxBoxLayout" type-name="MxListView" get-type="mx_list_view_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + <interface name="ClutterContainer"/> + <interface name="MxScrollable"/> + <interface name="MxFocusable"/> + </implements> + <method name="add_attribute" symbol="mx_list_view_add_attribute"> + <return-type type="void"/> + <parameters> + <parameter name="list_view" type="MxListView*"/> + <parameter name="attribute" type="gchar*"/> + <parameter name="column" type="gint"/> + </parameters> + </method> + <method name="freeze" symbol="mx_list_view_freeze"> + <return-type type="void"/> + <parameters> + <parameter name="list_view" type="MxListView*"/> + </parameters> + </method> + <method name="get_factory" symbol="mx_list_view_get_factory"> + <return-type type="MxItemFactory*"/> + <parameters> + <parameter name="list_view" type="MxListView*"/> + </parameters> + </method> + <method name="get_item_type" symbol="mx_list_view_get_item_type"> + <return-type type="GType"/> + <parameters> + <parameter name="list_view" type="MxListView*"/> + </parameters> + </method> + <method name="get_model" symbol="mx_list_view_get_model"> + <return-type type="ClutterModel*"/> + <parameters> + <parameter name="list_view" type="MxListView*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_list_view_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="set_factory" symbol="mx_list_view_set_factory"> + <return-type type="void"/> + <parameters> + <parameter name="list_view" type="MxListView*"/> + <parameter name="factory" type="MxItemFactory*"/> + </parameters> + </method> + <method name="set_item_type" symbol="mx_list_view_set_item_type"> + <return-type type="void"/> + <parameters> + <parameter name="list_view" type="MxListView*"/> + <parameter name="item_type" type="GType"/> + </parameters> + </method> + <method name="set_model" symbol="mx_list_view_set_model"> + <return-type type="void"/> + <parameters> + <parameter name="list_view" type="MxListView*"/> + <parameter name="model" type="ClutterModel*"/> + </parameters> + </method> + <method name="thaw" symbol="mx_list_view_thaw"> + <return-type type="void"/> + <parameters> + <parameter name="list_view" type="MxListView*"/> + </parameters> + </method> + <property name="factory" type="GObject*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="item-type" type="GType" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="model" type="ClutterModel*" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxMenu" parent="MxFloatingWidget" type-name="MxMenu" get-type="mx_menu_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + </implements> + <method name="add_action" symbol="mx_menu_add_action"> + <return-type type="void"/> + <parameters> + <parameter name="menu" type="MxMenu*"/> + <parameter name="action" type="MxAction*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_menu_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="remove_action" symbol="mx_menu_remove_action"> + <return-type type="void"/> + <parameters> + <parameter name="menu" type="MxMenu*"/> + <parameter name="action" type="MxAction*"/> + </parameters> + </method> + <method name="remove_all" symbol="mx_menu_remove_all"> + <return-type type="void"/> + <parameters> + <parameter name="menu" type="MxMenu*"/> + </parameters> + </method> + <method name="show_with_position" symbol="mx_menu_show_with_position"> + <return-type type="void"/> + <parameters> + <parameter name="menu" type="MxMenu*"/> + <parameter name="x" type="gfloat"/> + <parameter name="y" type="gfloat"/> + </parameters> + </method> + <signal name="action-activated" when="LAST"> + <return-type type="void"/> + <parameters> + <parameter name="menu" type="MxMenu*"/> + <parameter name="action" type="MxAction*"/> + </parameters> + </signal> + </object> + <object name="MxNotebook" parent="MxWidget" type-name="MxNotebook" get-type="mx_notebook_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + <interface name="ClutterContainer"/> + </implements> + <method name="get_current_page" symbol="mx_notebook_get_current_page"> + <return-type type="ClutterActor*"/> + <parameters> + <parameter name="notebook" type="MxNotebook*"/> + </parameters> + </method> + <method name="get_enable_gestures" symbol="mx_notebook_get_enable_gestures"> + <return-type type="gboolean"/> + <parameters> + <parameter name="book" type="MxNotebook*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_notebook_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="set_current_page" symbol="mx_notebook_set_current_page"> + <return-type type="void"/> + <parameters> + <parameter name="notebook" type="MxNotebook*"/> + <parameter name="page" type="ClutterActor*"/> + </parameters> + </method> + <method name="set_enable_gestures" symbol="mx_notebook_set_enable_gestures"> + <return-type type="void"/> + <parameters> + <parameter name="book" type="MxNotebook*"/> + <parameter name="enabled" type="gboolean"/> + </parameters> + </method> + <property name="current-page" type="ClutterActor*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="enable-gestures" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxOffscreen" parent="ClutterTexture" type-name="MxOffscreen" get-type="mx_offscreen_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="ClutterContainer"/> + </implements> + <method name="get_auto_update" symbol="mx_offscreen_get_auto_update"> + <return-type type="gboolean"/> + <parameters> + <parameter name="offscreen" type="MxOffscreen*"/> + </parameters> + </method> + <method name="get_child" symbol="mx_offscreen_get_child"> + <return-type type="ClutterActor*"/> + <parameters> + <parameter name="offscreen" type="MxOffscreen*"/> + </parameters> + </method> + <method name="get_pick_child" symbol="mx_offscreen_get_pick_child"> + <return-type type="gboolean"/> + <parameters> + <parameter name="offscreen" type="MxOffscreen*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_offscreen_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="set_auto_update" symbol="mx_offscreen_set_auto_update"> + <return-type type="void"/> + <parameters> + <parameter name="offscreen" type="MxOffscreen*"/> + <parameter name="auto_update" type="gboolean"/> + </parameters> + </method> + <method name="set_child" symbol="mx_offscreen_set_child"> + <return-type type="void"/> + <parameters> + <parameter name="offscreen" type="MxOffscreen*"/> + <parameter name="actor" type="ClutterActor*"/> + </parameters> + </method> + <method name="set_pick_child" symbol="mx_offscreen_set_pick_child"> + <return-type type="void"/> + <parameters> + <parameter name="offscreen" type="MxOffscreen*"/> + <parameter name="pick" type="gboolean"/> + </parameters> + </method> + <method name="update" symbol="mx_offscreen_update"> + <return-type type="void"/> + <parameters> + <parameter name="offscreen" type="MxOffscreen*"/> + </parameters> + </method> + <property name="auto-update" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="child" type="ClutterActor*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="pick-child" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <vfunc name="paint_child"> + <return-type type="void"/> + <parameters> + <parameter name="self" type="MxOffscreen*"/> + </parameters> + </vfunc> + </object> + <object name="MxPathBar" parent="MxWidget" type-name="MxPathBar" get-type="mx_path_bar_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + <interface name="MxFocusable"/> + </implements> + <method name="clear" symbol="mx_path_bar_clear"> + <return-type type="void"/> + <parameters> + <parameter name="bar" type="MxPathBar*"/> + </parameters> + </method> + <method name="get_clear_on_change" symbol="mx_path_bar_get_clear_on_change"> + <return-type type="gboolean"/> + <parameters> + <parameter name="bar" type="MxPathBar*"/> + </parameters> + </method> + <method name="get_editable" symbol="mx_path_bar_get_editable"> + <return-type type="gboolean"/> + <parameters> + <parameter name="bar" type="MxPathBar*"/> + </parameters> + </method> + <method name="get_entry" symbol="mx_path_bar_get_entry"> + <return-type type="MxEntry*"/> + <parameters> + <parameter name="bar" type="MxPathBar*"/> + </parameters> + </method> + <method name="get_label" symbol="mx_path_bar_get_label"> + <return-type type="gchar*"/> + <parameters> + <parameter name="bar" type="MxPathBar*"/> + <parameter name="level" type="gint"/> + </parameters> + </method> + <method name="get_level" symbol="mx_path_bar_get_level"> + <return-type type="gint"/> + <parameters> + <parameter name="bar" type="MxPathBar*"/> + </parameters> + </method> + <method name="get_text" symbol="mx_path_bar_get_text"> + <return-type type="gchar*"/> + <parameters> + <parameter name="bar" type="MxPathBar*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_path_bar_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="pop" symbol="mx_path_bar_pop"> + <return-type type="gint"/> + <parameters> + <parameter name="bar" type="MxPathBar*"/> + </parameters> + </method> + <method name="push" symbol="mx_path_bar_push"> + <return-type type="gint"/> + <parameters> + <parameter name="bar" type="MxPathBar*"/> + <parameter name="name" type="gchar*"/> + </parameters> + </method> + <method name="set_clear_on_change" symbol="mx_path_bar_set_clear_on_change"> + <return-type type="void"/> + <parameters> + <parameter name="bar" type="MxPathBar*"/> + <parameter name="clear_on_change" type="gboolean"/> + </parameters> + </method> + <method name="set_editable" symbol="mx_path_bar_set_editable"> + <return-type type="void"/> + <parameters> + <parameter name="bar" type="MxPathBar*"/> + <parameter name="editable" type="gboolean"/> + </parameters> + </method> + <method name="set_label" symbol="mx_path_bar_set_label"> + <return-type type="void"/> + <parameters> + <parameter name="bar" type="MxPathBar*"/> + <parameter name="level" type="gint"/> + <parameter name="label" type="gchar*"/> + </parameters> + </method> + <method name="set_text" symbol="mx_path_bar_set_text"> + <return-type type="void"/> + <parameters> + <parameter name="bar" type="MxPathBar*"/> + <parameter name="text" type="gchar*"/> + </parameters> + </method> + <property name="clear-on-change" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="editable" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="entry" type="MxEntry*" readable="1" writable="0" construct="0" construct-only="0"/> + <property name="level" type="gint" readable="1" writable="0" construct="0" construct-only="0"/> + </object> + <object name="MxProgressBar" parent="MxWidget" type-name="MxProgressBar" get-type="mx_progress_bar_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + </implements> + <method name="get_progress" symbol="mx_progress_bar_get_progress"> + <return-type type="gdouble"/> + <parameters> + <parameter name="bar" type="MxProgressBar*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_progress_bar_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="set_progress" symbol="mx_progress_bar_set_progress"> + <return-type type="void"/> + <parameters> + <parameter name="bar" type="MxProgressBar*"/> + <parameter name="progress" type="gdouble"/> + </parameters> + </method> + <property name="progress" type="gdouble" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxScrollBar" parent="MxBin" type-name="MxScrollBar" get-type="mx_scroll_bar_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + <interface name="ClutterContainer"/> + <interface name="MxFocusable"/> + </implements> + <method name="get_adjustment" symbol="mx_scroll_bar_get_adjustment"> + <return-type type="MxAdjustment*"/> + <parameters> + <parameter name="bar" type="MxScrollBar*"/> + </parameters> + </method> + <method name="get_orientation" symbol="mx_scroll_bar_get_orientation"> + <return-type type="MxOrientation"/> + <parameters> + <parameter name="bar" type="MxScrollBar*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_scroll_bar_new"> + <return-type type="ClutterActor*"/> + </constructor> + <constructor name="new_with_adjustment" symbol="mx_scroll_bar_new_with_adjustment"> + <return-type type="ClutterActor*"/> + <parameters> + <parameter name="adjustment" type="MxAdjustment*"/> + </parameters> + </constructor> + <method name="set_adjustment" symbol="mx_scroll_bar_set_adjustment"> + <return-type type="void"/> + <parameters> + <parameter name="bar" type="MxScrollBar*"/> + <parameter name="adjustment" type="MxAdjustment*"/> + </parameters> + </method> + <method name="set_orientation" symbol="mx_scroll_bar_set_orientation"> + <return-type type="void"/> + <parameters> + <parameter name="bar" type="MxScrollBar*"/> + <parameter name="orientation" type="MxOrientation"/> + </parameters> + </method> + <property name="adjustment" type="MxAdjustment*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="orientation" type="MxOrientation" readable="1" writable="1" construct="0" construct-only="0"/> + <signal name="scroll-start" when="LAST"> + <return-type type="void"/> + <parameters> + <parameter name="bar" type="MxScrollBar*"/> + </parameters> + </signal> + <signal name="scroll-stop" when="LAST"> + <return-type type="void"/> + <parameters> + <parameter name="bar" type="MxScrollBar*"/> + </parameters> + </signal> + </object> + <object name="MxScrollView" parent="MxBin" type-name="MxScrollView" get-type="mx_scroll_view_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + <interface name="ClutterContainer"/> + <interface name="MxFocusable"/> + </implements> + <method name="ensure_visible" symbol="mx_scroll_view_ensure_visible"> + <return-type type="void"/> + <parameters> + <parameter name="scroll" type="MxScrollView*"/> + <parameter name="geometry" type="ClutterGeometry*"/> + </parameters> + </method> + <method name="get_enable_gestures" symbol="mx_scroll_view_get_enable_gestures"> + <return-type type="gboolean"/> + <parameters> + <parameter name="scroll" type="MxScrollView*"/> + </parameters> + </method> + <method name="get_enable_mouse_scrolling" symbol="mx_scroll_view_get_enable_mouse_scrolling"> + <return-type type="gboolean"/> + <parameters> + <parameter name="scroll" type="MxScrollView*"/> + </parameters> + </method> + <method name="get_scroll_policy" symbol="mx_scroll_view_get_scroll_policy"> + <return-type type="MxScrollPolicy"/> + <parameters> + <parameter name="scroll" type="MxScrollView*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_scroll_view_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="set_enable_gestures" symbol="mx_scroll_view_set_enable_gestures"> + <return-type type="void"/> + <parameters> + <parameter name="scroll" type="MxScrollView*"/> + <parameter name="enabled" type="gboolean"/> + </parameters> + </method> + <method name="set_enable_mouse_scrolling" symbol="mx_scroll_view_set_enable_mouse_scrolling"> + <return-type type="void"/> + <parameters> + <parameter name="scroll" type="MxScrollView*"/> + <parameter name="enabled" type="gboolean"/> + </parameters> + </method> + <method name="set_scroll_policy" symbol="mx_scroll_view_set_scroll_policy"> + <return-type type="void"/> + <parameters> + <parameter name="scroll" type="MxScrollView*"/> + <parameter name="policy" type="MxScrollPolicy"/> + </parameters> + </method> + <property name="enable-gestures" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="enable-mouse-scrolling" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="scroll-policy" type="MxScrollPolicy" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxSlider" parent="MxWidget" type-name="MxSlider" get-type="mx_slider_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + </implements> + <method name="get_value" symbol="mx_slider_get_value"> + <return-type type="gdouble"/> + <parameters> + <parameter name="bar" type="MxSlider*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_slider_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="set_value" symbol="mx_slider_set_value"> + <return-type type="void"/> + <parameters> + <parameter name="bar" type="MxSlider*"/> + <parameter name="value" type="gdouble"/> + </parameters> + </method> + <property name="value" type="gdouble" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxStyle" parent="GObject" type-name="MxStyle" get-type="mx_style_get_type"> + <method name="get" symbol="mx_style_get"> + <return-type type="void"/> + <parameters> + <parameter name="style" type="MxStyle*"/> + <parameter name="stylable" type="MxStylable*"/> + <parameter name="first_property_name" type="gchar*"/> + </parameters> + </method> + <method name="get_default" symbol="mx_style_get_default"> + <return-type type="MxStyle*"/> + </method> + <method name="get_property" symbol="mx_style_get_property"> + <return-type type="void"/> + <parameters> + <parameter name="style" type="MxStyle*"/> + <parameter name="stylable" type="MxStylable*"/> + <parameter name="pspec" type="GParamSpec*"/> + <parameter name="value" type="GValue*"/> + </parameters> + </method> + <method name="get_valist" symbol="mx_style_get_valist"> + <return-type type="void"/> + <parameters> + <parameter name="style" type="MxStyle*"/> + <parameter name="stylable" type="MxStylable*"/> + <parameter name="first_property_name" type="gchar*"/> + <parameter name="va_args" type="va_list"/> + </parameters> + </method> + <method name="load_from_file" symbol="mx_style_load_from_file"> + <return-type type="gboolean"/> + <parameters> + <parameter name="style" type="MxStyle*"/> + <parameter name="filename" type="gchar*"/> + <parameter name="error" type="GError**"/> + </parameters> + </method> + <constructor name="new" symbol="mx_style_new"> + <return-type type="MxStyle*"/> + </constructor> + <signal name="changed" when="LAST"> + <return-type type="void"/> + <parameters> + <parameter name="style" type="MxStyle*"/> + </parameters> + </signal> + </object> + <object name="MxTable" parent="MxWidget" type-name="MxTable" get-type="mx_table_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + <interface name="ClutterContainer"/> + <interface name="MxFocusable"/> + </implements> + <method name="add_actor" symbol="mx_table_add_actor"> + <return-type type="void"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="actor" type="ClutterActor*"/> + <parameter name="row" type="gint"/> + <parameter name="column" type="gint"/> + </parameters> + </method> + <method name="add_actor_with_properties" symbol="mx_table_add_actor_with_properties"> + <return-type type="void"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="actor" type="ClutterActor*"/> + <parameter name="row" type="gint"/> + <parameter name="column" type="gint"/> + <parameter name="first_property_name" type="gchar*"/> + </parameters> + </method> + <method name="get_column_count" symbol="mx_table_get_column_count"> + <return-type type="gint"/> + <parameters> + <parameter name="table" type="MxTable*"/> + </parameters> + </method> + <method name="get_column_spacing" symbol="mx_table_get_column_spacing"> + <return-type type="gint"/> + <parameters> + <parameter name="table" type="MxTable*"/> + </parameters> + </method> + <method name="get_row_count" symbol="mx_table_get_row_count"> + <return-type type="gint"/> + <parameters> + <parameter name="table" type="MxTable*"/> + </parameters> + </method> + <method name="get_row_spacing" symbol="mx_table_get_row_spacing"> + <return-type type="gint"/> + <parameters> + <parameter name="table" type="MxTable*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_table_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="set_column_spacing" symbol="mx_table_set_column_spacing"> + <return-type type="void"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="spacing" type="gint"/> + </parameters> + </method> + <method name="set_row_spacing" symbol="mx_table_set_row_spacing"> + <return-type type="void"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="spacing" type="gint"/> + </parameters> + </method> + <property name="column-count" type="gint" readable="1" writable="0" construct="0" construct-only="0"/> + <property name="column-spacing" type="gint" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="row-count" type="gint" readable="1" writable="0" construct="0" construct-only="0"/> + <property name="row-spacing" type="gint" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxTableChild" parent="ClutterChildMeta" type-name="MxTableChild" get-type="mx_table_child_get_type"> + <method name="get_column" symbol="mx_table_child_get_column"> + <return-type type="gint"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + </parameters> + </method> + <method name="get_column_span" symbol="mx_table_child_get_column_span"> + <return-type type="gint"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + </parameters> + </method> + <method name="get_row" symbol="mx_table_child_get_row"> + <return-type type="gint"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + </parameters> + </method> + <method name="get_row_span" symbol="mx_table_child_get_row_span"> + <return-type type="gint"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + </parameters> + </method> + <method name="get_x_align" symbol="mx_table_child_get_x_align"> + <return-type type="MxAlign"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + </parameters> + </method> + <method name="get_x_expand" symbol="mx_table_child_get_x_expand"> + <return-type type="gboolean"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + </parameters> + </method> + <method name="get_x_fill" symbol="mx_table_child_get_x_fill"> + <return-type type="gboolean"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + </parameters> + </method> + <method name="get_y_align" symbol="mx_table_child_get_y_align"> + <return-type type="MxAlign"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + </parameters> + </method> + <method name="get_y_expand" symbol="mx_table_child_get_y_expand"> + <return-type type="gboolean"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + </parameters> + </method> + <method name="get_y_fill" symbol="mx_table_child_get_y_fill"> + <return-type type="gboolean"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + </parameters> + </method> + <method name="set_column" symbol="mx_table_child_set_column"> + <return-type type="void"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + <parameter name="col" type="gint"/> + </parameters> + </method> + <method name="set_column_span" symbol="mx_table_child_set_column_span"> + <return-type type="void"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + <parameter name="span" type="gint"/> + </parameters> + </method> + <method name="set_row" symbol="mx_table_child_set_row"> + <return-type type="void"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + <parameter name="row" type="gint"/> + </parameters> + </method> + <method name="set_row_span" symbol="mx_table_child_set_row_span"> + <return-type type="void"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + <parameter name="span" type="gint"/> + </parameters> + </method> + <method name="set_x_align" symbol="mx_table_child_set_x_align"> + <return-type type="void"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + <parameter name="align" type="MxAlign"/> + </parameters> + </method> + <method name="set_x_expand" symbol="mx_table_child_set_x_expand"> + <return-type type="void"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + <parameter name="expand" type="gboolean"/> + </parameters> + </method> + <method name="set_x_fill" symbol="mx_table_child_set_x_fill"> + <return-type type="void"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + <parameter name="fill" type="gboolean"/> + </parameters> + </method> + <method name="set_y_align" symbol="mx_table_child_set_y_align"> + <return-type type="void"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + <parameter name="align" type="MxAlign"/> + </parameters> + </method> + <method name="set_y_expand" symbol="mx_table_child_set_y_expand"> + <return-type type="void"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + <parameter name="expand" type="gboolean"/> + </parameters> + </method> + <method name="set_y_fill" symbol="mx_table_child_set_y_fill"> + <return-type type="void"/> + <parameters> + <parameter name="table" type="MxTable*"/> + <parameter name="child" type="ClutterActor*"/> + <parameter name="fill" type="gboolean"/> + </parameters> + </method> + <property name="column" type="gint" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="column-span" type="gint" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="row" type="gint" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="row-span" type="gint" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="x-align" type="MxAlign" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="x-expand" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="x-fill" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="y-align" type="MxAlign" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="y-expand" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="y-fill" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxTextureCache" parent="GObject" type-name="MxTextureCache" get-type="mx_texture_cache_get_type"> + <method name="get_actor" symbol="mx_texture_cache_get_actor"> + <return-type type="ClutterActor*"/> + <parameters> + <parameter name="self" type="MxTextureCache*"/> + <parameter name="path" type="gchar*"/> + </parameters> + </method> + <method name="get_cogl_texture" symbol="mx_texture_cache_get_cogl_texture"> + <return-type type="CoglHandle"/> + <parameters> + <parameter name="self" type="MxTextureCache*"/> + <parameter name="path" type="gchar*"/> + </parameters> + </method> + <method name="get_default" symbol="mx_texture_cache_get_default"> + <return-type type="MxTextureCache*"/> + </method> + <method name="get_size" symbol="mx_texture_cache_get_size"> + <return-type type="gint"/> + <parameters> + <parameter name="self" type="MxTextureCache*"/> + </parameters> + </method> + <method name="get_texture" symbol="mx_texture_cache_get_texture"> + <return-type type="ClutterTexture*"/> + <parameters> + <parameter name="self" type="MxTextureCache*"/> + <parameter name="path" type="gchar*"/> + </parameters> + </method> + <method name="load_cache" symbol="mx_texture_cache_load_cache"> + <return-type type="void"/> + <parameters> + <parameter name="self" type="MxTextureCache*"/> + <parameter name="filename" type="char*"/> + </parameters> + </method> + <vfunc name="error_loading"> + <return-type type="void"/> + <parameters> + <parameter name="self" type="MxTextureCache*"/> + <parameter name="error" type="GError*"/> + </parameters> + </vfunc> + <vfunc name="loaded"> + <return-type type="void"/> + <parameters> + <parameter name="self" type="MxTextureCache*"/> + <parameter name="path" type="gchar*"/> + <parameter name="texture" type="ClutterTexture*"/> + </parameters> + </vfunc> + </object> + <object name="MxTextureFrame" parent="ClutterActor" type-name="MxTextureFrame" get-type="mx_texture_frame_get_type"> + <implements> + <interface name="ClutterScriptable"/> + </implements> + <method name="get_border_values" symbol="mx_texture_frame_get_border_values"> + <return-type type="void"/> + <parameters> + <parameter name="frame" type="MxTextureFrame*"/> + <parameter name="top" type="gfloat*"/> + <parameter name="right" type="gfloat*"/> + <parameter name="bottom" type="gfloat*"/> + <parameter name="left" type="gfloat*"/> + </parameters> + </method> + <method name="get_parent_texture" symbol="mx_texture_frame_get_parent_texture"> + <return-type type="ClutterTexture*"/> + <parameters> + <parameter name="frame" type="MxTextureFrame*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_texture_frame_new"> + <return-type type="ClutterActor*"/> + <parameters> + <parameter name="texture" type="ClutterTexture*"/> + <parameter name="top" type="gfloat"/> + <parameter name="right" type="gfloat"/> + <parameter name="bottom" type="gfloat"/> + <parameter name="left" type="gfloat"/> + </parameters> + </constructor> + <method name="set_border_values" symbol="mx_texture_frame_set_border_values"> + <return-type type="void"/> + <parameters> + <parameter name="frame" type="MxTextureFrame*"/> + <parameter name="top" type="gfloat"/> + <parameter name="right" type="gfloat"/> + <parameter name="bottom" type="gfloat"/> + <parameter name="left" type="gfloat"/> + </parameters> + </method> + <method name="set_parent_texture" symbol="mx_texture_frame_set_parent_texture"> + <return-type type="void"/> + <parameters> + <parameter name="frame" type="MxTextureFrame*"/> + <parameter name="texture" type="ClutterTexture*"/> + </parameters> + </method> + <property name="bottom" type="gfloat" readable="1" writable="1" construct="1" construct-only="0"/> + <property name="left" type="gfloat" readable="1" writable="1" construct="1" construct-only="0"/> + <property name="parent-texture" type="ClutterTexture*" readable="1" writable="1" construct="1" construct-only="0"/> + <property name="right" type="gfloat" readable="1" writable="1" construct="1" construct-only="0"/> + <property name="top" type="gfloat" readable="1" writable="1" construct="1" construct-only="0"/> + </object> + <object name="MxToggle" parent="MxWidget" type-name="MxToggle" get-type="mx_toggle_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + </implements> + <method name="get_active" symbol="mx_toggle_get_active"> + <return-type type="gboolean"/> + <parameters> + <parameter name="toggle" type="MxToggle*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_toggle_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="set_active" symbol="mx_toggle_set_active"> + <return-type type="void"/> + <parameters> + <parameter name="toggle" type="MxToggle*"/> + <parameter name="active" type="gboolean"/> + </parameters> + </method> + <property name="active" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxToolbar" parent="MxBin" type-name="MxToolbar" get-type="mx_toolbar_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + <interface name="ClutterContainer"/> + <interface name="MxFocusable"/> + </implements> + <method name="get_has_close_button" symbol="mx_toolbar_get_has_close_button"> + <return-type type="gboolean"/> + <parameters> + <parameter name="toolbar" type="MxToolbar*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_toolbar_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="set_has_close_button" symbol="mx_toolbar_set_has_close_button"> + <return-type type="void"/> + <parameters> + <parameter name="toolbar" type="MxToolbar*"/> + <parameter name="has_close_button" type="gboolean"/> + </parameters> + </method> + <property name="has-close-button" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <signal name="close-button-clicked" when="LAST"> + <return-type type="gboolean"/> + <parameters> + <parameter name="toolbar" type="MxToolbar*"/> + </parameters> + </signal> + </object> + <object name="MxTooltip" parent="MxFloatingWidget" type-name="MxTooltip" get-type="mx_tooltip_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + </implements> + <method name="get_text" symbol="mx_tooltip_get_text"> + <return-type type="gchar*"/> + <parameters> + <parameter name="tooltip" type="MxTooltip*"/> + </parameters> + </method> + <method name="get_tip_area" symbol="mx_tooltip_get_tip_area"> + <return-type type="ClutterGeometry*"/> + <parameters> + <parameter name="tooltip" type="MxTooltip*"/> + </parameters> + </method> + <method name="hide" symbol="mx_tooltip_hide"> + <return-type type="void"/> + <parameters> + <parameter name="tooltip" type="MxTooltip*"/> + </parameters> + </method> + <method name="set_text" symbol="mx_tooltip_set_text"> + <return-type type="void"/> + <parameters> + <parameter name="tooltip" type="MxTooltip*"/> + <parameter name="text" type="gchar*"/> + </parameters> + </method> + <method name="set_tip_area" symbol="mx_tooltip_set_tip_area"> + <return-type type="void"/> + <parameters> + <parameter name="tooltip" type="MxTooltip*"/> + <parameter name="area" type="ClutterGeometry*"/> + </parameters> + </method> + <method name="show" symbol="mx_tooltip_show"> + <return-type type="void"/> + <parameters> + <parameter name="tooltip" type="MxTooltip*"/> + </parameters> + </method> + <property name="text" type="char*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="tip-area" type="ClutterGeometry*" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxViewport" parent="MxBin" type-name="MxViewport" get-type="mx_viewport_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + <interface name="ClutterContainer"/> + <interface name="MxFocusable"/> + <interface name="MxScrollable"/> + </implements> + <method name="get_origin" symbol="mx_viewport_get_origin"> + <return-type type="void"/> + <parameters> + <parameter name="viewport" type="MxViewport*"/> + <parameter name="x" type="gfloat*"/> + <parameter name="y" type="gfloat*"/> + <parameter name="z" type="gfloat*"/> + </parameters> + </method> + <method name="get_sync_adjustments" symbol="mx_viewport_get_sync_adjustments"> + <return-type type="gboolean"/> + <parameters> + <parameter name="viewport" type="MxViewport*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_viewport_new"> + <return-type type="ClutterActor*"/> + </constructor> + <method name="set_origin" symbol="mx_viewport_set_origin"> + <return-type type="void"/> + <parameters> + <parameter name="viewport" type="MxViewport*"/> + <parameter name="x" type="gfloat"/> + <parameter name="y" type="gfloat"/> + <parameter name="z" type="gfloat"/> + </parameters> + </method> + <method name="set_sync_adjustments" symbol="mx_viewport_set_sync_adjustments"> + <return-type type="void"/> + <parameters> + <parameter name="viewport" type="MxViewport*"/> + <parameter name="sync" type="gboolean"/> + </parameters> + </method> + <property name="sync-adjustments" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="x-origin" type="gfloat" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="y-origin" type="gfloat" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="z-origin" type="gfloat" readable="1" writable="1" construct="0" construct-only="0"/> + </object> + <object name="MxWidget" parent="ClutterActor" type-name="MxWidget" get-type="mx_widget_get_type"> + <implements> + <interface name="ClutterScriptable"/> + <interface name="MxStylable"/> + </implements> + <method name="get_available_area" symbol="mx_widget_get_available_area"> + <return-type type="void"/> + <parameters> + <parameter name="widget" type="MxWidget*"/> + <parameter name="allocation" type="ClutterActorBox*"/> + <parameter name="area" type="ClutterActorBox*"/> + </parameters> + </method> + <method name="get_background_image" symbol="mx_widget_get_background_image"> + <return-type type="ClutterActor*"/> + <parameters> + <parameter name="actor" type="MxWidget*"/> + </parameters> + </method> + <method name="get_border_image" symbol="mx_widget_get_border_image"> + <return-type type="ClutterActor*"/> + <parameters> + <parameter name="actor" type="MxWidget*"/> + </parameters> + </method> + <method name="get_disabled" symbol="mx_widget_get_disabled"> + <return-type type="gboolean"/> + <parameters> + <parameter name="widget" type="MxWidget*"/> + </parameters> + </method> + <method name="get_menu" symbol="mx_widget_get_menu"> + <return-type type="MxMenu*"/> + <parameters> + <parameter name="widget" type="MxWidget*"/> + </parameters> + </method> + <method name="get_padding" symbol="mx_widget_get_padding"> + <return-type type="void"/> + <parameters> + <parameter name="widget" type="MxWidget*"/> + <parameter name="padding" type="MxPadding*"/> + </parameters> + </method> + <method name="get_tooltip_text" symbol="mx_widget_get_tooltip_text"> + <return-type type="gchar*"/> + <parameters> + <parameter name="widget" type="MxWidget*"/> + </parameters> + </method> + <method name="hide_tooltip" symbol="mx_widget_hide_tooltip"> + <return-type type="void"/> + <parameters> + <parameter name="widget" type="MxWidget*"/> + </parameters> + </method> + <method name="long_press_cancel" symbol="mx_widget_long_press_cancel"> + <return-type type="void"/> + <parameters> + <parameter name="widget" type="MxWidget*"/> + </parameters> + </method> + <method name="long_press_query" symbol="mx_widget_long_press_query"> + <return-type type="void"/> + <parameters> + <parameter name="widget" type="MxWidget*"/> + <parameter name="event" type="ClutterButtonEvent*"/> + </parameters> + </method> + <method name="paint_background" symbol="mx_widget_paint_background"> + <return-type type="void"/> + <parameters> + <parameter name="widget" type="MxWidget*"/> + </parameters> + </method> + <method name="set_disabled" symbol="mx_widget_set_disabled"> + <return-type type="void"/> + <parameters> + <parameter name="widget" type="MxWidget*"/> + <parameter name="disabled" type="gboolean"/> + </parameters> + </method> + <method name="set_menu" symbol="mx_widget_set_menu"> + <return-type type="void"/> + <parameters> + <parameter name="widget" type="MxWidget*"/> + <parameter name="menu" type="MxMenu*"/> + </parameters> + </method> + <method name="set_tooltip_text" symbol="mx_widget_set_tooltip_text"> + <return-type type="void"/> + <parameters> + <parameter name="widget" type="MxWidget*"/> + <parameter name="text" type="gchar*"/> + </parameters> + </method> + <method name="show_tooltip" symbol="mx_widget_show_tooltip"> + <return-type type="void"/> + <parameters> + <parameter name="widget" type="MxWidget*"/> + </parameters> + </method> + <property name="disabled" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="menu" type="MxMenu*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="tooltip-text" type="char*" readable="1" writable="1" construct="0" construct-only="0"/> + <signal name="long-press" when="LAST"> + <return-type type="gboolean"/> + <parameters> + <parameter name="widget" type="MxWidget*"/> + <parameter name="action" type="gfloat"/> + <parameter name="x" type="gfloat"/> + <parameter name="y" type="MxLongPressAction"/> + </parameters> + </signal> + <vfunc name="paint_background"> + <return-type type="void"/> + <parameters> + <parameter name="self" type="MxWidget*"/> + <parameter name="background" type="ClutterActor*"/> + <parameter name="color" type="ClutterColor*"/> + </parameters> + </vfunc> + </object> + <object name="MxWindow" parent="GObject" type-name="MxWindow" get-type="mx_window_get_type"> + <method name="get_child" symbol="mx_window_get_child"> + <return-type type="ClutterActor*"/> + <parameters> + <parameter name="window" type="MxWindow*"/> + </parameters> + </method> + <method name="get_clutter_stage" symbol="mx_window_get_clutter_stage"> + <return-type type="ClutterStage*"/> + <parameters> + <parameter name="window" type="MxWindow*"/> + </parameters> + </method> + <method name="get_for_stage" symbol="mx_window_get_for_stage"> + <return-type type="MxWindow*"/> + <parameters> + <parameter name="stage" type="ClutterStage*"/> + </parameters> + </method> + <method name="get_has_toolbar" symbol="mx_window_get_has_toolbar"> + <return-type type="gboolean"/> + <parameters> + <parameter name="window" type="MxWindow*"/> + </parameters> + </method> + <method name="get_icon_name" symbol="mx_window_get_icon_name"> + <return-type type="gchar*"/> + <parameters> + <parameter name="window" type="MxWindow*"/> + </parameters> + </method> + <method name="get_small_screen" symbol="mx_window_get_small_screen"> + <return-type type="gboolean"/> + <parameters> + <parameter name="window" type="MxWindow*"/> + </parameters> + </method> + <method name="get_toolbar" symbol="mx_window_get_toolbar"> + <return-type type="MxToolbar*"/> + <parameters> + <parameter name="window" type="MxWindow*"/> + </parameters> + </method> + <method name="get_window_position" symbol="mx_window_get_window_position"> + <return-type type="void"/> + <parameters> + <parameter name="window" type="MxWindow*"/> + <parameter name="x" type="gint*"/> + <parameter name="y" type="gint*"/> + </parameters> + </method> + <constructor name="new" symbol="mx_window_new"> + <return-type type="MxWindow*"/> + </constructor> + <constructor name="new_with_clutter_stage" symbol="mx_window_new_with_clutter_stage"> + <return-type type="MxWindow*"/> + <parameters> + <parameter name="stage" type="ClutterStage*"/> + </parameters> + </constructor> + <method name="set_child" symbol="mx_window_set_child"> + <return-type type="void"/> + <parameters> + <parameter name="window" type="MxWindow*"/> + <parameter name="actor" type="ClutterActor*"/> + </parameters> + </method> + <method name="set_has_toolbar" symbol="mx_window_set_has_toolbar"> + <return-type type="void"/> + <parameters> + <parameter name="window" type="MxWindow*"/> + <parameter name="toolbar" type="gboolean"/> + </parameters> + </method> + <method name="set_icon_from_cogl_texture" symbol="mx_window_set_icon_from_cogl_texture"> + <return-type type="void"/> + <parameters> + <parameter name="window" type="MxWindow*"/> + <parameter name="texture" type="CoglHandle"/> + </parameters> + </method> + <method name="set_icon_name" symbol="mx_window_set_icon_name"> + <return-type type="void"/> + <parameters> + <parameter name="window" type="MxWindow*"/> + <parameter name="icon_name" type="gchar*"/> + </parameters> + </method> + <method name="set_small_screen" symbol="mx_window_set_small_screen"> + <return-type type="void"/> + <parameters> + <parameter name="window" type="MxWindow*"/> + <parameter name="small_screen" type="gboolean"/> + </parameters> + </method> + <method name="set_window_position" symbol="mx_window_set_window_position"> + <return-type type="void"/> + <parameters> + <parameter name="window" type="MxWindow*"/> + <parameter name="x" type="gint"/> + <parameter name="y" type="gint"/> + </parameters> + </method> + <property name="child" type="ClutterActor*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="clutter-stage" type="ClutterStage*" readable="1" writable="1" construct="0" construct-only="1"/> + <property name="has-toolbar" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="icon-cogl-texture" type="char*" readable="0" writable="1" construct="0" construct-only="0"/> + <property name="icon-name" type="char*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="small-screen" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="toolbar" type="MxToolbar*" readable="1" writable="0" construct="0" construct-only="0"/> + <signal name="destroy" when="LAST"> + <return-type type="void"/> + <parameters> + <parameter name="window" type="MxWindow*"/> + </parameters> + </signal> + </object> + <interface name="MxDraggable" type-name="MxDraggable" get-type="mx_draggable_get_type"> + <requires> + <interface name="ClutterActor"/> + </requires> + <method name="disable" symbol="mx_draggable_disable"> + <return-type type="void"/> + <parameters> + <parameter name="draggable" type="MxDraggable*"/> + </parameters> + </method> + <method name="enable" symbol="mx_draggable_enable"> + <return-type type="void"/> + <parameters> + <parameter name="draggable" type="MxDraggable*"/> + </parameters> + </method> + <method name="get_axis" symbol="mx_draggable_get_axis"> + <return-type type="MxDragAxis"/> + <parameters> + <parameter name="draggable" type="MxDraggable*"/> + </parameters> + </method> + <method name="get_drag_actor" symbol="mx_draggable_get_drag_actor"> + <return-type type="ClutterActor*"/> + <parameters> + <parameter name="draggable" type="MxDraggable*"/> + </parameters> + </method> + <method name="get_drag_threshold" symbol="mx_draggable_get_drag_threshold"> + <return-type type="guint"/> + <parameters> + <parameter name="draggable" type="MxDraggable*"/> + </parameters> + </method> + <method name="is_enabled" symbol="mx_draggable_is_enabled"> + <return-type type="gboolean"/> + <parameters> + <parameter name="draggable" type="MxDraggable*"/> + </parameters> + </method> + <method name="set_axis" symbol="mx_draggable_set_axis"> + <return-type type="void"/> + <parameters> + <parameter name="draggable" type="MxDraggable*"/> + <parameter name="axis" type="MxDragAxis"/> + </parameters> + </method> + <method name="set_drag_actor" symbol="mx_draggable_set_drag_actor"> + <return-type type="void"/> + <parameters> + <parameter name="draggable" type="MxDraggable*"/> + <parameter name="actor" type="ClutterActor*"/> + </parameters> + </method> + <method name="set_drag_threshold" symbol="mx_draggable_set_drag_threshold"> + <return-type type="void"/> + <parameters> + <parameter name="draggable" type="MxDraggable*"/> + <parameter name="threshold" type="guint"/> + </parameters> + </method> + <property name="axis" type="MxDragAxis" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="drag-actor" type="ClutterActor*" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="drag-enabled" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <property name="drag-threshold" type="guint" readable="1" writable="1" construct="0" construct-only="0"/> + <signal name="drag-begin" when="FIRST"> + <return-type type="void"/> + <parameters> + <parameter name="draggable" type="MxDraggable*"/> + <parameter name="event_x" type="gfloat"/> + <parameter name="event_y" type="gfloat"/> + <parameter name="event_button" type="gint"/> + <parameter name="modifiers" type="ClutterModifierType"/> + </parameters> + </signal> + <signal name="drag-end" when="FIRST"> + <return-type type="void"/> + <parameters> + <parameter name="draggable" type="MxDraggable*"/> + <parameter name="event_x" type="gfloat"/> + <parameter name="event_y" type="gfloat"/> + </parameters> + </signal> + <signal name="drag-motion" when="FIRST"> + <return-type type="void"/> + <parameters> + <parameter name="draggable" type="MxDraggable*"/> + <parameter name="delta_x" type="gfloat"/> + <parameter name="delta_y" type="gfloat"/> + </parameters> + </signal> + <vfunc name="disable"> + <return-type type="void"/> + <parameters> + <parameter name="draggable" type="MxDraggable*"/> + </parameters> + </vfunc> + <vfunc name="enable"> + <return-type type="void"/> + <parameters> + <parameter name="draggable" type="MxDraggable*"/> + </parameters> + </vfunc> + </interface> + <interface name="MxDroppable" type-name="MxDroppable" get-type="mx_droppable_get_type"> + <requires> + <interface name="ClutterActor"/> + </requires> + <method name="accept_drop" symbol="mx_droppable_accept_drop"> + <return-type type="gboolean"/> + <parameters> + <parameter name="droppable" type="MxDroppable*"/> + <parameter name="draggable" type="MxDraggable*"/> + </parameters> + </method> + <method name="disable" symbol="mx_droppable_disable"> + <return-type type="void"/> + <parameters> + <parameter name="droppable" type="MxDroppable*"/> + </parameters> + </method> + <method name="enable" symbol="mx_droppable_enable"> + <return-type type="void"/> + <parameters> + <parameter name="droppable" type="MxDroppable*"/> + </parameters> + </method> + <method name="is_enabled" symbol="mx_droppable_is_enabled"> + <return-type type="gboolean"/> + <parameters> + <parameter name="droppable" type="MxDroppable*"/> + </parameters> + </method> + <property name="drop-enabled" type="gboolean" readable="1" writable="1" construct="0" construct-only="0"/> + <signal name="drop" when="FIRST"> + <return-type type="void"/> + <parameters> + <parameter name="droppable" type="MxDroppable*"/> + <parameter name="draggable" type="ClutterActor*"/> + <parameter name="event_x" type="gfloat"/> + <parameter name="event_y" type="gfloat"/> + <parameter name="button" type="gint"/> + <parameter name="modifiers" type="ClutterModifierType"/> + </parameters> + </signal> + <signal name="over-in" when="FIRST"> + <return-type type="void"/> + <parameters> + <parameter name="droppable" type="MxDroppable*"/> + <parameter name="draggable" type="ClutterActor*"/> + </parameters> + </signal> + <signal name="over-out" when="FIRST"> + <return-type type="void"/> + <parameters> + <parameter name="droppable" type="MxDroppable*"/> + <parameter name="draggable" type="ClutterActor*"/> + </parameters> + </signal> + <vfunc name="accept_drop"> + <return-type type="gboolean"/> + <parameters> + <parameter name="droppable" type="MxDroppable*"/> + <parameter name="draggable" type="MxDraggable*"/> + </parameters> + </vfunc> + <vfunc name="disable"> + <return-type type="void"/> + <parameters> + <parameter name="droppable" type="MxDroppable*"/> + </parameters> + </vfunc> + <vfunc name="enable"> + <return-type type="void"/> + <parameters> + <parameter name="droppable" type="MxDroppable*"/> + </parameters> + </vfunc> + </interface> + <interface name="MxFocusable" type-name="MxFocusable" get-type="mx_focusable_get_type"> + <method name="accept_focus" symbol="mx_focusable_accept_focus"> + <return-type type="MxFocusable*"/> + <parameters> + <parameter name="focusable" type="MxFocusable*"/> + <parameter name="hint" type="MxFocusHint"/> + </parameters> + </method> + <method name="move_focus" symbol="mx_focusable_move_focus"> + <return-type type="MxFocusable*"/> + <parameters> + <parameter name="focusable" type="MxFocusable*"/> + <parameter name="direction" type="MxFocusDirection"/> + <parameter name="from" type="MxFocusable*"/> + </parameters> + </method> + <vfunc name="accept_focus"> + <return-type type="MxFocusable*"/> + <parameters> + <parameter name="focusable" type="MxFocusable*"/> + <parameter name="hint" type="MxFocusHint"/> + </parameters> + </vfunc> + <vfunc name="move_focus"> + <return-type type="MxFocusable*"/> + <parameters> + <parameter name="focusable" type="MxFocusable*"/> + <parameter name="direction" type="MxFocusDirection"/> + <parameter name="from" type="MxFocusable*"/> + </parameters> + </vfunc> + </interface> + <interface name="MxItemFactory" type-name="MxItemFactory" get-type="mx_item_factory_get_type"> + <method name="create" symbol="mx_item_factory_create"> + <return-type type="ClutterActor*"/> + <parameters> + <parameter name="factory" type="MxItemFactory*"/> + </parameters> + </method> + <vfunc name="create"> + <return-type type="ClutterActor*"/> + <parameters> + <parameter name="factory" type="MxItemFactory*"/> + </parameters> + </vfunc> + </interface> + <interface name="MxScrollable" type-name="MxScrollable" get-type="mx_scrollable_get_type"> + <method name="get_adjustments" symbol="mx_scrollable_get_adjustments"> + <return-type type="void"/> + <parameters> + <parameter name="scrollable" type="MxScrollable*"/> + <parameter name="hadjustment" type="MxAdjustment**"/> + <parameter name="vadjustment" type="MxAdjustment**"/> + </parameters> + </method> + <method name="set_adjustments" symbol="mx_scrollable_set_adjustments"> + <return-type type="void"/> + <parameters> + <parameter name="scrollable" type="MxScrollable*"/> + <parameter name="hadjustment" type="MxAdjustment*"/> + <parameter name="vadjustment" type="MxAdjustment*"/> + </parameters> + </method> + <vfunc name="get_adjustments"> + <return-type type="void"/> + <parameters> + <parameter name="scrollable" type="MxScrollable*"/> + <parameter name="hadjustment" type="MxAdjustment**"/> + <parameter name="vadjustment" type="MxAdjustment**"/> + </parameters> + </vfunc> + <vfunc name="set_adjustments"> + <return-type type="void"/> + <parameters> + <parameter name="scrollable" type="MxScrollable*"/> + <parameter name="hadjustment" type="MxAdjustment*"/> + <parameter name="vadjustment" type="MxAdjustment*"/> + </parameters> + </vfunc> + </interface> + <interface name="MxStylable" type-name="MxStylable" get-type="mx_stylable_get_type"> + <method name="apply_clutter_text_attributes" symbol="mx_stylable_apply_clutter_text_attributes"> + <return-type type="void"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + <parameter name="text" type="ClutterText*"/> + </parameters> + </method> + <method name="connect_change_notifiers" symbol="mx_stylable_connect_change_notifiers"> + <return-type type="void"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + </parameters> + </method> + <method name="find_property" symbol="mx_stylable_find_property"> + <return-type type="GParamSpec*"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + <parameter name="property_name" type="gchar*"/> + </parameters> + </method> + <method name="get" symbol="mx_stylable_get"> + <return-type type="void"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + <parameter name="first_property_name" type="gchar*"/> + </parameters> + </method> + <method name="get_default_value" symbol="mx_stylable_get_default_value"> + <return-type type="gboolean"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + <parameter name="property_name" type="gchar*"/> + <parameter name="value_out" type="GValue*"/> + </parameters> + </method> + <method name="get_property" symbol="mx_stylable_get_property"> + <return-type type="void"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + <parameter name="property_name" type="gchar*"/> + <parameter name="value" type="GValue*"/> + </parameters> + </method> + <method name="get_style" symbol="mx_stylable_get_style"> + <return-type type="MxStyle*"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + </parameters> + </method> + <method name="get_style_class" symbol="mx_stylable_get_style_class"> + <return-type type="gchar*"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + </parameters> + </method> + <method name="get_style_pseudo_class" symbol="mx_stylable_get_style_pseudo_class"> + <return-type type="gchar*"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + </parameters> + </method> + <method name="iface_install_property" symbol="mx_stylable_iface_install_property"> + <return-type type="void"/> + <parameters> + <parameter name="iface" type="MxStylableIface*"/> + <parameter name="owner_type" type="GType"/> + <parameter name="pspec" type="GParamSpec*"/> + </parameters> + </method> + <method name="list_properties" symbol="mx_stylable_list_properties"> + <return-type type="GParamSpec**"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + <parameter name="n_props" type="guint*"/> + </parameters> + </method> + <method name="set_style" symbol="mx_stylable_set_style"> + <return-type type="void"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + <parameter name="style" type="MxStyle*"/> + </parameters> + </method> + <method name="set_style_class" symbol="mx_stylable_set_style_class"> + <return-type type="void"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + <parameter name="style_class" type="gchar*"/> + </parameters> + </method> + <method name="set_style_pseudo_class" symbol="mx_stylable_set_style_pseudo_class"> + <return-type type="void"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + <parameter name="pseudo_class" type="gchar*"/> + </parameters> + </method> + <method name="style_changed" symbol="mx_stylable_style_changed"> + <return-type type="void"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + <parameter name="flags" type="MxStyleChangedFlags"/> + </parameters> + </method> + <signal name="style-changed" when="FIRST"> + <return-type type="void"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + <parameter name="flags" type="MxStyleChangedFlags"/> + </parameters> + </signal> + <vfunc name="get_style"> + <return-type type="MxStyle*"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + </parameters> + </vfunc> + <vfunc name="get_style_class"> + <return-type type="gchar*"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + </parameters> + </vfunc> + <vfunc name="get_style_pseudo_class"> + <return-type type="gchar*"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + </parameters> + </vfunc> + <vfunc name="set_style"> + <return-type type="void"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + <parameter name="style" type="MxStyle*"/> + </parameters> + </vfunc> + <vfunc name="set_style_class"> + <return-type type="void"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + <parameter name="style_class" type="gchar*"/> + </parameters> + </vfunc> + <vfunc name="set_style_pseudo_class"> + <return-type type="void"/> + <parameters> + <parameter name="stylable" type="MxStylable*"/> + <parameter name="style_class" type="gchar*"/> + </parameters> + </vfunc> + </interface> + <constant name="MX_MAJOR_VERSION" type="int" value="1"/> + <constant name="MX_MICRO_VERSION" type="int" value="0"/> + <constant name="MX_MINOR_VERSION" type="int" value="0"/> + <constant name="MX_VERSION_HEX" type="int" value="0"/> + <constant name="MX_VERSION_S" type="char*" value="1.0.0"/> + </namespace> +</api> diff --git a/vapi/packages/mx-1.0/mx-1.0.metadata b/vapi/packages/mx-1.0/mx-1.0.metadata new file mode 100644 index 0000000000..04d212a4e8 --- /dev/null +++ b/vapi/packages/mx-1.0/mx-1.0.metadata @@ -0,0 +1,12 @@ +Mx* cheader_filename="mx/mx.h" +mx_application_new.argc hidden="1" +mx_application_new.argv is_array="1" is_ref="1" array_length_pos="0.9" +mx_button_group_foreach.userdata hidden="1" +mx_button_group_set_active_button.button nullable="1" +MxStylable::style_changed has_emitter="1" +mx_stylable_iface_install_property hidden="1" +mx_stylable_notify name="emit_notify" + +# Should be removed when bug #614686 is resolved +mx_table_add_actor hidden="1" +mx_box_layout_add_actor hidden="1" diff --git a/vapi/packages/mx-1.0/mx-1.0.namespace b/vapi/packages/mx-1.0/mx-1.0.namespace new file mode 100644 index 0000000000..a6cea364ad --- /dev/null +++ b/vapi/packages/mx-1.0/mx-1.0.namespace @@ -0,0 +1 @@ +Mx
3e4efd0d34df74f1c3f2360dcf79f8b4f028e739
Valadoc
gtkdoc-importer: Add support for orderedlist
a
https://github.com/GNOME/vala/
diff --git a/src/libvaladoc/documentation/gtkdoccommentparser.vala b/src/libvaladoc/documentation/gtkdoccommentparser.vala index 4c5a236b51..d73003aafc 100644 --- a/src/libvaladoc/documentation/gtkdoccommentparser.vala +++ b/src/libvaladoc/documentation/gtkdoccommentparser.vala @@ -609,9 +609,13 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { return (Warning?) parse_docbook_information_box_template ("warning", factory.create_warning ()); } - private Content.List? parse_docbook_itemizedlist () { - if (!check_xml_open_tag ("itemizedlist")) { - this.report_unexpected_token (current, "<itemizedlist>"); + private inline Content.List? parse_docbook_orderedlist () { + return parse_docbook_itemizedlist ("orderedlist", Content.List.Bullet.ORDERED); + } + + private Content.List? parse_docbook_itemizedlist (string tag_name = "itemizedlist", Content.List.Bullet bullet_type = Content.List.Bullet.UNORDERED) { + if (!check_xml_open_tag (tag_name)) { + this.report_unexpected_token (current, "<%s>".printf (tag_name)); return null; } @@ -620,7 +624,7 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { parse_docbook_spaces (); Content.List list = factory.create_list (); - list.bullet = Content.List.Bullet.UNORDERED; + list.bullet = bullet_type; while (current.type == TokenType.XML_OPEN) { if (current.content == "listitem") { @@ -632,8 +636,8 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { parse_docbook_spaces (); } - if (!check_xml_close_tag ("itemizedlist")) { - this.report_unexpected_token (current, "</itemizedlist>"); + if (!check_xml_close_tag (tag_name)) { + this.report_unexpected_token (current, "</%s>".printf (tag_name)); return list; } @@ -1373,6 +1377,8 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { if (current.type == TokenType.XML_OPEN && current.content == "itemizedlist") { this.append_block_content_not_null (content, parse_docbook_itemizedlist ()); + } else if (current.type == TokenType.XML_OPEN && current.content == "orderedlist") { + this.append_block_content_not_null (content, parse_docbook_orderedlist ()); } else if (current.type == TokenType.XML_OPEN && current.content == "variablelist") { this.append_block_content_not_null_all (content, parse_docbook_variablelist ()); } else if (current.type == TokenType.XML_OPEN && current.content == "simplelist") {
0e707e9b96c2086154b5352bf4c5ceb050a590a5
Valadoc
Add support for valac 0.18.0
a
https://github.com/GNOME/vala/
diff --git a/configure.in b/configure.in index 95248c5761..488792919c 100755 --- a/configure.in +++ b/configure.in @@ -62,6 +62,12 @@ AC_SUBST(LIBGDKPIXBUF_LIBS) ## Drivers: ## +PKG_CHECK_MODULES(LIBVALA_0_18_X, libvala-0.18 >= 0.17.0, have_libvala_0_18_x="yes", have_libvala_0_18_x="no") +AM_CONDITIONAL(HAVE_LIBVALA_0_18_X, test "$have_libvala_0_18_x" = "yes") +AC_SUBST(LIBVALA_0_18_X_CFLAGS) +AC_SUBST(LIBVALA_0_18_X_LIBS) + + PKG_CHECK_MODULES(LIBVALA_0_16_X, libvala-0.16 >= 0.15.1, have_libvala_0_16_x="yes", have_libvala_0_16_x="no") AM_CONDITIONAL(HAVE_LIBVALA_0_16_X, test "$have_libvala_0_16_x" = "yes") AC_SUBST(LIBVALA_0_16_X_CFLAGS) @@ -134,6 +140,7 @@ AC_CONFIG_FILES([Makefile src/driver/0.12.x/Makefile src/driver/0.14.x/Makefile src/driver/0.16.x/Makefile + src/driver/0.18.x/Makefile src/doclets/Makefile src/doclets/htm/Makefile src/doclets/devhelp/Makefile diff --git a/src/driver/0.18.x/Makefile.am b/src/driver/0.18.x/Makefile.am new file mode 100755 index 0000000000..c8ee3fd0c4 --- /dev/null +++ b/src/driver/0.18.x/Makefile.am @@ -0,0 +1,68 @@ +NULL = + + + +VERSIONED_VAPI_DIR=`pkg-config libvala-0.18 --variable vapidir` + + + +AM_CFLAGS = -g \ + -DPACKAGE_ICONDIR=\"$(datadir)/valadoc/icons/\" \ + -I ../../libvaladoc/ \ + $(GLIB_CFLAGS) \ + $(LIBGEE_CFLAGS) \ + $(LIBVALA_0_18_X_CFLAGS) \ + $(NULL) + + + +BUILT_SOURCES = libdriver.vala.stamp + + +driverdir = $(libdir)/valadoc/drivers/0.18.x + + +libdriver_la_LDFLAGS = -module -avoid-version -no-undefined + + +driver_LTLIBRARIES = \ + libdriver.la \ + $(NULL) + + +libdriver_la_VALASOURCES = \ + initializerbuilder.vala \ + symbolresolver.vala \ + treebuilder.vala \ + girwriter.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 $(VERSIONED_VAPI_DIR) --vapidir $(top_srcdir)/src/vapi --vapidir $(top_srcdir)/src/libvaladoc --pkg libvala-0.18 --pkg gee-1.0 --pkg valadoc-1.0 --basedir . $^ + touch $@ + + +libdriver_la_LIBADD = \ + ../../libvaladoc/libvaladoc.la \ + $(GLIB_LIBS) \ + $(LIBVALA_0_18_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.18.x/driver.vala b/src/driver/0.18.x/driver.vala new file mode 100755 index 0000000000..35d43d1381 --- /dev/null +++ b/src/driver/0.18.x/driver.vala @@ -0,0 +1,65 @@ +/* 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 { + private SymbolResolver resolver; + private Api.Tree? tree; + + public void write_gir (Settings settings, ErrorReporter reporter) { + var gir_writer = new Drivers.GirWriter (resolver); + + // put .gir file in current directory unless -d has been explicitly specified + string gir_directory = "."; + if (settings.gir_directory != null) { + gir_directory = settings.gir_directory; + } + + gir_writer.write_file ((Vala.CodeContext) tree.data, gir_directory, settings.gir_namespace, settings.gir_version, settings.pkg_name); + } + + public Api.Tree? build (Settings settings, ErrorReporter reporter) { + TreeBuilder builder = new TreeBuilder (); + tree = builder.build (settings, reporter); + if (reporter.errors > 0) { + return null; + } + + 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.18.x/girwriter.vala b/src/driver/0.18.x/girwriter.vala new file mode 100644 index 0000000000..c250854d64 --- /dev/null +++ b/src/driver/0.18.x/girwriter.vala @@ -0,0 +1,204 @@ +/* girwriter.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; + + +/** + * Code visitor generating .gir file for the public interface. + */ +public class Valadoc.Drivers.GirWriter : Vala.GIRWriter { + private GtkdocRenderer renderer; + private SymbolResolver resolver; + + public GirWriter (SymbolResolver resolver) { + this.renderer = new GtkdocRenderer (); + this.resolver = resolver; + } + + private string? translate (Content.Comment? documentation) { + if (documentation == null) { + return null; + } + + renderer.render_symbol (documentation); + + return MarkupWriter.escape (renderer.content); + } + + private string? translate_taglet (Content.Taglet? taglet) { + if (taglet == null) { + return null; + } + + renderer.render_children (taglet); + + return MarkupWriter.escape (renderer.content); + } + + protected override string? get_interface_comment (Vala.Interface viface) { + Interface iface = resolver.resolve (viface) as Interface; + return translate (iface.documentation); + } + + protected override string? get_struct_comment (Vala.Struct vst) { + Struct st = resolver.resolve (vst) as Struct; + return translate (st.documentation); + } + + protected override string? get_enum_comment (Vala.Enum ven) { + Enum en = resolver.resolve (ven) as Enum; + return translate (en.documentation); + } + + protected override string? get_class_comment (Vala.Class vc) { + Class c = resolver.resolve (vc) as Class; + return translate (c.documentation); + } + + protected override string? get_error_code_comment (Vala.ErrorCode vecode) { + ErrorCode ecode = resolver.resolve (vecode) as ErrorCode; + return translate (ecode.documentation); + } + + protected override string? get_enum_value_comment (Vala.EnumValue vev) { + Api.EnumValue ev = resolver.resolve (vev) as Api.EnumValue; + return translate (ev.documentation); + } + + protected override string? get_constant_comment (Vala.Constant vc) { + Constant c = resolver.resolve (vc) as Constant; + return translate (c.documentation); + } + + protected override string? get_error_domain_comment (Vala.ErrorDomain vedomain) { + ErrorDomain edomain = resolver.resolve (vedomain) as ErrorDomain; + return translate (edomain.documentation); + } + + protected override string? get_field_comment (Vala.Field vf) { + Field f = resolver.resolve (vf) as Field; + return translate (f.documentation); + } + + protected override string? get_delegate_comment (Vala.Delegate vcb) { + Delegate cb = resolver.resolve (vcb) as Delegate; + return translate (cb.documentation); + } + + protected override string? get_method_comment (Vala.Method vm) { + Method m = resolver.resolve (vm) as Method; + return translate (m.documentation); + } + + protected override string? get_property_comment (Vala.Property vprop) { + Property prop = resolver.resolve (vprop) as Property; + return translate (prop.documentation); + } + + protected override string? get_delegate_return_comment (Vala.Delegate vcb) { + Delegate cb = resolver.resolve (vcb) as Delegate; + if (cb.documentation == null) { + return null; + } + + Content.Comment? documentation = cb.documentation; + if (documentation == null) { + return null; + } + + Gee.List<Content.Taglet> taglets = documentation.find_taglets (cb, typeof(Taglets.Return)); + foreach (Content.Taglet taglet in taglets) { + return translate_taglet (taglet); + } + + return null; + } + + protected override string? get_signal_return_comment (Vala.Signal vsig) { + Api.Signal sig = resolver.resolve (vsig) as Api.Signal; + if (sig.documentation == null) { + return null; + } + + Content.Comment? documentation = sig.documentation; + if (documentation == null) { + return null; + } + + Gee.List<Content.Taglet> taglets = documentation.find_taglets (sig, typeof(Taglets.Return)); + foreach (Content.Taglet taglet in taglets) { + return translate_taglet (taglet); + } + + return null; + } + + protected override string? get_method_return_comment (Vala.Method vm) { + Method m = resolver.resolve (vm) as Method; + if (m.documentation == null) { + return null; + } + + Content.Comment? documentation = m.documentation; + if (documentation == null) { + return null; + } + + Gee.List<Content.Taglet> taglets = documentation.find_taglets (m, typeof(Taglets.Return)); + foreach (Content.Taglet taglet in taglets) { + return translate_taglet (taglet); + } + + return null; + } + + protected override string? get_signal_comment (Vala.Signal vsig) { + Api.Signal sig = resolver.resolve (vsig) as Api.Signal; + return translate (sig.documentation); + } + + protected override string? get_parameter_comment (Vala.Parameter param) { + Api.Symbol symbol = resolver.resolve (((Vala.Symbol) param.parent_symbol)); + if (symbol == null) { + return null; + } + + Content.Comment? documentation = symbol.documentation; + if (documentation == null) { + return null; + } + + Gee.List<Content.Taglet> taglets = documentation.find_taglets (symbol, typeof(Taglets.Param)); + foreach (Content.Taglet _taglet in taglets) { + Taglets.Param taglet = (Taglets.Param) _taglet; + if (taglet.parameter_name == param.name) { + return translate_taglet (taglet); + } + } + + return null; + } +} + + diff --git a/src/driver/0.18.x/initializerbuilder.vala b/src/driver/0.18.x/initializerbuilder.vala new file mode 100644 index 0000000000..70fd1d6bb9 --- /dev/null +++ b/src/driver/0.18.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.18.x/symbolresolver.vala b/src/driver/0.18.x/symbolresolver.vala new file mode 100644 index 0000000000..f548f735d8 --- /dev/null +++ b/src/driver/0.18.x/symbolresolver.vala @@ -0,0 +1,321 @@ +/* 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 (); + } + + public Symbol? resolve (Vala.Symbol symbol) { + return symbol_map.get (symbol); + } + + private void resolve_thrown_list (Symbol symbol, Vala.List<Vala.DataType> types) { + foreach (Vala.DataType type in types) { + Vala.ErrorDomain vala_edom = (Vala.ErrorDomain) type.data_type; + Symbol? edom = symbol_map.get (vala_edom); + symbol.add_child (edom ?? glib_error); + } + } + + 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) { + Vala.Delegate vala_delegate = item.data as Vala.Delegate; + + resolve_type_reference (item.return_type); + + resolve_thrown_list (item, vala_delegate.get_error_types ()); + + 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_thrown_list (item, vala_method.get_error_types ()); + + 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.18.x/treebuilder.vala b/src/driver/0.18.x/treebuilder.vala new file mode 100644 index 0000000000..3a1fb0385b --- /dev/null +++ b/src/driver/0.18.x/treebuilder.vala @@ -0,0 +1,1183 @@ +/* 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; + if (c is Vala.GirComment) { + comment = new GirSourceComment (c.content, file, pos.first_line, pos.first_column, pos.last_line, pos.last_column); + } else { + 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.CodeNode 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); + if (comment is Vala.GirComment) { + var tmp = new GirSourceComment (comment.content, file, pos.first_line, pos.first_column, pos.last_line, pos.last_column); + if (((Vala.GirComment) comment).return_content != null) { + Vala.SourceReference return_pos = ((Vala.GirComment) comment).return_content.source_reference; + tmp.return_comment = new SourceComment (((Vala.GirComment) comment).return_content.content, file, return_pos.first_line, return_pos.first_column, return_pos.last_line, return_pos.last_column); + } + + Vala.MapIterator<string, Vala.Comment> it = ((Vala.GirComment) comment).parameter_iterator (); + while (it.next ()) { + Vala.Comment vala_param = it.get_value (); + Vala.SourceReference param_pos = vala_param.source_reference; + var param_comment = new SourceComment (vala_param.content, file, param_pos.first_line, param_pos.first_column, param_pos.last_line, param_pos.last_column); + tmp.add_parameter_content (it.get_key (), param_comment); + } + return tmp; + } else { + 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 (meta_data.package, 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 string get_package_name (string path) { + string file_name = Path.get_basename (path); + return file_name.substring (0, file_name.last_index_of_char ('.')); + } + + 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 = 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 = get_package_name (source); + + 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"); + } + + if (settings.target_glib != null && settings.target_glib.scanf ("%d.%d", out glib_major, out glib_minor) != 2) { + Vala.Report.error (null, "Invalid format for --target-glib"); + } + + 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"); + } + + for (int i = 16; i <= glib_minor; i += 2) { + context.add_define ("GLIB_2_%d".printf (i)); + } + + // 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_ccode_type_id (element), get_param_spec_function (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_ccode_type_id (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 (accessor), 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 (accessor), 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.settings = settings; + this.reporter = reporter; + + this.tree = new Api.Tree (reporter, settings); + var context = create_valac_tree (settings); + this.tree.data = context; + + reporter.warnings_offset = context.report.get_warnings (); + reporter.errors_offset = context.report.get_errors (); + + if (context == null) { + return null; + } + + // TODO: Register all packages here + // register packages included by gir-files + foreach (Vala.SourceFile vfile in context.get_source_files ()) { + if (vfile.file_type == Vala.SourceFileType.PACKAGE && vfile.get_nodes ().size > 0 && files.contains (vfile) == false) { + Package vdpkg = new Package (get_package_name (vfile.filename), true, null); + register_source_file (register_package (vdpkg), vfile); + } + } + + context.accept(this); + + return (reporter.errors == 0)? tree : null; + } +} + + diff --git a/src/driver/Makefile.am b/src/driver/Makefile.am index 863cc95f6f..ada5a150ed 100755 --- a/src/driver/Makefile.am +++ b/src/driver/Makefile.am @@ -34,11 +34,17 @@ if HAVE_LIBVALA_0_16_X DRIVER_0_16_X_DIR = 0.16.x endif +if HAVE_LIBVALA_0_18_X +DRIVER_0_18_X_DIR = 0.18.x +endif + + SUBDIRS = \ $(DRIVER_0_10_X_DIR) \ $(DRIVER_0_12_X_DIR) \ $(DRIVER_0_14_X_DIR) \ $(DRIVER_0_16_X_DIR) \ + $(DRIVER_0_18_X_DIR) \ $(NULL) diff --git a/src/libvaladoc/moduleloader.vala b/src/libvaladoc/moduleloader.vala index bcad4d5552..9ac5d7b9ed 100755 --- a/src/libvaladoc/moduleloader.vala +++ b/src/libvaladoc/moduleloader.vala @@ -143,7 +143,8 @@ public class Valadoc.ModuleLoader : Object { DriverMetaData (0, 10, 0, 10, "0.10.x"), DriverMetaData (0, 11, 0, 12, "0.12.x"), DriverMetaData (0, 13, 0, 14, "0.14.x"), - DriverMetaData (0, 15, 0, 16, "0.16.x") + DriverMetaData (0, 15, 0, 16, "0.16.x"), + DriverMetaData (0, 17, 0, 18, "0.18.x") };
67b40f7142ea54d9d8234fd30ae82c85b3c7176c
camel
CAMEL-2470: Adding test for sending back a reply- to JMSReplyTo based on a temporary queue.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@949117 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/camel
diff --git a/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java b/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java index 11725b01dccb0..59713a088527d 100644 --- a/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java +++ b/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsEndpoint.java @@ -120,11 +120,9 @@ public static JmsEndpoint newInstance(Destination destination, JmsComponent comp public static JmsEndpoint newInstance(Destination destination) throws JMSException { if (destination instanceof TemporaryQueue) { return new JmsTemporaryQueueEndpoint((TemporaryQueue) destination); - } - if (destination instanceof TemporaryTopic) { + } else if (destination instanceof TemporaryTopic) { return new JmsTemporaryTopicEndpoint((TemporaryTopic) destination); - } - if (destination instanceof Queue) { + } else if (destination instanceof Queue) { return new JmsQueueEndpoint((Queue) destination); } else { return new JmsEndpoint((Topic) destination); diff --git a/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsTemporaryQueueEndpoint.java b/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsTemporaryQueueEndpoint.java index b30c2c32fdf2d..f7cd4034d1188 100644 --- a/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsTemporaryQueueEndpoint.java +++ b/components/camel-jms/src/main/java/org/apache/camel/component/jms/JmsTemporaryQueueEndpoint.java @@ -24,10 +24,11 @@ /** * A <a href="http://activemq.apache.org/jms.html">JMS Endpoint</a> * for working with a {@link TemporaryQueue} + * <p/> + * <b>Important:</b> Need to be really careful to always use the same Connection otherwise the destination goes stale * * @version $Revision$ */ -// TODO need to be really careful to always use the same Connection otherwise the destination goes stale public class JmsTemporaryQueueEndpoint extends JmsQueueEndpoint implements DestinationEndpoint { private Destination jmsDestination; @@ -61,11 +62,10 @@ public boolean isSingleton() { } @Override - // We don't want to manage this temporary object public Object getManagedObject(JmsEndpoint object) { + // We don't want to manage this temporary object, so return null return null; } - public synchronized Destination getJmsDestination(Session session) throws JMSException { if (jmsDestination == null) { diff --git a/components/camel-jms/src/test/java/org/apache/camel/component/jms/issues/TempReplyToIssueTest.java b/components/camel-jms/src/test/java/org/apache/camel/component/jms/issues/TempReplyToIssueTest.java new file mode 100644 index 0000000000000..f77da977b1c43 --- /dev/null +++ b/components/camel-jms/src/test/java/org/apache/camel/component/jms/issues/TempReplyToIssueTest.java @@ -0,0 +1,91 @@ +/** + * 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.component.jms.issues; + +import javax.jms.ConnectionFactory; +import javax.jms.Destination; + +import org.apache.activemq.ActiveMQConnectionFactory; +import org.apache.camel.Body; +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.Header; +import org.apache.camel.Processor; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.jms.JmsConstants; +import org.apache.camel.test.junit4.CamelTestSupport; +import org.junit.Test; + +import static org.apache.camel.component.jms.JmsComponent.jmsComponentClientAcknowledge; + +/** + * @version $Revision$ + */ +public class TempReplyToIssueTest extends CamelTestSupport { + + @Test + public void testReplyToIssue() throws Exception { + String out = template.requestBody("activemq:queue:test.queue", "World", String.class); + // we should receive that fixed reply + assertEquals("Hello Moon", out); + } + + public String handleMessage(final @Header("JMSReplyTo") Destination jmsReplyTo, final @Header("JMSCorrelationID") String id, + @Body String body, Exchange exchange) throws Exception { + assertNotNull(jmsReplyTo); + assertTrue("Should be a temp queue", jmsReplyTo.toString().startsWith("temp-queue")); + + // we send the reply manually (notice we just use a bogus endpoint uri) + ProducerTemplate producer = exchange.getContext().createProducerTemplate(); + producer.send("activemq:queue:xxx", new Processor() { + public void process(Exchange exchange) throws Exception { + exchange.getIn().setBody("Hello Moon"); + // remember to set correlation id + exchange.getIn().setHeader("JMSCorrelationID", id); + // this is the real destination we send the reply to + exchange.getIn().setHeader(JmsConstants.JMS_DESTINATION, jmsReplyTo); + } + }); + // stop it after use + producer.stop(); + + // sleep a bit so Camel will send the reply a bit later + Thread.sleep(1000); + + // this will later cause a problem as the temp queue has been deleted + // and exceptions will be logged etc + return "Hello " + body; + } + + protected CamelContext createCamelContext() throws Exception { + CamelContext camelContext = super.createCamelContext(); + ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"); + camelContext.addComponent("activemq", jmsComponentClientAcknowledge(connectionFactory)); + return camelContext; + } + + @Override + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + @Override + public void configure() throws Exception { + from("activemq:queue:test.queue").bean(TempReplyToIssueTest.class, "handleMessage"); + } + }; + } +}
f5ff5b55dbe1c786acddbe835ed1b6ef824e0c9e
tapiji
Removes out-dated LGPL sources and adapts copyright headers. The wording "TapiJI" located in the copyright header has been replaced with a list of all contributors that have modified a particular file.
p
https://github.com/tapiji/tapiji
diff --git a/org.eclipse.babel.core/META-INF/MANIFEST.MF b/org.eclipse.babel.core/META-INF/MANIFEST.MF index 0955b9d3..eac2c587 100644 --- a/org.eclipse.babel.core/META-INF/MANIFEST.MF +++ b/org.eclipse.babel.core/META-INF/MANIFEST.MF @@ -26,5 +26,6 @@ Export-Package: org.eclipse.babel.core.configuration;uses:="org.eclipse.babel.co Require-Bundle: org.eclipse.core.databinding, org.eclipse.core.resources, org.eclipse.core.runtime, - org.eclipse.jdt.core;bundle-version="3.6.2" + org.eclipse.jdt.core;bundle-version="3.6.2", + org.eclipse.pde.core;bundle-version="3.7.1" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/ConfigurationManager.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/ConfigurationManager.java index 66639ae7..dda1538e 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/ConfigurationManager.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/ConfigurationManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/DirtyHack.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/DirtyHack.java index ba1770bc..c4c37a4c 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/DirtyHack.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/DirtyHack.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/IConfiguration.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/IConfiguration.java index 4b8b26b1..5fdef1f3 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/IConfiguration.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/configuration/IConfiguration.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessageFactory.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessageFactory.java index b7c1bcd0..5ab62fa0 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessageFactory.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessageFactory.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessagesBundleGroupFactory.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessagesBundleGroupFactory.java index 2ac01f85..bafc1fc4 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessagesBundleGroupFactory.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/factory/MessagesBundleGroupFactory.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessage.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessage.java index 779af4a0..85dae2ef 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessage.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessage.java @@ -1,12 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Martin Reiterer - initial API + * Martin Reiterer - initial API * Alexej Strelzow - extended API ******************************************************************************/ package org.eclipse.babel.core.message; diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundle.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundle.java index c3c6c911..ef843f56 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundle.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundle.java @@ -1,12 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Martin Reiterer - initial API + * Martin Reiterer - initial API * Alexej Strelzow - extended API ******************************************************************************/ package org.eclipse.babel.core.message; diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundleGroup.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundleGroup.java index 13177f4b..5de5c0ab 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundleGroup.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/IMessagesBundleGroup.java @@ -1,12 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Martin Reiterer - initial API + * Martin Reiterer - initial API * Alexej Strelzow - extended API ******************************************************************************/ package org.eclipse.babel.core.message; diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IMessagesEditorListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IMessagesEditorListener.java index b4d7aaf9..9ab5b378 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IMessagesEditorListener.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IMessagesEditorListener.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IResourceDeltaListener.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IResourceDeltaListener.java index 4f309816..15b18db6 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IResourceDeltaListener.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/IResourceDeltaListener.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/RBManager.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/RBManager.java index 1d8f7d79..a4e1c561 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/RBManager.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/RBManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -520,6 +520,7 @@ protected void detectResourceBundles() { for (IProject p : fragments) { p.accept(new ResourceBundleDetectionVisitor(this)); } + } } catch (CoreException e) { logger.log(Level.SEVERE, "detectResourceBundles: accept failed!", e); diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java index 6f7d5ccc..38ff1a9d 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/ResourceBundleDetectionVisitor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/IPropertiesDeserializerConfig.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/IPropertiesDeserializerConfig.java index c5eaee78..6791225b 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/IPropertiesDeserializerConfig.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/IPropertiesDeserializerConfig.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/IPropertiesSerializerConfig.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/IPropertiesSerializerConfig.java index c3f77ed4..c5f452e6 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/IPropertiesSerializerConfig.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/resource/ser/IPropertiesSerializerConfig.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IAbstractKeyTreeModel.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IAbstractKeyTreeModel.java index 8e87ae22..632184f9 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IAbstractKeyTreeModel.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IAbstractKeyTreeModel.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeNode.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeNode.java index f774382b..b7b85856 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeNode.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/IKeyTreeNode.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/TreeType.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/TreeType.java index 67049e74..bf833e90 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/TreeType.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/tree/TreeType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileUtils.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileUtils.java index 689b5a0b..2a226522 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileUtils.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/FileUtils.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/NameUtils.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/NameUtils.java index 90ff2f52..7fafe733 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/NameUtils.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/NameUtils.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java index 69ede279..887626f7 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/util/PDEUtils.java @@ -239,7 +239,7 @@ public static String getFileContent(IFile file, String charset) { } } - private static String getManifestEntryValue(IResource manifest, String entryKey) { + private static String getManifestEntryValue(IResource manifest, String entryKey) { if (manifest instanceof IFile) { String content = getFileContent((IFile) manifest, "UTF8"); //$NON-NLS-1$ int index = content.indexOf(entryKey); diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditor.java index dedc0e90..8774bc53 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditor.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/IMessagesEditor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Matthias Lettmayer. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/AnalyzerFactory.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/AnalyzerFactory.java index 70b7bfc9..b0ead893 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/AnalyzerFactory.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/AnalyzerFactory.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ILevenshteinDistanceAnalyzer.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ILevenshteinDistanceAnalyzer.java index e3bf349c..fcf0ff6c 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ILevenshteinDistanceAnalyzer.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ILevenshteinDistanceAnalyzer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/IValuedKeyTreeNode.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/IValuedKeyTreeNode.java index 6be0f20f..88e53f98 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/IValuedKeyTreeNode.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/IValuedKeyTreeNode.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/KeyTreeFactory.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/KeyTreeFactory.java index a5a2c770..f79ae8fe 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/KeyTreeFactory.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/KeyTreeFactory.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ValuedKeyTreeNode.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ValuedKeyTreeNode.java index 0a02dd6d..89ab1a6f 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ValuedKeyTreeNode.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/api/ValuedKeyTreeNode.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/IKeyTreeContributor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/IKeyTreeContributor.java index e4d1bf07..0a503b08 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/IKeyTreeContributor.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/IKeyTreeContributor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/IResourceBundleWizard.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/IResourceBundleWizard.java index 7d4b05a8..5a797dcb 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/IResourceBundleWizard.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/IResourceBundleWizard.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleNewWizardPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleNewWizardPage.java index 12f7e427..0d5597b9 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleNewWizardPage.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/wizards/internal/ResourceBundleNewWizardPage.java @@ -1,23 +1,15 @@ -/* - * Copyright (C) 2003, 2004 Pascal Essiembre, Essiembre Consultant Inc. - * - * This file is part of Essiembre ResourceBundle Editor. - * - * Essiembre ResourceBundle Editor is free software; you can redistribute it - * and/or modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * Essiembre ResourceBundle Editor is distributed in the hope that it will be - * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with Essiembre ResourceBundle Editor; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307 USA - */ +/******************************************************************************* + * 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 + * Clemente Lodi-Fè - fixing bugs and setting dialog defaults + ******************************************************************************/ + package org.eclipse.babel.editor.wizards.internal; import java.util.Locale; @@ -55,7 +47,7 @@ * the new bundle group as well as the bundle group common base name. The page * will only accept file name without the extension. * @author Pascal Essiembre ([email protected]) - * @version $Author: pessiembr $ $Revision: 1.1 $ $Date: 2008/01/11 04:17:06 $ + * @version $Author: droy $ $Revision: 1.2 $ $Date: 2012/07/18 20:13:09 $ */ public class ResourceBundleNewWizardPage extends WizardPage { diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/Activator.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/Activator.java index 746db867..c3fdae77 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/Activator.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/Activator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -19,70 +19,70 @@ */ public class Activator extends AbstractUIPlugin { - // The plug-in ID - public static final String PLUGIN_ID = "org.eclipse.babel.tapiji.tools.core.ui"; //$NON-NLS-1$ + // The plug-in ID + public static final String PLUGIN_ID = "org.eclipse.babel.tapiji.tools.core.ui"; //$NON-NLS-1$ - // The shared instance - private static Activator plugin; + // The shared instance + private static Activator plugin; - /** - * The constructor - */ - public Activator() { - } - - /** - * Returns an image descriptor for the image file at the given plug-in - * relative path - * - * @param path - * the path - * @return the image descriptor - */ - public static ImageDescriptor getImageDescriptor(String path) { - if (path.indexOf("icons/") < 0) { - path = "icons/" + path; - } + /** + * The constructor + */ + public Activator() { + } - return imageDescriptorFromPlugin(PLUGIN_ID, path); + /** + * Returns an image descriptor for the image file at the given plug-in + * relative path + * + * @param path + * the path + * @return the image descriptor + */ + public static ImageDescriptor getImageDescriptor(String path) { + if (path.indexOf("icons/") < 0) { + path = "icons/" + path; } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext - * ) - */ - @Override - public void start(BundleContext context) throws Exception { - super.start(context); - plugin = this; - } + return imageDescriptorFromPlugin(PLUGIN_ID, path); + } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext - * ) - */ - @Override - public void stop(BundleContext context) throws Exception { - // save state of ResourceBundleManager - ResourceBundleManager.saveManagerState(); + /* + * (non-Javadoc) + * + * @see + * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext + * ) + */ + @Override + public void start(BundleContext context) throws Exception { + super.start(context); + plugin = this; + } - plugin = null; - super.stop(context); - } + /* + * (non-Javadoc) + * + * @see + * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext + * ) + */ + @Override + public void stop(BundleContext context) throws Exception { + // save state of ResourceBundleManager + ResourceBundleManager.saveManagerState(); - /** - * Returns the shared instance - * - * @return the shared instance - */ - public static Activator getDefault() { - return plugin; - } + plugin = null; + super.stop(context); + } + + /** + * Returns the shared instance + * + * @return the shared instance + */ + public static Activator getDefault() { + return plugin; + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java index 234af8e9..4656e5a3 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/ResourceBundleManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -60,758 +60,759 @@ public class ResourceBundleManager { - public static String defaultLocaleTag = "[default]"; // TODO externalize + public static String defaultLocaleTag = "[default]"; // TODO externalize - /*** CONFIG SECTION ***/ - private static boolean checkResourceExclusionRoot = false; + /*** CONFIG SECTION ***/ + private static boolean checkResourceExclusionRoot = false; - /*** MEMBER SECTION ***/ - private static Map<IProject, ResourceBundleManager> rbmanager = new HashMap<IProject, ResourceBundleManager>(); + /*** MEMBER SECTION ***/ + private static Map<IProject, ResourceBundleManager> rbmanager = new HashMap<IProject, ResourceBundleManager>(); - public static final String RESOURCE_BUNDLE_EXTENSION = ".properties"; + public static final String RESOURCE_BUNDLE_EXTENSION = ".properties"; - // project-specific - private Map<String, Set<IResource>> resources = new HashMap<String, Set<IResource>>(); + // project-specific + private Map<String, Set<IResource>> resources = new HashMap<String, Set<IResource>>(); - private Map<String, String> bundleNames = new HashMap<String, String>(); + private Map<String, String> bundleNames = new HashMap<String, String>(); - private Map<String, List<IResourceBundleChangedListener>> listeners = new HashMap<String, List<IResourceBundleChangedListener>>(); + private Map<String, List<IResourceBundleChangedListener>> listeners = new HashMap<String, List<IResourceBundleChangedListener>>(); - private List<IResourceExclusionListener> exclusionListeners = new ArrayList<IResourceExclusionListener>(); + private List<IResourceExclusionListener> exclusionListeners = new ArrayList<IResourceExclusionListener>(); - // global - private static Set<IResourceDescriptor> excludedResources = new HashSet<IResourceDescriptor>(); + // global + private static Set<IResourceDescriptor> excludedResources = new HashSet<IResourceDescriptor>(); - private static Map<String, Set<IResource>> allBundles = new HashMap<String, Set<IResource>>(); + private static Map<String, Set<IResource>> allBundles = new HashMap<String, Set<IResource>>(); - // private static IResourceChangeListener changelistener; // - // RBChangeListener -> see stateLoader! + // private static IResourceChangeListener changelistener; // + // RBChangeListener -> see stateLoader! - public static final String NATURE_ID = Activator.PLUGIN_ID + ".nature"; + public static final String NATURE_ID = Activator.PLUGIN_ID + ".nature"; - public static final String BUILDER_ID = Activator.PLUGIN_ID - + ".I18NBuilder"; + public static final String BUILDER_ID = Activator.PLUGIN_ID + + ".I18NBuilder"; - /* Host project */ - private IProject project = null; + /* Host project */ + private IProject project = null; - /** State-Serialization Information **/ - private static boolean state_loaded = false; + /** State-Serialization Information **/ + private static boolean state_loaded = false; - private static IStateLoader stateLoader; + private static IStateLoader stateLoader; - // Define private constructor - private ResourceBundleManager(IProject project) { - this.project = project; - - RBManager.getInstance(project).addResourceDeltaListener( - new IResourceDeltaListener() { - - /** - * {@inheritDoc} - */ - @Override - public void onDelete(IMessagesBundleGroup bundleGroup) { - resources.remove(bundleGroup.getResourceBundleId()); - } - - /** - * {@inheritDoc} - */ - @Override - public void onDelete(String resourceBundleId, IResource resource) { - resources.get(resourceBundleId).remove(resource); - } - }); - } + // Define private constructor + private ResourceBundleManager(IProject project) { + this.project = project; - public static ResourceBundleManager getManager(IProject project) { - // check if persistant state has been loaded - if (!state_loaded) { - stateLoader = getStateLoader(); - stateLoader.loadState(); - state_loaded = true; - excludedResources = stateLoader.getExcludedResources(); - } + RBManager.getInstance(project).addResourceDeltaListener( + new IResourceDeltaListener() { - // set host-project - if (FragmentProjectUtils.isFragment(project)) { - project = FragmentProjectUtils.getFragmentHost(project); - } - - ResourceBundleManager manager = rbmanager.get(project); - if (manager == null) { - manager = new ResourceBundleManager(project); - rbmanager.put(project, manager); - manager.detectResourceBundles(); - } - return manager; - } + /** + * {@inheritDoc} + */ + @Override + public void onDelete(IMessagesBundleGroup bundleGroup) { + resources.remove(bundleGroup.getResourceBundleId()); + } - public Set<Locale> getProvidedLocales(String bundleName) { - RBManager instance = RBManager.getInstance(project); - - Set<Locale> locales = new HashSet<Locale>(); - IMessagesBundleGroup group = instance - .getMessagesBundleGroup(bundleName); - if (group == null) { - return locales; - } + /** + * {@inheritDoc} + */ + @Override + public void onDelete(String resourceBundleId, + IResource resource) { + resources.get(resourceBundleId).remove(resource); + } + }); + } - for (IMessagesBundle bundle : group.getMessagesBundles()) { - locales.add(bundle.getLocale()); - } - return locales; + public static ResourceBundleManager getManager(IProject project) { + // check if persistant state has been loaded + if (!state_loaded) { + stateLoader = getStateLoader(); + stateLoader.loadState(); + state_loaded = true; + excludedResources = stateLoader.getExcludedResources(); } - public static String getResourceBundleName(IResource res) { - String name = res.getName(); - String regex = "^(.*?)" //$NON-NLS-1$ - + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$ - + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$ - + res.getFileExtension() + ")$"; //$NON-NLS-1$ - return name.replaceFirst(regex, "$1"); //$NON-NLS-1$ + // set host-project + if (FragmentProjectUtils.isFragment(project)) { + project = FragmentProjectUtils.getFragmentHost(project); + } + + ResourceBundleManager manager = rbmanager.get(project); + if (manager == null) { + manager = new ResourceBundleManager(project); + rbmanager.put(project, manager); + manager.detectResourceBundles(); } + return manager; + } + + public Set<Locale> getProvidedLocales(String bundleName) { + RBManager instance = RBManager.getInstance(project); - protected boolean isResourceBundleLoaded(String bundleName) { - return RBManager.getInstance(project).containsMessagesBundleGroup( - bundleName); + Set<Locale> locales = new HashSet<Locale>(); + IMessagesBundleGroup group = instance + .getMessagesBundleGroup(bundleName); + if (group == null) { + return locales; } - protected void unloadResource(String bundleName, IResource resource) { - // TODO implement more efficient - unloadResourceBundle(bundleName); - // loadResourceBundle(bundleName); + for (IMessagesBundle bundle : group.getMessagesBundles()) { + locales.add(bundle.getLocale()); } + return locales; + } + + public static String getResourceBundleName(IResource res) { + String name = res.getName(); + String regex = "^(.*?)" //$NON-NLS-1$ + + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" //$NON-NLS-1$ + + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." //$NON-NLS-1$ + + res.getFileExtension() + ")$"; //$NON-NLS-1$ + return name.replaceFirst(regex, "$1"); //$NON-NLS-1$ + } - public static String getResourceBundleId(IResource resource) { - String packageFragment = ""; + protected boolean isResourceBundleLoaded(String bundleName) { + return RBManager.getInstance(project).containsMessagesBundleGroup( + bundleName); + } - IJavaElement propertyFile = JavaCore.create(resource.getParent()); - if (propertyFile != null && propertyFile instanceof IPackageFragment) { - packageFragment = ((IPackageFragment) propertyFile) - .getElementName(); - } + protected void unloadResource(String bundleName, IResource resource) { + // TODO implement more efficient + unloadResourceBundle(bundleName); + // loadResourceBundle(bundleName); + } - return (packageFragment.length() > 0 ? packageFragment + "." : "") - + getResourceBundleName(resource); - } + public static String getResourceBundleId(IResource resource) { + String packageFragment = ""; - public void addBundleResource(IResource resource) { - if (resource.isDerived()) { - return; - } + IJavaElement propertyFile = JavaCore.create(resource.getParent()); + if (propertyFile != null && propertyFile instanceof IPackageFragment) { + packageFragment = ((IPackageFragment) propertyFile) + .getElementName(); + } - String bundleName = getResourceBundleId(resource); - Set<IResource> res; + return (packageFragment.length() > 0 ? packageFragment + "." : "") + + getResourceBundleName(resource); + } - if (!resources.containsKey(bundleName)) { - res = new HashSet<IResource>(); - } else { - res = resources.get(bundleName); - } + public void addBundleResource(IResource resource) { + if (resource.isDerived()) { + return; + } - res.add(resource); - resources.put(bundleName, res); - allBundles.put(bundleName, new HashSet<IResource>(res)); - bundleNames.put(bundleName, getResourceBundleName(resource)); + String bundleName = getResourceBundleId(resource); + Set<IResource> res; - // Fire resource changed event - ResourceBundleChangedEvent event = new ResourceBundleChangedEvent( - ResourceBundleChangedEvent.ADDED, bundleName, - resource.getProject()); - this.fireResourceBundleChangedEvent(bundleName, event); + if (!resources.containsKey(bundleName)) { + res = new HashSet<IResource>(); + } else { + res = resources.get(bundleName); } - protected void removeAllBundleResources(String bundleName) { - unloadResourceBundle(bundleName); - resources.remove(bundleName); - // allBundles.remove(bundleName); - listeners.remove(bundleName); - } + res.add(resource); + resources.put(bundleName, res); + allBundles.put(bundleName, new HashSet<IResource>(res)); + bundleNames.put(bundleName, getResourceBundleName(resource)); - public void unloadResourceBundle(String name) { - RBManager instance = RBManager.getInstance(project); - instance.deleteMessagesBundleGroup(name); - } + // Fire resource changed event + ResourceBundleChangedEvent event = new ResourceBundleChangedEvent( + ResourceBundleChangedEvent.ADDED, bundleName, + resource.getProject()); + this.fireResourceBundleChangedEvent(bundleName, event); + } - public IMessagesBundleGroup getResourceBundle(String name) { - RBManager instance = RBManager.getInstance(project); - return instance.getMessagesBundleGroup(name); - } + protected void removeAllBundleResources(String bundleName) { + unloadResourceBundle(bundleName); + resources.remove(bundleName); + // allBundles.remove(bundleName); + listeners.remove(bundleName); + } - public Collection<IResource> getResourceBundles(String bundleName) { - return resources.get(bundleName); - } + public void unloadResourceBundle(String name) { + RBManager instance = RBManager.getInstance(project); + instance.deleteMessagesBundleGroup(name); + } - public List<String> getResourceBundleNames() { - List<String> returnList = new ArrayList<String>(); + public IMessagesBundleGroup getResourceBundle(String name) { + RBManager instance = RBManager.getInstance(project); + return instance.getMessagesBundleGroup(name); + } - Iterator<String> it = resources.keySet().iterator(); - while (it.hasNext()) { - returnList.add(it.next()); - } - return returnList; - } + public Collection<IResource> getResourceBundles(String bundleName) { + return resources.get(bundleName); + } - public IResource getResourceFile(String file) { - String regex = "^(.*?)" + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" - + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." + "properties" + ")$"; - String bundleName = file.replaceFirst(regex, "$1"); - IResource resource = null; + public List<String> getResourceBundleNames() { + List<String> returnList = new ArrayList<String>(); - for (IResource res : resources.get(bundleName)) { - if (res.getName().equalsIgnoreCase(file)) { - resource = res; - break; - } - } + Iterator<String> it = resources.keySet().iterator(); + while (it.hasNext()) { + returnList.add(it.next()); + } + return returnList; + } + + public IResource getResourceFile(String file) { + String regex = "^(.*?)" + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" + + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." + "properties" + ")$"; + String bundleName = file.replaceFirst(regex, "$1"); + IResource resource = null; - return resource; + for (IResource res : resources.get(bundleName)) { + if (res.getName().equalsIgnoreCase(file)) { + resource = res; + break; + } } - public void fireResourceBundleChangedEvent(String bundleName, - ResourceBundleChangedEvent event) { - List<IResourceBundleChangedListener> l = listeners.get(bundleName); + return resource; + } - if (l == null) { - return; - } + public void fireResourceBundleChangedEvent(String bundleName, + ResourceBundleChangedEvent event) { + List<IResourceBundleChangedListener> l = listeners.get(bundleName); - for (IResourceBundleChangedListener listener : l) { - listener.resourceBundleChanged(event); - } + if (l == null) { + return; } - public void registerResourceBundleChangeListener(String bundleName, - IResourceBundleChangedListener listener) { - List<IResourceBundleChangedListener> l = listeners.get(bundleName); - if (l == null) { - l = new ArrayList<IResourceBundleChangedListener>(); - } - l.add(listener); - listeners.put(bundleName, l); + for (IResourceBundleChangedListener listener : l) { + listener.resourceBundleChanged(event); } + } - public void unregisterResourceBundleChangeListener(String bundleName, - IResourceBundleChangedListener listener) { - List<IResourceBundleChangedListener> l = listeners.get(bundleName); - if (l == null) { - return; - } - l.remove(listener); - listeners.put(bundleName, l); + public void registerResourceBundleChangeListener(String bundleName, + IResourceBundleChangedListener listener) { + List<IResourceBundleChangedListener> l = listeners.get(bundleName); + if (l == null) { + l = new ArrayList<IResourceBundleChangedListener>(); } + l.add(listener); + listeners.put(bundleName, l); + } - protected void detectResourceBundles() { - try { - project.accept(new ResourceBundleDetectionVisitor(getProject())); - - IProject[] fragments = FragmentProjectUtils.lookupFragment(project); - if (fragments != null) { - for (IProject p : fragments) { - p.accept(new ResourceBundleDetectionVisitor(getProject())); - } - } - } catch (CoreException e) { - } + public void unregisterResourceBundleChangeListener(String bundleName, + IResourceBundleChangedListener listener) { + List<IResourceBundleChangedListener> l = listeners.get(bundleName); + if (l == null) { + return; } + l.remove(listener); + listeners.put(bundleName, l); + } + + protected void detectResourceBundles() { + try { + project.accept(new ResourceBundleDetectionVisitor(getProject())); - public IProject getProject() { - return project; + IProject[] fragments = FragmentProjectUtils.lookupFragment(project); + if (fragments != null) { + for (IProject p : fragments) { + p.accept(new ResourceBundleDetectionVisitor(getProject())); + } + } + } catch (CoreException e) { } + } - public List<String> getResourceBundleIdentifiers() { - List<String> returnList = new ArrayList<String>(); + public IProject getProject() { + return project; + } - // TODO check other resource bundles that are available on the curren - // class path - Iterator<String> it = this.resources.keySet().iterator(); - while (it.hasNext()) { - returnList.add(it.next()); - } + public List<String> getResourceBundleIdentifiers() { + List<String> returnList = new ArrayList<String>(); - return returnList; + // TODO check other resource bundles that are available on the curren + // class path + Iterator<String> it = this.resources.keySet().iterator(); + while (it.hasNext()) { + returnList.add(it.next()); } - public static List<String> getAllResourceBundleNames() { - List<String> returnList = new ArrayList<String>(); + return returnList; + } - for (IProject p : getAllSupportedProjects()) { - if (!FragmentProjectUtils.isFragment(p)) { - Iterator<String> it = getManager(p).resources.keySet() - .iterator(); - while (it.hasNext()) { - returnList.add(p.getName() + "/" + it.next()); - } - } - } - return returnList; - } - - public static Set<IProject> getAllSupportedProjects() { - IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() - .getProjects(); - Set<IProject> projs = new HashSet<IProject>(); - - for (IProject p : projects) { - try { - if (p.isOpen() && p.hasNature(NATURE_ID)) { - projs.add(p); - } - } catch (CoreException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + public static List<String> getAllResourceBundleNames() { + List<String> returnList = new ArrayList<String>(); + + for (IProject p : getAllSupportedProjects()) { + if (!FragmentProjectUtils.isFragment(p)) { + Iterator<String> it = getManager(p).resources.keySet() + .iterator(); + while (it.hasNext()) { + returnList.add(p.getName() + "/" + it.next()); } - return projs; + } } + return returnList; + } - public String getKeyHoverString(String rbName, String key) { - try { - RBManager instance = RBManager.getInstance(project); - IMessagesBundleGroup bundleGroup = instance - .getMessagesBundleGroup(rbName); - if (!bundleGroup.containsKey(key)) { - return null; - } - - String hoverText = "<html><head></head><body>"; - - for (IMessage message : bundleGroup.getMessages(key)) { - String displayName = message.getLocale() == null ? "Default" - : message.getLocale().getDisplayName(); - String value = message.getValue(); - hoverText += "<b><i>" + displayName + "</i></b><br/>" - + value.replace("\n", "<br/>") + "<br/><br/>"; - } - return hoverText + "</body></html>"; - } catch (Exception e) { - // silent catch - return ""; + public static Set<IProject> getAllSupportedProjects() { + IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() + .getProjects(); + Set<IProject> projs = new HashSet<IProject>(); + + for (IProject p : projects) { + try { + if (p.isOpen() && p.hasNature(NATURE_ID)) { + projs.add(p); } + } catch (CoreException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } + return projs; + } - public boolean isKeyBroken(String rbName, String key) { - IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance( - project).getMessagesBundleGroup(rbName); - if (messagesBundleGroup == null) { - return true; + public String getKeyHoverString(String rbName, String key) { + try { + RBManager instance = RBManager.getInstance(project); + IMessagesBundleGroup bundleGroup = instance + .getMessagesBundleGroup(rbName); + if (!bundleGroup.containsKey(key)) { + return null; + } + + String hoverText = "<html><head></head><body>"; + + for (IMessage message : bundleGroup.getMessages(key)) { + String displayName = message.getLocale() == null ? "Default" + : message.getLocale().getDisplayName(); + String value = message.getValue(); + hoverText += "<b><i>" + displayName + "</i></b><br/>" + + value.replace("\n", "<br/>") + "<br/><br/>"; + } + return hoverText + "</body></html>"; + } catch (Exception e) { + // silent catch + return ""; + } + } + + public boolean isKeyBroken(String rbName, String key) { + IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance( + project).getMessagesBundleGroup(rbName); + if (messagesBundleGroup == null) { + return true; + } else { + return !messagesBundleGroup.containsKey(key); + } + + // if (!resourceBundles.containsKey(rbName)) + // return true; + // return !this.isResourceExisting(rbName, key); + } + + protected void excludeSingleResource(IResource res) { + IResourceDescriptor rd = new ResourceDescriptor(res); + org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils + .deleteAuditMarkersForResource(res); + + // exclude resource + excludedResources.add(rd); + Collection<Object> changedExclusoins = new HashSet<Object>(); + changedExclusoins.add(res); + fireResourceExclusionEvent(new ResourceExclusionEvent(changedExclusoins)); + + // Check if the excluded resource represents a resource-bundle + if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils + .isResourceBundleFile(res)) { + String bundleName = getResourceBundleId(res); + Set<IResource> resSet = resources.remove(bundleName); + if (resSet != null) { + resSet.remove(res); + + if (!resSet.isEmpty()) { + resources.put(bundleName, resSet); + unloadResource(bundleName, res); + } else { + rd.setBundleId(bundleName); + unloadResourceBundle(bundleName); + try { + res.getProject().build( + IncrementalProjectBuilder.FULL_BUILD, + BUILDER_ID, null, null); + } catch (CoreException e) { + Logger.logError(e); + } + } + + fireResourceBundleChangedEvent(getResourceBundleId(res), + new ResourceBundleChangedEvent( + ResourceBundleChangedEvent.EXCLUDED, + bundleName, res.getProject())); + } + } + } + + public void excludeResource(IResource res, IProgressMonitor monitor) { + try { + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + + final List<IResource> resourceSubTree = new ArrayList<IResource>(); + res.accept(new IResourceVisitor() { + + @Override + public boolean visit(IResource resource) throws CoreException { + Logger.logInfo("Excluding resource '" + + resource.getFullPath().toOSString() + "'"); + resourceSubTree.add(resource); + return true; + } + + }); + + // Iterate previously retrieved resource and exclude them from + // Internationalization + monitor.beginTask( + "Exclude resources from Internationalization context", + resourceSubTree.size()); + try { + for (IResource resource : resourceSubTree) { + excludeSingleResource(resource); + org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils + .deleteAuditMarkersForResource(resource); + monitor.worked(1); + } + } catch (Exception e) { + Logger.logError(e); + } finally { + monitor.done(); + } + } catch (CoreException e) { + Logger.logError(e); + } + } + + public void includeResource(IResource res, IProgressMonitor monitor) { + if (monitor == null) { + monitor = new NullProgressMonitor(); + } + + final Collection<Object> changedResources = new HashSet<Object>(); + IResource resource = res; + + if (!excludedResources.contains(new ResourceDescriptor(res))) { + while (!(resource instanceof IProject || resource instanceof IWorkspaceRoot)) { + if (excludedResources + .contains(new ResourceDescriptor(resource))) { + excludeResource(resource, monitor); + changedResources.add(resource); + break; } else { - return !messagesBundleGroup.containsKey(key); + resource = resource.getParent(); } - - // if (!resourceBundles.containsKey(rbName)) - // return true; - // return !this.isResourceExisting(rbName, key); + } } - protected void excludeSingleResource(IResource res) { - IResourceDescriptor rd = new ResourceDescriptor(res); - org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils - .deleteAuditMarkersForResource(res); - - // exclude resource - excludedResources.add(rd); - Collection<Object> changedExclusoins = new HashSet<Object>(); - changedExclusoins.add(res); - fireResourceExclusionEvent(new ResourceExclusionEvent(changedExclusoins)); + try { + res.accept(new IResourceVisitor() { - // Check if the excluded resource represents a resource-bundle - if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils - .isResourceBundleFile(res)) { - String bundleName = getResourceBundleId(res); - Set<IResource> resSet = resources.remove(bundleName); - if (resSet != null) { - resSet.remove(res); - - if (!resSet.isEmpty()) { - resources.put(bundleName, resSet); - unloadResource(bundleName, res); - } else { - rd.setBundleId(bundleName); - unloadResourceBundle(bundleName); - try { - res.getProject().build( - IncrementalProjectBuilder.FULL_BUILD, - BUILDER_ID, null, null); - } catch (CoreException e) { - Logger.logError(e); - } - } - - fireResourceBundleChangedEvent(getResourceBundleId(res), - new ResourceBundleChangedEvent( - ResourceBundleChangedEvent.EXCLUDED, - bundleName, res.getProject())); - } + @Override + public boolean visit(IResource resource) throws CoreException { + changedResources.add(resource); + return true; } - } + }); - public void excludeResource(IResource res, IProgressMonitor monitor) { - try { - if (monitor == null) { - monitor = new NullProgressMonitor(); - } - - final List<IResource> resourceSubTree = new ArrayList<IResource>(); - res.accept(new IResourceVisitor() { - - @Override - public boolean visit(IResource resource) throws CoreException { - Logger.logInfo("Excluding resource '" - + resource.getFullPath().toOSString() + "'"); - resourceSubTree.add(resource); - return true; - } - - }); - - // Iterate previously retrieved resource and exclude them from - // Internationalization - monitor.beginTask( - "Exclude resources from Internationalization context", - resourceSubTree.size()); - try { - for (IResource resource : resourceSubTree) { - excludeSingleResource(resource); - org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils - .deleteAuditMarkersForResource(resource); - monitor.worked(1); - } - } catch (Exception e) { - Logger.logError(e); - } finally { - monitor.done(); - } - } catch (CoreException e) { - Logger.logError(e); + monitor.beginTask("Add resources to Internationalization context", + changedResources.size()); + try { + for (Object r : changedResources) { + excludedResources.remove(new ResourceDescriptor( + (IResource) r)); + monitor.worked(1); } + + } catch (Exception e) { + Logger.logError(e); + } finally { + monitor.done(); + } + } catch (Exception e) { + Logger.logError(e); } - public void includeResource(IResource res, IProgressMonitor monitor) { - if (monitor == null) { - monitor = new NullProgressMonitor(); - } + try { + res.touch(null); + } catch (CoreException e) { + Logger.logError(e); + } - final Collection<Object> changedResources = new HashSet<Object>(); - IResource resource = res; - - if (!excludedResources.contains(new ResourceDescriptor(res))) { - while (!(resource instanceof IProject || resource instanceof IWorkspaceRoot)) { - if (excludedResources - .contains(new ResourceDescriptor(resource))) { - excludeResource(resource, monitor); - changedResources.add(resource); - break; - } else { - resource = resource.getParent(); - } - } - } + // Check if the included resource represents a resource-bundle + if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils + .isResourceBundleFile(res)) { + String bundleName = getResourceBundleId(res); + boolean newRB = resources.containsKey(bundleName); - try { - res.accept(new IResourceVisitor() { - - @Override - public boolean visit(IResource resource) throws CoreException { - changedResources.add(resource); - return true; - } - }); - - monitor.beginTask("Add resources to Internationalization context", - changedResources.size()); - try { - for (Object r : changedResources) { - excludedResources.remove(new ResourceDescriptor( - (IResource) r)); - monitor.worked(1); - } - - } catch (Exception e) { - Logger.logError(e); - } finally { - monitor.done(); - } - } catch (Exception e) { - Logger.logError(e); - } + this.addBundleResource(res); + this.unloadResourceBundle(bundleName); + // this.loadResourceBundle(bundleName); + if (newRB) { try { - res.touch(null); + resource.getProject().build( + IncrementalProjectBuilder.FULL_BUILD, BUILDER_ID, + null, null); } catch (CoreException e) { - Logger.logError(e); + Logger.logError(e); } + } + fireResourceBundleChangedEvent(getResourceBundleId(res), + new ResourceBundleChangedEvent( + ResourceBundleChangedEvent.INCLUDED, bundleName, + res.getProject())); + } - // Check if the included resource represents a resource-bundle - if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils - .isResourceBundleFile(res)) { - String bundleName = getResourceBundleId(res); - boolean newRB = resources.containsKey(bundleName); - - this.addBundleResource(res); - this.unloadResourceBundle(bundleName); - // this.loadResourceBundle(bundleName); - - if (newRB) { - try { - resource.getProject().build( - IncrementalProjectBuilder.FULL_BUILD, BUILDER_ID, - null, null); - } catch (CoreException e) { - Logger.logError(e); - } - } - fireResourceBundleChangedEvent(getResourceBundleId(res), - new ResourceBundleChangedEvent( - ResourceBundleChangedEvent.INCLUDED, bundleName, - res.getProject())); - } + fireResourceExclusionEvent(new ResourceExclusionEvent(changedResources)); + } - fireResourceExclusionEvent(new ResourceExclusionEvent(changedResources)); + protected void fireResourceExclusionEvent(ResourceExclusionEvent event) { + for (IResourceExclusionListener listener : exclusionListeners) { + listener.exclusionChanged(event); } + } - protected void fireResourceExclusionEvent(ResourceExclusionEvent event) { - for (IResourceExclusionListener listener : exclusionListeners) { - listener.exclusionChanged(event); - } - } + public static boolean isResourceExcluded(IResource res) { + IResource resource = res; - public static boolean isResourceExcluded(IResource res) { - IResource resource = res; + if (!state_loaded) { + stateLoader.loadState(); + } - if (!state_loaded) { - stateLoader.loadState(); - } + boolean isExcluded = false; - boolean isExcluded = false; - - do { - if (excludedResources.contains(new ResourceDescriptor(resource))) { - if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils - .isResourceBundleFile(resource)) { - Set<IResource> resources = allBundles - .remove(getResourceBundleName(resource)); - if (resources == null) { - resources = new HashSet<IResource>(); - } - resources.add(resource); - allBundles.put(getResourceBundleName(resource), resources); - } - - isExcluded = true; - break; - } - resource = resource.getParent(); - } while (resource != null - && !(resource instanceof IProject || resource instanceof IWorkspaceRoot) - && checkResourceExclusionRoot); - - return isExcluded; // excludedResources.contains(new - // ResourceDescriptor(res)); - } - - public IFile getRandomFile(String bundleName) { - try { - Collection<IMessagesBundle> messagesBundles = RBManager - .getInstance(project).getMessagesBundleGroup(bundleName) - .getMessagesBundles(); - IMessagesBundle bundle = messagesBundles.iterator().next(); - return FileUtils.getFile(bundle); - } catch (Exception e) { - e.printStackTrace(); + do { + if (excludedResources.contains(new ResourceDescriptor(resource))) { + if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils + .isResourceBundleFile(resource)) { + Set<IResource> resources = allBundles + .remove(getResourceBundleName(resource)); + if (resources == null) { + resources = new HashSet<IResource>(); + } + resources.add(resource); + allBundles.put(getResourceBundleName(resource), resources); + } + + isExcluded = true; + break; + } + resource = resource.getParent(); + } while (resource != null + && !(resource instanceof IProject || resource instanceof IWorkspaceRoot) + && checkResourceExclusionRoot); + + return isExcluded; // excludedResources.contains(new + // ResourceDescriptor(res)); + } + + public IFile getRandomFile(String bundleName) { + try { + Collection<IMessagesBundle> messagesBundles = RBManager + .getInstance(project).getMessagesBundleGroup(bundleName) + .getMessagesBundles(); + IMessagesBundle bundle = messagesBundles.iterator().next(); + return FileUtils.getFile(bundle); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + @Deprecated + protected static boolean isResourceExcluded(IProject project, String bname) { + Iterator<IResourceDescriptor> itExcl = excludedResources.iterator(); + while (itExcl.hasNext()) { + IResourceDescriptor rd = itExcl.next(); + if (project.getName().equals(rd.getProjectName()) + && bname.equals(rd.getBundleId())) { + return true; + } + } + return false; + } + + public static ResourceBundleManager getManager(String projectName) { + for (IProject p : getAllSupportedProjects()) { + if (p.getName().equalsIgnoreCase(projectName)) { + // check if the projectName is a fragment and return the manager + // for the host + if (FragmentProjectUtils.isFragment(p)) { + return getManager(FragmentProjectUtils.getFragmentHost(p)); + } else { + return getManager(p); } - return null; + } } + return null; + } - @Deprecated - protected static boolean isResourceExcluded(IProject project, String bname) { - Iterator<IResourceDescriptor> itExcl = excludedResources.iterator(); - while (itExcl.hasNext()) { - IResourceDescriptor rd = itExcl.next(); - if (project.getName().equals(rd.getProjectName()) - && bname.equals(rd.getBundleId())) { - return true; - } - } - return false; - } - - public static ResourceBundleManager getManager(String projectName) { - for (IProject p : getAllSupportedProjects()) { - if (p.getName().equalsIgnoreCase(projectName)) { - // check if the projectName is a fragment and return the manager - // for the host - if (FragmentProjectUtils.isFragment(p)) { - return getManager(FragmentProjectUtils.getFragmentHost(p)); - } else { - return getManager(p); - } - } - } - return null; - } + public IFile getResourceBundleFile(String resourceBundle, Locale l) { + IFile res = null; + Set<IResource> resSet = resources.get(resourceBundle); - public IFile getResourceBundleFile(String resourceBundle, Locale l) { - IFile res = null; - Set<IResource> resSet = resources.get(resourceBundle); - - if (resSet != null) { - for (IResource resource : resSet) { - Locale refLoc = NameUtils.getLocaleByName(resourceBundle, - resource.getName()); - if (refLoc == null - && l == null - || (refLoc != null && refLoc.equals(l) || l != null - && l.equals(refLoc))) { - res = resource.getProject().getFile( - resource.getProjectRelativePath()); - break; - } - } + if (resSet != null) { + for (IResource resource : resSet) { + Locale refLoc = NameUtils.getLocaleByName(resourceBundle, + resource.getName()); + if (refLoc == null + && l == null + || (refLoc != null && refLoc.equals(l) || l != null + && l.equals(refLoc))) { + res = resource.getProject().getFile( + resource.getProjectRelativePath()); + break; } - - return res; + } } - public Set<IResource> getAllResourceBundleResources(String resourceBundle) { - return allBundles.get(resourceBundle); - } + return res; + } - public void registerResourceExclusionListener( - IResourceExclusionListener listener) { - exclusionListeners.add(listener); - } + public Set<IResource> getAllResourceBundleResources(String resourceBundle) { + return allBundles.get(resourceBundle); + } - public void unregisterResourceExclusionListener( - IResourceExclusionListener listener) { - exclusionListeners.remove(listener); - } + public void registerResourceExclusionListener( + IResourceExclusionListener listener) { + exclusionListeners.add(listener); + } - public boolean isResourceExclusionListenerRegistered( - IResourceExclusionListener listener) { - return exclusionListeners.contains(listener); - } + public void unregisterResourceExclusionListener( + IResourceExclusionListener listener) { + exclusionListeners.remove(listener); + } - public static void unregisterResourceExclusionListenerFromAllManagers( - IResourceExclusionListener excludedResource) { - for (ResourceBundleManager mgr : rbmanager.values()) { - mgr.unregisterResourceExclusionListener(excludedResource); - } + public boolean isResourceExclusionListenerRegistered( + IResourceExclusionListener listener) { + return exclusionListeners.contains(listener); + } + + public static void unregisterResourceExclusionListenerFromAllManagers( + IResourceExclusionListener excludedResource) { + for (ResourceBundleManager mgr : rbmanager.values()) { + mgr.unregisterResourceExclusionListener(excludedResource); } + } - public void addResourceBundleEntry(String resourceBundleId, String key, - Locale locale, String message) throws ResourceBundleException { + public void addResourceBundleEntry(String resourceBundleId, String key, + Locale locale, String message) throws ResourceBundleException { - RBManager instance = RBManager.getInstance(project); - IMessagesBundleGroup bundleGroup = instance - .getMessagesBundleGroup(resourceBundleId); - IMessage entry = bundleGroup.getMessage(key, locale); + RBManager instance = RBManager.getInstance(project); + IMessagesBundleGroup bundleGroup = instance + .getMessagesBundleGroup(resourceBundleId); + IMessage entry = bundleGroup.getMessage(key, locale); - if (entry == null) { - DirtyHack.setFireEnabled(false); + if (entry == null) { + DirtyHack.setFireEnabled(false); - IMessagesBundle messagesBundle = bundleGroup - .getMessagesBundle(locale); - IMessage m = MessageFactory.createMessage(key, locale); - m.setText(message); - messagesBundle.addMessage(m); + IMessagesBundle messagesBundle = bundleGroup + .getMessagesBundle(locale); + IMessage m = MessageFactory.createMessage(key, locale); + m.setText(message); + messagesBundle.addMessage(m); - FileUtils.writeToFile(messagesBundle); - instance.fireResourceChanged(messagesBundle); + FileUtils.writeToFile(messagesBundle); + instance.fireResourceChanged(messagesBundle); - DirtyHack.setFireEnabled(true); + DirtyHack.setFireEnabled(true); - // notify the PropertyKeySelectionTree - instance.fireEditorChanged(); - } + // notify the PropertyKeySelectionTree + instance.fireEditorChanged(); } + } - public void saveResourceBundle(String resourceBundleId, - IMessagesBundleGroup newBundleGroup) throws ResourceBundleException { + public void saveResourceBundle(String resourceBundleId, + IMessagesBundleGroup newBundleGroup) throws ResourceBundleException { - // RBManager.getInstance(). - } - - public void removeResourceBundleEntry(String resourceBundleId, - List<String> keys) throws ResourceBundleException { + // RBManager.getInstance(). + } - RBManager instance = RBManager.getInstance(project); - IMessagesBundleGroup messagesBundleGroup = instance - .getMessagesBundleGroup(resourceBundleId); + public void removeResourceBundleEntry(String resourceBundleId, + List<String> keys) throws ResourceBundleException { - DirtyHack.setFireEnabled(false); + RBManager instance = RBManager.getInstance(project); + IMessagesBundleGroup messagesBundleGroup = instance + .getMessagesBundleGroup(resourceBundleId); - for (String key : keys) { - messagesBundleGroup.removeMessages(key); - } + DirtyHack.setFireEnabled(false); - instance.writeToFile(messagesBundleGroup); + for (String key : keys) { + messagesBundleGroup.removeMessages(key); + } - DirtyHack.setFireEnabled(true); + instance.writeToFile(messagesBundleGroup); - // notify the PropertyKeySelectionTree - instance.fireEditorChanged(); - } + DirtyHack.setFireEnabled(true); - public boolean isResourceExisting(String bundleId, String key) { - boolean keyExists = false; - IMessagesBundleGroup bGroup = getResourceBundle(bundleId); + // notify the PropertyKeySelectionTree + instance.fireEditorChanged(); + } - if (bGroup != null) { - keyExists = bGroup.isKey(key); - } + public boolean isResourceExisting(String bundleId, String key) { + boolean keyExists = false; + IMessagesBundleGroup bGroup = getResourceBundle(bundleId); - return keyExists; + if (bGroup != null) { + keyExists = bGroup.isKey(key); } - public static void rebuildProject(IResource resource) { - try { - resource.touch(null); - } catch (CoreException e) { - Logger.logError(e); - } + return keyExists; + } + + public static void rebuildProject(IResource resource) { + try { + resource.touch(null); + } catch (CoreException e) { + Logger.logError(e); } + } + + public Set<Locale> getProjectProvidedLocales() { + Set<Locale> locales = new HashSet<Locale>(); - public Set<Locale> getProjectProvidedLocales() { - Set<Locale> locales = new HashSet<Locale>(); - - for (String bundleId : getResourceBundleNames()) { - Set<Locale> rb_l = getProvidedLocales(bundleId); - if (!rb_l.isEmpty()) { - Object[] bundlelocales = rb_l.toArray(); - for (Object l : bundlelocales) { - /* TODO check if useful to add the default */ - if (!locales.contains(l)) { - locales.add((Locale) l); - } - } - } + for (String bundleId : getResourceBundleNames()) { + Set<Locale> rb_l = getProvidedLocales(bundleId); + if (!rb_l.isEmpty()) { + Object[] bundlelocales = rb_l.toArray(); + for (Object l : bundlelocales) { + /* TODO check if useful to add the default */ + if (!locales.contains(l)) { + locales.add((Locale) l); + } } - return locales; + } } + return locales; + } - private static IStateLoader getStateLoader() { + private static IStateLoader getStateLoader() { - IExtensionPoint extp = Platform.getExtensionRegistry() - .getExtensionPoint( - "org.eclipse.babel.tapiji.tools.core" + ".stateLoader"); - IConfigurationElement[] elements = extp.getConfigurationElements(); + IExtensionPoint extp = Platform.getExtensionRegistry() + .getExtensionPoint( + "org.eclipse.babel.tapiji.tools.core" + ".stateLoader"); + IConfigurationElement[] elements = extp.getConfigurationElements(); - if (elements.length != 0) { - try { - return (IStateLoader) elements[0] - .createExecutableExtension("class"); - } catch (CoreException e) { - e.printStackTrace(); - } - } - return null; + if (elements.length != 0) { + try { + return (IStateLoader) elements[0] + .createExecutableExtension("class"); + } catch (CoreException e) { + e.printStackTrace(); + } } + return null; + } - public static void saveManagerState() { - stateLoader.saveState(); - } + public static void saveManagerState() { + stateLoader.saveState(); + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/RBAuditor.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/RBAuditor.java index bf244de6..0cd1afcd 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/RBAuditor.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/RBAuditor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -23,42 +23,42 @@ public class RBAuditor extends I18nResourceAuditor { - @Override - public void audit(IResource resource) { - if (RBFileUtils.isResourceBundleFile(resource)) { - ResourceBundleManager.getManager(resource.getProject()) - .addBundleResource(resource); - } + @Override + public void audit(IResource resource) { + if (RBFileUtils.isResourceBundleFile(resource)) { + ResourceBundleManager.getManager(resource.getProject()) + .addBundleResource(resource); } + } - @Override - public String[] getFileEndings() { - return new String[] { "properties" }; - } + @Override + public String[] getFileEndings() { + return new String[] { "properties" }; + } - @Override - public List<ILocation> getConstantStringLiterals() { - return new ArrayList<ILocation>(); - } + @Override + public List<ILocation> getConstantStringLiterals() { + return new ArrayList<ILocation>(); + } - @Override - public List<ILocation> getBrokenResourceReferences() { - return new ArrayList<ILocation>(); - } + @Override + public List<ILocation> getBrokenResourceReferences() { + return new ArrayList<ILocation>(); + } - @Override - public List<ILocation> getBrokenBundleReferences() { - return new ArrayList<ILocation>(); - } + @Override + public List<ILocation> getBrokenBundleReferences() { + return new ArrayList<ILocation>(); + } - @Override - public String getContextId() { - return "resource_bundle"; - } + @Override + public String getContextId() { + return "resource_bundle"; + } - @Override - public List<IMarkerResolution> getMarkerResolutions(IMarker marker) { - return null; - } + @Override + public List<IMarkerResolution> getMarkerResolutions(IMarker marker) { + return null; + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceBundleDetectionVisitor.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceBundleDetectionVisitor.java index 4e36b65d..66fe8b55 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceBundleDetectionVisitor.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceBundleDetectionVisitor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -21,43 +21,43 @@ import org.eclipse.core.runtime.CoreException; public class ResourceBundleDetectionVisitor implements IResourceVisitor, - IResourceDeltaVisitor { - - private IProject project = null; - - public ResourceBundleDetectionVisitor(IProject project) { - this.project = project; - } - - @Override - public boolean visit(IResource resource) throws CoreException { - try { - if (RBFileUtils.isResourceBundleFile(resource)) { - Logger.logInfo("Loading Resource-Bundle file '" - + resource.getName() + "'"); - if (!ResourceBundleManager.isResourceExcluded(resource)) { - ResourceBundleManager.getManager(project) - .addBundleResource(resource); - } - return false; - } else { - return true; - } - } catch (Exception e) { - return false; + IResourceDeltaVisitor { + + private IProject project = null; + + public ResourceBundleDetectionVisitor(IProject project) { + this.project = project; + } + + @Override + public boolean visit(IResource resource) throws CoreException { + try { + if (RBFileUtils.isResourceBundleFile(resource)) { + Logger.logInfo("Loading Resource-Bundle file '" + + resource.getName() + "'"); + if (!ResourceBundleManager.isResourceExcluded(resource)) { + ResourceBundleManager.getManager(project) + .addBundleResource(resource); } + return false; + } else { + return true; + } + } catch (Exception e) { + return false; } + } - @Override - public boolean visit(IResourceDelta delta) throws CoreException { - IResource resource = delta.getResource(); + @Override + public boolean visit(IResourceDelta delta) throws CoreException { + IResource resource = delta.getResource(); - if (RBFileUtils.isResourceBundleFile(resource)) { - // ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta); - return false; - } - - return true; + if (RBFileUtils.isResourceBundleFile(resource)) { + // ResourceBundleManager.getManager(resource.getProject()).bundleResourceModified(delta); + return false; } + return true; + } + } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceFinder.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceFinder.java index 49a5f92b..61fe27ba 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceFinder.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/analyzer/ResourceFinder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -24,33 +24,33 @@ public class ResourceFinder implements IResourceVisitor, IResourceDeltaVisitor { - List<IResource> javaResources = null; - Set<String> supportedExtensions = null; - - public ResourceFinder(Set<String> ext) { - javaResources = new ArrayList<IResource>(); - supportedExtensions = ext; - } - - @Override - public boolean visit(IResource resource) throws CoreException { - if (I18nBuilder.isResourceAuditable(resource, supportedExtensions)) { - Logger.logInfo("Audit necessary for resource '" - + resource.getFullPath().toOSString() + "'"); - javaResources.add(resource); - return false; - } else - return true; - } - - public List<IResource> getResources() { - return javaResources; - } - - @Override - public boolean visit(IResourceDelta delta) throws CoreException { - visit(delta.getResource()); - return true; - } + List<IResource> javaResources = null; + Set<String> supportedExtensions = null; + + public ResourceFinder(Set<String> ext) { + javaResources = new ArrayList<IResource>(); + supportedExtensions = ext; + } + + @Override + public boolean visit(IResource resource) throws CoreException { + if (I18nBuilder.isResourceAuditable(resource, supportedExtensions)) { + Logger.logInfo("Audit necessary for resource '" + + resource.getFullPath().toOSString() + "'"); + javaResources.add(resource); + return false; + } else + return true; + } + + public List<IResource> getResources() { + return javaResources; + } + + @Override + public boolean visit(IResourceDelta delta) throws CoreException { + visit(delta.getResource()); + return true; + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/BuilderPropertyChangeListener.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/BuilderPropertyChangeListener.java index 75da3d54..3f3c7c19 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/BuilderPropertyChangeListener.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/BuilderPropertyChangeListener.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -31,104 +31,104 @@ public class BuilderPropertyChangeListener implements IPropertyChangeListener { - @Override - public void propertyChange(PropertyChangeEvent event) { - if (event.getNewValue().equals(true) && isTapiJIPropertyp(event)) - rebuild(); + @Override + public void propertyChange(PropertyChangeEvent event) { + if (event.getNewValue().equals(true) && isTapiJIPropertyp(event)) + rebuild(); - if (event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN)) - rebuild(); - - if (event.getNewValue().equals(false)) { - if (event.getProperty().equals(TapiJIPreferences.AUDIT_RESOURCE)) { - deleteMarkersByCause(EditorUtils.MARKER_ID, -1); - } - if (event.getProperty().equals(TapiJIPreferences.AUDIT_RB)) { - deleteMarkersByCause(EditorUtils.RB_MARKER_ID, -1); - } - if (event.getProperty().equals( - TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)) { - deleteMarkersByCause(EditorUtils.RB_MARKER_ID, - IMarkerConstants.CAUSE_UNSPEZIFIED_KEY); - } - if (event.getProperty().equals(TapiJIPreferences.AUDIT_SAME_VALUE)) { - deleteMarkersByCause(EditorUtils.RB_MARKER_ID, - IMarkerConstants.CAUSE_SAME_VALUE); - } - if (event.getProperty().equals( - TapiJIPreferences.AUDIT_MISSING_LANGUAGE)) { - deleteMarkersByCause(EditorUtils.RB_MARKER_ID, - IMarkerConstants.CAUSE_MISSING_LANGUAGE); - } - } + if (event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN)) + rebuild(); + if (event.getNewValue().equals(false)) { + if (event.getProperty().equals(TapiJIPreferences.AUDIT_RESOURCE)) { + deleteMarkersByCause(EditorUtils.MARKER_ID, -1); + } + if (event.getProperty().equals(TapiJIPreferences.AUDIT_RB)) { + deleteMarkersByCause(EditorUtils.RB_MARKER_ID, -1); + } + if (event.getProperty().equals( + TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)) { + deleteMarkersByCause(EditorUtils.RB_MARKER_ID, + IMarkerConstants.CAUSE_UNSPEZIFIED_KEY); + } + if (event.getProperty().equals(TapiJIPreferences.AUDIT_SAME_VALUE)) { + deleteMarkersByCause(EditorUtils.RB_MARKER_ID, + IMarkerConstants.CAUSE_SAME_VALUE); + } + if (event.getProperty().equals( + TapiJIPreferences.AUDIT_MISSING_LANGUAGE)) { + deleteMarkersByCause(EditorUtils.RB_MARKER_ID, + IMarkerConstants.CAUSE_MISSING_LANGUAGE); + } } - private boolean isTapiJIPropertyp(PropertyChangeEvent event) { - if (event.getProperty().equals(TapiJIPreferences.AUDIT_RESOURCE) - || event.getProperty().equals(TapiJIPreferences.AUDIT_RB) - || event.getProperty().equals( - TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY) - || event.getProperty().equals( - TapiJIPreferences.AUDIT_SAME_VALUE) - || event.getProperty().equals( - TapiJIPreferences.AUDIT_MISSING_LANGUAGE)) - return true; - else - return false; - } + } + + private boolean isTapiJIPropertyp(PropertyChangeEvent event) { + if (event.getProperty().equals(TapiJIPreferences.AUDIT_RESOURCE) + || event.getProperty().equals(TapiJIPreferences.AUDIT_RB) + || event.getProperty().equals( + TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY) + || event.getProperty().equals( + TapiJIPreferences.AUDIT_SAME_VALUE) + || event.getProperty().equals( + TapiJIPreferences.AUDIT_MISSING_LANGUAGE)) + return true; + else + return false; + } - /* - * cause == -1 ignores the attribute 'case' - */ - private void deleteMarkersByCause(final String markertype, final int cause) { - final IWorkspace workspace = ResourcesPlugin.getWorkspace(); - BusyIndicator.showWhile(Display.getCurrent(), new Runnable() { - @Override - public void run() { - IMarker[] marker; - try { - marker = workspace.getRoot().findMarkers(markertype, true, - IResource.DEPTH_INFINITE); + /* + * cause == -1 ignores the attribute 'case' + */ + private void deleteMarkersByCause(final String markertype, final int cause) { + final IWorkspace workspace = ResourcesPlugin.getWorkspace(); + BusyIndicator.showWhile(Display.getCurrent(), new Runnable() { + @Override + public void run() { + IMarker[] marker; + try { + marker = workspace.getRoot().findMarkers(markertype, true, + IResource.DEPTH_INFINITE); - for (IMarker m : marker) { - if (m.exists()) { - if (m.getAttribute("cause", -1) == cause) - m.delete(); - if (cause == -1) - m.getResource().deleteMarkers(markertype, true, - IResource.DEPTH_INFINITE); - } - } - } catch (CoreException e) { - } + for (IMarker m : marker) { + if (m.exists()) { + if (m.getAttribute("cause", -1) == cause) + m.delete(); + if (cause == -1) + m.getResource().deleteMarkers(markertype, true, + IResource.DEPTH_INFINITE); } - }); - } + } + } catch (CoreException e) { + } + } + }); + } - private void rebuild() { - final IWorkspace workspace = ResourcesPlugin.getWorkspace(); + private void rebuild() { + final IWorkspace workspace = ResourcesPlugin.getWorkspace(); - new Job("Audit source files") { - @Override - protected IStatus run(IProgressMonitor monitor) { - try { - for (IResource res : workspace.getRoot().members()) { - final IProject p = (IProject) res; - try { - p.build(I18nBuilder.FULL_BUILD, - I18nBuilder.BUILDER_ID, null, monitor); - } catch (CoreException e) { - Logger.logError(e); - } - } - } catch (CoreException e) { - Logger.logError(e); - } - return Status.OK_STATUS; + new Job("Audit source files") { + @Override + protected IStatus run(IProgressMonitor monitor) { + try { + for (IResource res : workspace.getRoot().members()) { + final IProject p = (IProject) res; + try { + p.build(I18nBuilder.FULL_BUILD, + I18nBuilder.BUILDER_ID, null, monitor); + } catch (CoreException e) { + Logger.logError(e); } + } + } catch (CoreException e) { + Logger.logError(e); + } + return Status.OK_STATUS; + } - }.schedule(); - } + }.schedule(); + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ExtensionManager.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ExtensionManager.java index 8d9a8ab4..0b1cc8c3 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ExtensionManager.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ExtensionManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -28,53 +28,53 @@ public class ExtensionManager { - // list of registered extension plug-ins - private static List<I18nAuditor> extensions = null; + // list of registered extension plug-ins + private static List<I18nAuditor> extensions = null; - // change listener for builder property change events - private static IPropertyChangeListener propertyChangeListener = null; + // change listener for builder property change events + private static IPropertyChangeListener propertyChangeListener = null; - // file-endings supported by the registered extension plug-ins - private static Set<String> supportedFileEndings = new HashSet<String>(); + // file-endings supported by the registered extension plug-ins + private static Set<String> supportedFileEndings = new HashSet<String>(); - public static List<I18nAuditor> getRegisteredI18nAuditors() { - if (extensions == null) { - extensions = new ArrayList<I18nAuditor>(); + public static List<I18nAuditor> getRegisteredI18nAuditors() { + if (extensions == null) { + extensions = new ArrayList<I18nAuditor>(); - // init default auditors - extensions.add(new RBAuditor()); + // init default auditors + extensions.add(new RBAuditor()); - // lookup registered auditor extensions - IConfigurationElement[] config = Platform - .getExtensionRegistry() - .getConfigurationElementsFor(Activator.BUILDER_EXTENSION_ID); + // lookup registered auditor extensions + IConfigurationElement[] config = Platform + .getExtensionRegistry() + .getConfigurationElementsFor(Activator.BUILDER_EXTENSION_ID); - try { - for (IConfigurationElement e : config) { - addExtensionPlugIn((I18nAuditor) e - .createExecutableExtension("class")); - } - } catch (CoreException ex) { - Logger.logError(ex); - } + try { + for (IConfigurationElement e : config) { + addExtensionPlugIn((I18nAuditor) e + .createExecutableExtension("class")); } - - // init builder property change listener - if (propertyChangeListener == null) { - propertyChangeListener = new BuilderPropertyChangeListener(); - TapiJIPreferences.addPropertyChangeListener(propertyChangeListener); - } - - return extensions; + } catch (CoreException ex) { + Logger.logError(ex); + } } - public static Set<String> getSupportedFileEndings() { - return supportedFileEndings; + // init builder property change listener + if (propertyChangeListener == null) { + propertyChangeListener = new BuilderPropertyChangeListener(); + TapiJIPreferences.addPropertyChangeListener(propertyChangeListener); } - private static void addExtensionPlugIn(I18nAuditor extension) { - I18nAuditor a = extension; - extensions.add(a); - supportedFileEndings.addAll(Arrays.asList(a.getFileEndings())); - } + return extensions; + } + + public static Set<String> getSupportedFileEndings() { + return supportedFileEndings; + } + + private static void addExtensionPlugIn(I18nAuditor extension) { + I18nAuditor a = extension; + extensions.add(a); + supportedFileEndings.addAll(Arrays.asList(a.getFileEndings())); + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/I18nBuilder.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/I18nBuilder.java index a1adbea7..40bc2f38 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/I18nBuilder.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/I18nBuilder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -44,426 +44,423 @@ public class I18nBuilder extends IncrementalProjectBuilder { - public static final String BUILDER_ID = ResourceBundleManager.BUILDER_ID; + public static final String BUILDER_ID = ResourceBundleManager.BUILDER_ID; - // private static I18nAuditor[] resourceAuditors; - // private static Set<String> supportedFileEndings; - - public static I18nAuditor getI18nAuditorByContext(String contextId) - throws NoSuchResourceAuditorException { - for (I18nAuditor auditor : ExtensionManager.getRegisteredI18nAuditors()) { - if (auditor.getContextId().equals(contextId)) { - return auditor; - } - } - throw new NoSuchResourceAuditorException(); + public static I18nAuditor getI18nAuditorByContext(String contextId) + throws NoSuchResourceAuditorException { + for (I18nAuditor auditor : ExtensionManager.getRegisteredI18nAuditors()) { + if (auditor.getContextId().equals(contextId)) { + return auditor; + } } - - public static boolean isResourceAuditable(IResource resource, - Set<String> supportedExtensions) { - for (String ext : supportedExtensions) { - if (resource.getType() == IResource.FILE && !resource.isDerived() - && resource.getFileExtension() != null - && (resource.getFileExtension().equalsIgnoreCase(ext))) { - return true; - } - } - return false; + throw new NoSuchResourceAuditorException(); + } + + public static boolean isResourceAuditable(IResource resource, + Set<String> supportedExtensions) { + for (String ext : supportedExtensions) { + if (resource.getType() == IResource.FILE && !resource.isDerived() + && resource.getFileExtension() != null + && (resource.getFileExtension().equalsIgnoreCase(ext))) { + return true; + } } + return false; + } + + @Override + protected IProject[] build(final int kind, Map args, + IProgressMonitor monitor) throws CoreException { + + ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() { + @Override + public void run(IProgressMonitor monitor) throws CoreException { + if (kind == FULL_BUILD) { + fullBuild(monitor); + } else { + // only perform audit if the resource delta is not empty + IResourceDelta resDelta = getDelta(getProject()); + + if (resDelta == null) { + return; + } - @Override - protected IProject[] build(final int kind, Map args, - IProgressMonitor monitor) throws CoreException { - - ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() { - @Override - public void run(IProgressMonitor monitor) throws CoreException { - if (kind == FULL_BUILD) { - fullBuild(monitor); - } else { - // only perform audit if the resource delta is not empty - IResourceDelta resDelta = getDelta(getProject()); - - if (resDelta == null) { - return; - } - - if (resDelta.getAffectedChildren() == null) { - return; - } - - incrementalBuild(monitor, resDelta); - } - } - }, monitor); - - return null; - } + if (resDelta.getAffectedChildren() == null) { + return; + } - private void incrementalBuild(IProgressMonitor monitor, - IResourceDelta resDelta) throws CoreException { - try { - // inspect resource delta - ResourceFinder csrav = new ResourceFinder( - ExtensionManager.getSupportedFileEndings()); - resDelta.accept(csrav); - auditResources(csrav.getResources(), monitor, getProject()); - } catch (CoreException e) { - Logger.logError(e); + incrementalBuild(monitor, resDelta); } + } + }, monitor); + + return null; + } + + private void incrementalBuild(IProgressMonitor monitor, + IResourceDelta resDelta) throws CoreException { + try { + // inspect resource delta + ResourceFinder csrav = new ResourceFinder( + ExtensionManager.getSupportedFileEndings()); + resDelta.accept(csrav); + auditResources(csrav.getResources(), monitor, getProject()); + } catch (CoreException e) { + Logger.logError(e); } - - public void buildResource(IResource resource, IProgressMonitor monitor) { - if (isResourceAuditable(resource, - ExtensionManager.getSupportedFileEndings())) { - List<IResource> resources = new ArrayList<IResource>(); - resources.add(resource); - // TODO: create instance of progressmonitor and hand it over to - // auditResources - try { - auditResources(resources, monitor, resource.getProject()); - } catch (Exception e) { - Logger.logError(e); - } - } + } + + public void buildResource(IResource resource, IProgressMonitor monitor) { + if (isResourceAuditable(resource, + ExtensionManager.getSupportedFileEndings())) { + List<IResource> resources = new ArrayList<IResource>(); + resources.add(resource); + // TODO: create instance of progressmonitor and hand it over to + // auditResources + try { + auditResources(resources, monitor, resource.getProject()); + } catch (Exception e) { + Logger.logError(e); + } } - - public void buildProject(IProgressMonitor monitor, IProject proj) { - try { - ResourceFinder csrav = new ResourceFinder( - ExtensionManager.getSupportedFileEndings()); - proj.accept(csrav); - auditResources(csrav.getResources(), monitor, proj); - } catch (CoreException e) { - Logger.logError(e); - } + } + + public void buildProject(IProgressMonitor monitor, IProject proj) { + try { + ResourceFinder csrav = new ResourceFinder( + ExtensionManager.getSupportedFileEndings()); + proj.accept(csrav); + auditResources(csrav.getResources(), monitor, proj); + } catch (CoreException e) { + Logger.logError(e); } + } + + private void fullBuild(IProgressMonitor monitor) { + buildProject(monitor, getProject()); + } + + private void auditResources(List<IResource> resources, + IProgressMonitor monitor, IProject project) { + IConfiguration configuration = ConfigurationManager.getInstance() + .getConfiguration(); - private void fullBuild(IProgressMonitor monitor) { - buildProject(monitor, getProject()); + int work = resources.size(); + int actWork = 0; + if (monitor == null) { + monitor = new NullProgressMonitor(); } - private void auditResources(List<IResource> resources, - IProgressMonitor monitor, IProject project) { - IConfiguration configuration = ConfigurationManager.getInstance() - .getConfiguration(); + monitor.beginTask( + "Audit resource file for Internationalization problems", work); - int work = resources.size(); - int actWork = 0; - if (monitor == null) { - monitor = new NullProgressMonitor(); - } + for (IResource resource : resources) { + monitor.subTask("'" + resource.getFullPath().toOSString() + "'"); + if (monitor.isCanceled()) { + throw new OperationCanceledException(); + } - monitor.beginTask( - "Audit resource file for Internationalization problems", work); - - for (IResource resource : resources) { - monitor.subTask("'" + resource.getFullPath().toOSString() + "'"); - if (monitor.isCanceled()) { - throw new OperationCanceledException(); - } - - if (!EditorUtils.deleteAuditMarkersForResource(resource)) { - continue; - } - - if (ResourceBundleManager.isResourceExcluded(resource)) { - continue; - } - - if (!resource.exists()) { - continue; - } - - for (I18nAuditor ra : ExtensionManager.getRegisteredI18nAuditors()) { - if (ra instanceof I18nResourceAuditor - && !(configuration.getAuditResource())) { - continue; - } - if (ra instanceof I18nRBAuditor - && !(configuration.getAuditRb())) { - continue; - } - - try { - if (monitor.isCanceled()) { - monitor.done(); - break; - } - - if (ra.isResourceOfType(resource)) { - ra.audit(resource); - } - } catch (Exception e) { - Logger.logError( - "Error during auditing '" + resource.getFullPath() - + "'", e); - } - } - - if (monitor != null) { - monitor.worked(1); - } - } + if (!EditorUtils.deleteAuditMarkersForResource(resource)) { + continue; + } - for (I18nAuditor a : ExtensionManager.getRegisteredI18nAuditors()) { - if (a instanceof I18nResourceAuditor) { - handleI18NAuditorMarkers((I18nResourceAuditor) a); - } - if (a instanceof I18nRBAuditor) { - handleI18NAuditorMarkers((I18nRBAuditor) a); - ((I18nRBAuditor) a).resetProblems(); - } - } + if (ResourceBundleManager.isResourceExcluded(resource)) { + continue; + } - monitor.done(); - } + if (!resource.exists()) { + continue; + } - private void handleI18NAuditorMarkers(I18nResourceAuditor ra) { - try { - for (ILocation problem : ra.getConstantStringLiterals()) { - EditorUtils - .reportToMarker( - org.eclipse.babel.tapiji.tools.core.util.EditorUtils - .getFormattedMessage( - org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_NON_LOCALIZED_LITERAL, - new String[] { problem - .getLiteral() }), - problem, - IMarkerConstants.CAUSE_CONSTANT_LITERAL, "", - (ILocation) problem.getData(), ra - .getContextId()); - } - - // Report all broken Resource-Bundle references - for (ILocation brokenLiteral : ra.getBrokenResourceReferences()) { - EditorUtils - .reportToMarker( - org.eclipse.babel.tapiji.tools.core.util.EditorUtils - .getFormattedMessage( - org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_BROKEN_RESOURCE_REFERENCE, - new String[] { - brokenLiteral - .getLiteral(), - ((ILocation) brokenLiteral - .getData()) - .getLiteral() }), - brokenLiteral, - IMarkerConstants.CAUSE_BROKEN_REFERENCE, - brokenLiteral.getLiteral(), - (ILocation) brokenLiteral.getData(), ra - .getContextId()); - } - - // Report all broken definitions to Resource-Bundle - // references - for (ILocation brokenLiteral : ra.getBrokenBundleReferences()) { - EditorUtils - .reportToMarker( - org.eclipse.babel.tapiji.tools.core.util.EditorUtils - .getFormattedMessage( - org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE, - new String[] { brokenLiteral - .getLiteral() }), - brokenLiteral, - IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE, - brokenLiteral.getLiteral(), - (ILocation) brokenLiteral.getData(), ra - .getContextId()); - } - } catch (Exception e) { - Logger.logError( - "Exception during reporting of Internationalization errors", - e); + for (I18nAuditor ra : ExtensionManager.getRegisteredI18nAuditors()) { + if (ra instanceof I18nResourceAuditor + && !(configuration.getAuditResource())) { + continue; + } + if (ra instanceof I18nRBAuditor + && !(configuration.getAuditRb())) { + continue; } - } - private void handleI18NAuditorMarkers(I18nRBAuditor ra) { - IConfiguration configuration = ConfigurationManager.getInstance() - .getConfiguration(); try { - // Report all unspecified keys - if (configuration.getAuditMissingValue()) { - for (ILocation problem : ra.getUnspecifiedKeyReferences()) { - EditorUtils - .reportToRBMarker( - org.eclipse.babel.tapiji.tools.core.util.EditorUtils - .getFormattedMessage( - org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_UNSPECIFIED_KEYS, - new String[] { - problem.getLiteral(), - problem.getFile() - .getName() }), - problem, - IMarkerConstants.CAUSE_UNSPEZIFIED_KEY, - problem.getLiteral(), "", - (ILocation) problem.getData(), ra - .getContextId()); - } - } - - // Report all same values - if (configuration.getAuditSameValue()) { - Map<ILocation, ILocation> sameValues = ra - .getSameValuesReferences(); - for (ILocation problem : sameValues.keySet()) { - EditorUtils - .reportToRBMarker( - org.eclipse.babel.tapiji.tools.core.util.EditorUtils - .getFormattedMessage( - org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_SAME_VALUE, - new String[] { - problem.getFile() - .getName(), - sameValues - .get(problem) - .getFile() - .getName(), - problem.getLiteral() }), - problem, - IMarkerConstants.CAUSE_SAME_VALUE, - problem.getLiteral(), - sameValues.get(problem).getFile().getName(), - (ILocation) problem.getData(), ra - .getContextId()); - } - } - // Report all missing languages - if (configuration.getAuditMissingLanguage()) { - for (ILocation problem : ra.getMissingLanguageReferences()) { - EditorUtils - .reportToRBMarker( - org.eclipse.babel.tapiji.tools.core.util.EditorUtils - .getFormattedMessage( - org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_MISSING_LANGUAGE, - new String[] { - RBFileUtils - .getCorrespondingResourceBundleId(problem - .getFile()), - problem.getLiteral() }), - problem, - IMarkerConstants.CAUSE_MISSING_LANGUAGE, - problem.getLiteral(), "", - (ILocation) problem.getData(), ra - .getContextId()); - } - } + if (monitor.isCanceled()) { + monitor.done(); + break; + } + + if (ra.isResourceOfType(resource)) { + ra.audit(resource); + } } catch (Exception e) { - Logger.logError( - "Exception during reporting of Internationalization errors", - e); + Logger.logError( + "Error during auditing '" + resource.getFullPath() + + "'", e); } + } + + if (monitor != null) { + monitor.worked(1); + } } - @SuppressWarnings("unused") - private void setProgress(IProgressMonitor monitor, int progress) - throws InterruptedException { - monitor.worked(progress); + for (I18nAuditor a : ExtensionManager.getRegisteredI18nAuditors()) { + if (a instanceof I18nResourceAuditor) { + handleI18NAuditorMarkers((I18nResourceAuditor) a); + } + if (a instanceof I18nRBAuditor) { + handleI18NAuditorMarkers((I18nRBAuditor) a); + ((I18nRBAuditor) a).resetProblems(); + } + } - if (monitor.isCanceled()) { - throw new OperationCanceledException(); + monitor.done(); + } + + private void handleI18NAuditorMarkers(I18nResourceAuditor ra) { + try { + for (ILocation problem : ra.getConstantStringLiterals()) { + EditorUtils + .reportToMarker( + org.eclipse.babel.tapiji.tools.core.util.EditorUtils + .getFormattedMessage( + org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_NON_LOCALIZED_LITERAL, + new String[] { problem + .getLiteral() }), + problem, + IMarkerConstants.CAUSE_CONSTANT_LITERAL, "", + (ILocation) problem.getData(), ra + .getContextId()); + } + + // Report all broken Resource-Bundle references + for (ILocation brokenLiteral : ra.getBrokenResourceReferences()) { + EditorUtils + .reportToMarker( + org.eclipse.babel.tapiji.tools.core.util.EditorUtils + .getFormattedMessage( + org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_BROKEN_RESOURCE_REFERENCE, + new String[] { + brokenLiteral + .getLiteral(), + ((ILocation) brokenLiteral + .getData()) + .getLiteral() }), + brokenLiteral, + IMarkerConstants.CAUSE_BROKEN_REFERENCE, + brokenLiteral.getLiteral(), + (ILocation) brokenLiteral.getData(), ra + .getContextId()); + } + + // Report all broken definitions to Resource-Bundle + // references + for (ILocation brokenLiteral : ra.getBrokenBundleReferences()) { + EditorUtils + .reportToMarker( + org.eclipse.babel.tapiji.tools.core.util.EditorUtils + .getFormattedMessage( + org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE, + new String[] { brokenLiteral + .getLiteral() }), + brokenLiteral, + IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE, + brokenLiteral.getLiteral(), + (ILocation) brokenLiteral.getData(), ra + .getContextId()); + } + } catch (Exception e) { + Logger.logError( + "Exception during reporting of Internationalization errors", + e); + } + } + + private void handleI18NAuditorMarkers(I18nRBAuditor ra) { + IConfiguration configuration = ConfigurationManager.getInstance() + .getConfiguration(); + try { + // Report all unspecified keys + if (configuration.getAuditMissingValue()) { + for (ILocation problem : ra.getUnspecifiedKeyReferences()) { + EditorUtils + .reportToRBMarker( + org.eclipse.babel.tapiji.tools.core.util.EditorUtils + .getFormattedMessage( + org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_UNSPECIFIED_KEYS, + new String[] { + problem.getLiteral(), + problem.getFile() + .getName() }), + problem, + IMarkerConstants.CAUSE_UNSPEZIFIED_KEY, + problem.getLiteral(), "", + (ILocation) problem.getData(), ra + .getContextId()); } - - if (isInterrupted()) { - throw new InterruptedException(); + } + + // Report all same values + if (configuration.getAuditSameValue()) { + Map<ILocation, ILocation> sameValues = ra + .getSameValuesReferences(); + for (ILocation problem : sameValues.keySet()) { + EditorUtils + .reportToRBMarker( + org.eclipse.babel.tapiji.tools.core.util.EditorUtils + .getFormattedMessage( + org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_SAME_VALUE, + new String[] { + problem.getFile() + .getName(), + sameValues + .get(problem) + .getFile() + .getName(), + problem.getLiteral() }), + problem, + IMarkerConstants.CAUSE_SAME_VALUE, + problem.getLiteral(), + sameValues.get(problem).getFile().getName(), + (ILocation) problem.getData(), ra + .getContextId()); } + } + // Report all missing languages + if (configuration.getAuditMissingLanguage()) { + for (ILocation problem : ra.getMissingLanguageReferences()) { + EditorUtils + .reportToRBMarker( + org.eclipse.babel.tapiji.tools.core.util.EditorUtils + .getFormattedMessage( + org.eclipse.babel.tapiji.tools.core.util.EditorUtils.MESSAGE_MISSING_LANGUAGE, + new String[] { + RBFileUtils + .getCorrespondingResourceBundleId(problem + .getFile()), + problem.getLiteral() }), + problem, + IMarkerConstants.CAUSE_MISSING_LANGUAGE, + problem.getLiteral(), "", + (ILocation) problem.getData(), ra + .getContextId()); + } + } + } catch (Exception e) { + Logger.logError( + "Exception during reporting of Internationalization errors", + e); } + } + + @SuppressWarnings("unused") + private void setProgress(IProgressMonitor monitor, int progress) + throws InterruptedException { + monitor.worked(progress); - @Override - protected void clean(IProgressMonitor monitor) throws CoreException { - // TODO Auto-generated method stub - super.clean(monitor); + if (monitor.isCanceled()) { + throw new OperationCanceledException(); } - public static void addBuilderToProject(IProject project) { - Logger.logInfo("Internationalization-Builder registered for '" - + project.getName() + "'"); + if (isInterrupted()) { + throw new InterruptedException(); + } + } - // Only for open projects - if (!project.isOpen()) { - return; - } + @Override + protected void clean(IProgressMonitor monitor) throws CoreException { + // TODO Auto-generated method stub + super.clean(monitor); + } - IProjectDescription description = null; - try { - description = project.getDescription(); - } catch (CoreException e) { - Logger.logError(e); - return; - } + public static void addBuilderToProject(IProject project) { + Logger.logInfo("Internationalization-Builder registered for '" + + project.getName() + "'"); - // Check if the builder is already associated to the specified project - ICommand[] commands = description.getBuildSpec(); - for (ICommand command : commands) { - if (command.getBuilderName().equals(BUILDER_ID)) { - return; - } - } + // Only for open projects + if (!project.isOpen()) { + return; + } - // Associate the builder with the project - ICommand builderCmd = description.newCommand(); - builderCmd.setBuilderName(BUILDER_ID); - List<ICommand> newCommands = new ArrayList<ICommand>(); - newCommands.addAll(Arrays.asList(commands)); - newCommands.add(builderCmd); - description.setBuildSpec(newCommands.toArray(new ICommand[newCommands - .size()])); + IProjectDescription description = null; + try { + description = project.getDescription(); + } catch (CoreException e) { + Logger.logError(e); + return; + } - try { - project.setDescription(description, null); - } catch (CoreException e) { - Logger.logError(e); - } + // Check if the builder is already associated to the specified project + ICommand[] commands = description.getBuildSpec(); + for (ICommand command : commands) { + if (command.getBuilderName().equals(BUILDER_ID)) { + return; + } } - public static void removeBuilderFromProject(IProject project) { - // Only for open projects - if (!project.isOpen()) { - return; - } + // Associate the builder with the project + ICommand builderCmd = description.newCommand(); + builderCmd.setBuilderName(BUILDER_ID); + List<ICommand> newCommands = new ArrayList<ICommand>(); + newCommands.addAll(Arrays.asList(commands)); + newCommands.add(builderCmd); + description.setBuildSpec(newCommands.toArray(new ICommand[newCommands + .size()])); + + try { + project.setDescription(description, null); + } catch (CoreException e) { + Logger.logError(e); + } + } - try { - project.deleteMarkers(EditorUtils.MARKER_ID, false, - IResource.DEPTH_INFINITE); - project.deleteMarkers(EditorUtils.RB_MARKER_ID, false, - IResource.DEPTH_INFINITE); - } catch (CoreException e1) { - Logger.logError(e1); - } + public static void removeBuilderFromProject(IProject project) { + // Only for open projects + if (!project.isOpen()) { + return; + } - IProjectDescription description = null; - try { - description = project.getDescription(); - } catch (CoreException e) { - Logger.logError(e); - return; - } + try { + project.deleteMarkers(EditorUtils.MARKER_ID, false, + IResource.DEPTH_INFINITE); + project.deleteMarkers(EditorUtils.RB_MARKER_ID, false, + IResource.DEPTH_INFINITE); + } catch (CoreException e1) { + Logger.logError(e1); + } - // remove builder from project - int idx = -1; - ICommand[] commands = description.getBuildSpec(); - for (int i = 0; i < commands.length; i++) { - if (commands[i].getBuilderName().equals(BUILDER_ID)) { - idx = i; - break; - } - } - if (idx == -1) { - return; - } + IProjectDescription description = null; + try { + description = project.getDescription(); + } catch (CoreException e) { + Logger.logError(e); + return; + } - List<ICommand> newCommands = new ArrayList<ICommand>(); - newCommands.addAll(Arrays.asList(commands)); - newCommands.remove(idx); - description.setBuildSpec(newCommands.toArray(new ICommand[newCommands - .size()])); + // remove builder from project + int idx = -1; + ICommand[] commands = description.getBuildSpec(); + for (int i = 0; i < commands.length; i++) { + if (commands[i].getBuilderName().equals(BUILDER_ID)) { + idx = i; + break; + } + } + if (idx == -1) { + return; + } - try { - project.setDescription(description, null); - } catch (CoreException e) { - Logger.logError(e); - } + List<ICommand> newCommands = new ArrayList<ICommand>(); + newCommands.addAll(Arrays.asList(commands)); + newCommands.remove(idx); + description.setBuildSpec(newCommands.toArray(new ICommand[newCommands + .size()])); + try { + project.setDescription(description, null); + } catch (CoreException e) { + Logger.logError(e); } + } + } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/InternationalizationNature.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/InternationalizationNature.java index fa4ea483..21f78413 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/InternationalizationNature.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/InternationalizationNature.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -27,116 +27,116 @@ public class InternationalizationNature implements IProjectNature { - private static final String NATURE_ID = ResourceBundleManager.NATURE_ID; - - private IProject project; - - @Override - public void configure() throws CoreException { - I18nBuilder.addBuilderToProject(project); - new Job("Audit source files") { - - @Override - protected IStatus run(IProgressMonitor monitor) { - try { - project.build(I18nBuilder.FULL_BUILD, - I18nBuilder.BUILDER_ID, null, monitor); - } catch (CoreException e) { - Logger.logError(e); - } - return Status.OK_STATUS; - } - - }.schedule(); - } - - @Override - public void deconfigure() throws CoreException { - I18nBuilder.removeBuilderFromProject(project); - } - - @Override - public IProject getProject() { - return project; - } - - @Override - public void setProject(IProject project) { - this.project = project; - } - - public static void addNature(IProject project) { - if (!project.isOpen()) - return; - - IProjectDescription description = null; - - try { - description = project.getDescription(); - } catch (CoreException e) { - Logger.logError(e); - return; - } + private static final String NATURE_ID = ResourceBundleManager.NATURE_ID; - // Check if the project has already this nature - List<String> newIds = new ArrayList<String>(); - newIds.addAll(Arrays.asList(description.getNatureIds())); - int index = newIds.indexOf(NATURE_ID); - if (index != -1) - return; + private IProject project; - // Add the nature - newIds.add(NATURE_ID); - description.setNatureIds(newIds.toArray(new String[newIds.size()])); + @Override + public void configure() throws CoreException { + I18nBuilder.addBuilderToProject(project); + new Job("Audit source files") { + @Override + protected IStatus run(IProgressMonitor monitor) { try { - project.setDescription(description, null); + project.build(I18nBuilder.FULL_BUILD, + I18nBuilder.BUILDER_ID, null, monitor); } catch (CoreException e) { - Logger.logError(e); + Logger.logError(e); } + return Status.OK_STATUS; + } + + }.schedule(); + } + + @Override + public void deconfigure() throws CoreException { + I18nBuilder.removeBuilderFromProject(project); + } + + @Override + public IProject getProject() { + return project; + } + + @Override + public void setProject(IProject project) { + this.project = project; + } + + public static void addNature(IProject project) { + if (!project.isOpen()) + return; + + IProjectDescription description = null; + + try { + description = project.getDescription(); + } catch (CoreException e) { + Logger.logError(e); + return; } - public static boolean supportsNature(IProject project) { - return project.isOpen(); + // Check if the project has already this nature + List<String> newIds = new ArrayList<String>(); + newIds.addAll(Arrays.asList(description.getNatureIds())); + int index = newIds.indexOf(NATURE_ID); + if (index != -1) + return; + + // Add the nature + newIds.add(NATURE_ID); + description.setNatureIds(newIds.toArray(new String[newIds.size()])); + + try { + project.setDescription(description, null); + } catch (CoreException e) { + Logger.logError(e); } - - public static boolean hasNature(IProject project) { - try { - return project.isOpen() && project.hasNature(NATURE_ID); - } catch (CoreException e) { - Logger.logError(e); - return false; - } + } + + public static boolean supportsNature(IProject project) { + return project.isOpen(); + } + + public static boolean hasNature(IProject project) { + try { + return project.isOpen() && project.hasNature(NATURE_ID); + } catch (CoreException e) { + Logger.logError(e); + return false; } + } - public static void removeNature(IProject project) { - if (!project.isOpen()) - return; + public static void removeNature(IProject project) { + if (!project.isOpen()) + return; - IProjectDescription description = null; + IProjectDescription description = null; - try { - description = project.getDescription(); - } catch (CoreException e) { - Logger.logError(e); - return; - } - - // Check if the project has already this nature - List<String> newIds = new ArrayList<String>(); - newIds.addAll(Arrays.asList(description.getNatureIds())); - int index = newIds.indexOf(NATURE_ID); - if (index == -1) - return; - - // remove the nature - newIds.remove(NATURE_ID); - description.setNatureIds(newIds.toArray(new String[newIds.size()])); + try { + description = project.getDescription(); + } catch (CoreException e) { + Logger.logError(e); + return; + } - try { - project.setDescription(description, null); - } catch (CoreException e) { - Logger.logError(e); - } + // Check if the project has already this nature + List<String> newIds = new ArrayList<String>(); + newIds.addAll(Arrays.asList(description.getNatureIds())); + int index = newIds.indexOf(NATURE_ID); + if (index == -1) + return; + + // remove the nature + newIds.remove(NATURE_ID); + description.setNatureIds(newIds.toArray(new String[newIds.size()])); + + try { + project.setDescription(description, null); + } catch (CoreException e) { + Logger.logError(e); } + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ViolationResolutionGenerator.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ViolationResolutionGenerator.java index 472593e4..da1fad4a 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ViolationResolutionGenerator.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/builder/ViolationResolutionGenerator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -20,32 +20,32 @@ import org.eclipse.ui.IMarkerResolutionGenerator2; public class ViolationResolutionGenerator implements - IMarkerResolutionGenerator2 { + IMarkerResolutionGenerator2 { - @Override - public boolean hasResolutions(IMarker marker) { - return true; - } - - @Override - public IMarkerResolution[] getResolutions(IMarker marker) { + @Override + public boolean hasResolutions(IMarker marker) { + return true; + } - EditorUtils.updateMarker(marker); + @Override + public IMarkerResolution[] getResolutions(IMarker marker) { - String contextId = marker.getAttribute("context", ""); + EditorUtils.updateMarker(marker); - // find resolution generator for the given context - try { - I18nAuditor auditor = I18nBuilder - .getI18nAuditorByContext(contextId); - List<IMarkerResolution> resolutions = auditor - .getMarkerResolutions(marker); - return resolutions - .toArray(new IMarkerResolution[resolutions.size()]); - } catch (NoSuchResourceAuditorException e) { - } + String contextId = marker.getAttribute("context", ""); - return new IMarkerResolution[0]; + // find resolution generator for the given context + try { + I18nAuditor auditor = I18nBuilder + .getI18nAuditorByContext(contextId); + List<IMarkerResolution> resolutions = auditor + .getMarkerResolutions(marker); + return resolutions + .toArray(new IMarkerResolution[resolutions.size()]); + } catch (NoSuchResourceAuditorException e) { } + return new IMarkerResolution[0]; + } + } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java index 57bfdfb7..bf119685 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/decorators/ExcludedResource.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -31,85 +31,85 @@ import org.eclipse.swt.graphics.Image; public class ExcludedResource implements ILabelDecorator, - IResourceExclusionListener { + IResourceExclusionListener { - private static final String ENTRY_SUFFIX = "[no i18n]"; - private static final Image OVERLAY_IMAGE_ON = ImageUtils - .getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_ON); - private static final Image OVERLAY_IMAGE_OFF = ImageUtils - .getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF); - private final List<ILabelProviderListener> label_provider_listener = new ArrayList<ILabelProviderListener>(); + private static final String ENTRY_SUFFIX = "[no i18n]"; + private static final Image OVERLAY_IMAGE_ON = ImageUtils + .getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_ON); + private static final Image OVERLAY_IMAGE_OFF = ImageUtils + .getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF); + private final List<ILabelProviderListener> label_provider_listener = new ArrayList<ILabelProviderListener>(); - public boolean decorate(Object element) { - boolean needsDecoration = false; - if (element instanceof IFolder || element instanceof IFile) { - IResource resource = (IResource) element; - if (!InternationalizationNature.hasNature(resource.getProject())) - return false; - try { - ResourceBundleManager manager = ResourceBundleManager - .getManager(resource.getProject()); - if (!manager.isResourceExclusionListenerRegistered(this)) - manager.registerResourceExclusionListener(this); - if (ResourceBundleManager.isResourceExcluded(resource)) { - needsDecoration = true; - } - } catch (Exception e) { - Logger.logError(e); - } + public boolean decorate(Object element) { + boolean needsDecoration = false; + if (element instanceof IFolder || element instanceof IFile) { + IResource resource = (IResource) element; + if (!InternationalizationNature.hasNature(resource.getProject())) + return false; + try { + ResourceBundleManager manager = ResourceBundleManager + .getManager(resource.getProject()); + if (!manager.isResourceExclusionListenerRegistered(this)) + manager.registerResourceExclusionListener(this); + if (ResourceBundleManager.isResourceExcluded(resource)) { + needsDecoration = true; } - return needsDecoration; + } catch (Exception e) { + Logger.logError(e); + } } + return needsDecoration; + } - @Override - public void addListener(ILabelProviderListener listener) { - label_provider_listener.add(listener); - } + @Override + public void addListener(ILabelProviderListener listener) { + label_provider_listener.add(listener); + } - @Override - public void dispose() { - ResourceBundleManager - .unregisterResourceExclusionListenerFromAllManagers(this); - } + @Override + public void dispose() { + ResourceBundleManager + .unregisterResourceExclusionListenerFromAllManagers(this); + } - @Override - public boolean isLabelProperty(Object element, String property) { - return false; - } + @Override + public boolean isLabelProperty(Object element, String property) { + return false; + } - @Override - public void removeListener(ILabelProviderListener listener) { - label_provider_listener.remove(listener); - } + @Override + public void removeListener(ILabelProviderListener listener) { + label_provider_listener.remove(listener); + } - @Override - public void exclusionChanged(ResourceExclusionEvent event) { - LabelProviderChangedEvent labelEvent = new LabelProviderChangedEvent( - this, event.getChangedResources().toArray()); - for (ILabelProviderListener l : label_provider_listener) - l.labelProviderChanged(labelEvent); - } + @Override + public void exclusionChanged(ResourceExclusionEvent event) { + LabelProviderChangedEvent labelEvent = new LabelProviderChangedEvent( + this, event.getChangedResources().toArray()); + for (ILabelProviderListener l : label_provider_listener) + l.labelProviderChanged(labelEvent); + } - @Override - public Image decorateImage(Image image, Object element) { - if (decorate(element)) { - DecorationOverlayIcon overlayIcon = new DecorationOverlayIcon( - image, - Activator - .getImageDescriptor(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF), - IDecoration.TOP_RIGHT); - return overlayIcon.createImage(); - } else { - return image; - } + @Override + public Image decorateImage(Image image, Object element) { + if (decorate(element)) { + DecorationOverlayIcon overlayIcon = new DecorationOverlayIcon( + image, + Activator + .getImageDescriptor(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF), + IDecoration.TOP_RIGHT); + return overlayIcon.createImage(); + } else { + return image; } + } - @Override - public String decorateText(String text, Object element) { - if (decorate(element)) { - return text + " " + ENTRY_SUFFIX; - } else - return text; - } + @Override + public String decorateText(String text, Object element) { + if (decorate(element)) { + return text + " " + ENTRY_SUFFIX; + } else + return text; + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java index a61b3728..c592586f 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -36,133 +36,133 @@ import org.eclipse.swt.widgets.Text; public class AddLanguageDialoge extends Dialog { - private Locale locale; - private Shell shell; - - private Text titelText; - private Text descriptionText; - private Combo cmbLanguage; - private Text language; - private Text country; - private Text variant; - - public AddLanguageDialoge(Shell parentShell) { - super(parentShell); - shell = parentShell; + private Locale locale; + private Shell shell; + + private Text titelText; + private Text descriptionText; + private Combo cmbLanguage; + private Text language; + private Text country; + private Text variant; + + public AddLanguageDialoge(Shell parentShell) { + super(parentShell); + shell = parentShell; + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite titelArea = new Composite(parent, SWT.NO_BACKGROUND); + Composite dialogArea = (Composite) super.createDialogArea(parent); + GridLayout layout = new GridLayout(1, true); + dialogArea.setLayout(layout); + + initDescription(titelArea); + initCombo(dialogArea); + initTextArea(dialogArea); + + titelArea.pack(); + dialogArea.pack(); + parent.pack(); + + return dialogArea; + } + + private void initDescription(Composite titelArea) { + titelArea.setEnabled(false); + titelArea.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, true, + 1, 1)); + titelArea.setLayout(new GridLayout(1, true)); + titelArea.setBackground(new Color(shell.getDisplay(), 255, 255, 255)); + + titelText = new Text(titelArea, SWT.LEFT); + titelText.setFont(new Font(shell.getDisplay(), shell.getFont() + .getFontData()[0].getName(), 11, SWT.BOLD)); + titelText.setText("Please, specify the desired language"); + + descriptionText = new Text(titelArea, SWT.WRAP); + descriptionText.setLayoutData(new GridData(450, 60)); // TODO improve + descriptionText + .setText("Note: " + + "In all ResourceBundles of the project/plug-in will be created a new properties-file with the basename of the ResourceBundle and the corresponding locale-extension. " + + "If the locale is just provided of a ResourceBundle, no new file will be created."); + } + + private void initCombo(Composite dialogArea) { + cmbLanguage = new Combo(dialogArea, SWT.DROP_DOWN); + cmbLanguage.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, + true, 1, 1)); + + final Locale[] locales = Locale.getAvailableLocales(); + final Set<Locale> localeSet = new HashSet<Locale>(); + List<String> localeNames = new LinkedList<String>(); + + for (Locale l : locales) { + localeNames.add(l.getDisplayName()); + localeSet.add(l); } - @Override - protected Control createDialogArea(Composite parent) { - Composite titelArea = new Composite(parent, SWT.NO_BACKGROUND); - Composite dialogArea = (Composite) super.createDialogArea(parent); - GridLayout layout = new GridLayout(1, true); - dialogArea.setLayout(layout); - - initDescription(titelArea); - initCombo(dialogArea); - initTextArea(dialogArea); - - titelArea.pack(); - dialogArea.pack(); - parent.pack(); - - return dialogArea; - } - - private void initDescription(Composite titelArea) { - titelArea.setEnabled(false); - titelArea.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, true, - 1, 1)); - titelArea.setLayout(new GridLayout(1, true)); - titelArea.setBackground(new Color(shell.getDisplay(), 255, 255, 255)); - - titelText = new Text(titelArea, SWT.LEFT); - titelText.setFont(new Font(shell.getDisplay(), shell.getFont() - .getFontData()[0].getName(), 11, SWT.BOLD)); - titelText.setText("Please, specify the desired language"); - - descriptionText = new Text(titelArea, SWT.WRAP); - descriptionText.setLayoutData(new GridData(450, 60)); // TODO improve - descriptionText - .setText("Note: " - + "In all ResourceBundles of the project/plug-in will be created a new properties-file with the basename of the ResourceBundle and the corresponding locale-extension. " - + "If the locale is just provided of a ResourceBundle, no new file will be created."); - } - - private void initCombo(Composite dialogArea) { - cmbLanguage = new Combo(dialogArea, SWT.DROP_DOWN); - cmbLanguage.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, - true, 1, 1)); - - final Locale[] locales = Locale.getAvailableLocales(); - final Set<Locale> localeSet = new HashSet<Locale>(); - List<String> localeNames = new LinkedList<String>(); - - for (Locale l : locales) { - localeNames.add(l.getDisplayName()); - localeSet.add(l); + Collections.sort(localeNames); + + String[] s = new String[localeNames.size()]; + cmbLanguage.setItems(localeNames.toArray(s)); + cmbLanguage.add(ResourceBundleManager.defaultLocaleTag, 0); + + cmbLanguage.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent e) { + int selectIndex = ((Combo) e.getSource()).getSelectionIndex(); + if (!cmbLanguage.getItem(selectIndex).equals( + ResourceBundleManager.defaultLocaleTag)) { + Locale l = LocaleUtils.getLocaleByDisplayName(localeSet, + cmbLanguage.getItem(selectIndex)); + + language.setText(l.getLanguage()); + country.setText(l.getCountry()); + variant.setText(l.getVariant()); + } else { + language.setText(""); + country.setText(""); + variant.setText(""); } - - Collections.sort(localeNames); - - String[] s = new String[localeNames.size()]; - cmbLanguage.setItems(localeNames.toArray(s)); - cmbLanguage.add(ResourceBundleManager.defaultLocaleTag, 0); - - cmbLanguage.addSelectionListener(new SelectionListener() { - @Override - public void widgetSelected(SelectionEvent e) { - int selectIndex = ((Combo) e.getSource()).getSelectionIndex(); - if (!cmbLanguage.getItem(selectIndex).equals( - ResourceBundleManager.defaultLocaleTag)) { - Locale l = LocaleUtils.getLocaleByDisplayName(localeSet, - cmbLanguage.getItem(selectIndex)); - - language.setText(l.getLanguage()); - country.setText(l.getCountry()); - variant.setText(l.getVariant()); - } else { - language.setText(""); - country.setText(""); - variant.setText(""); - } - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - // TODO Auto-generated method stub - } - }); - } - - private void initTextArea(Composite dialogArea) { - final Group group = new Group(dialogArea, SWT.SHADOW_ETCHED_IN); - group.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 1, - 1)); - group.setLayout(new GridLayout(3, true)); - group.setText("Locale"); - - Label languageLabel = new Label(group, SWT.SINGLE); - languageLabel.setText("Language"); - Label countryLabel = new Label(group, SWT.SINGLE); - countryLabel.setText("Country"); - Label variantLabel = new Label(group, SWT.SINGLE); - variantLabel.setText("Variant"); - - language = new Text(group, SWT.SINGLE); - country = new Text(group, SWT.SINGLE); - variant = new Text(group, SWT.SINGLE); - } - - @Override - protected void okPressed() { - locale = new Locale(language.getText(), country.getText(), - variant.getText()); - - super.okPressed(); - } - - public Locale getSelectedLanguage() { - return locale; - } + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + // TODO Auto-generated method stub + } + }); + } + + private void initTextArea(Composite dialogArea) { + final Group group = new Group(dialogArea, SWT.SHADOW_ETCHED_IN); + group.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 1, + 1)); + group.setLayout(new GridLayout(3, true)); + group.setText("Locale"); + + Label languageLabel = new Label(group, SWT.SINGLE); + languageLabel.setText("Language"); + Label countryLabel = new Label(group, SWT.SINGLE); + countryLabel.setText("Country"); + Label variantLabel = new Label(group, SWT.SINGLE); + variantLabel.setText("Variant"); + + language = new Text(group, SWT.SINGLE); + country = new Text(group, SWT.SINGLE); + variant = new Text(group, SWT.SINGLE); + } + + @Override + protected void okPressed() { + locale = new Locale(language.getText(), country.getText(), + variant.getText()); + + super.okPressed(); + } + + public Locale getSelectedLanguage() { + return locale; + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java index 6d348525..cda61c0d 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -21,47 +21,47 @@ import org.eclipse.swt.widgets.Text; public class CreatePatternDialoge extends Dialog { - private String pattern; - private Text patternText; + private String pattern; + private Text patternText; - public CreatePatternDialoge(Shell shell) { - this(shell, ""); - } + public CreatePatternDialoge(Shell shell) { + this(shell, ""); + } - public CreatePatternDialoge(Shell shell, String pattern) { - super(shell); - this.pattern = pattern; - // setShellStyle(SWT.RESIZE); - } + public CreatePatternDialoge(Shell shell, String pattern) { + super(shell); + this.pattern = pattern; + // setShellStyle(SWT.RESIZE); + } - @Override - protected Control createDialogArea(Composite parent) { - Composite composite = new Composite(parent, SWT.NONE); - composite.setLayout(new GridLayout(1, true)); - composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false)); + @Override + protected Control createDialogArea(Composite parent) { + Composite composite = new Composite(parent, SWT.NONE); + composite.setLayout(new GridLayout(1, true)); + composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false)); - Label descriptionLabel = new Label(composite, SWT.NONE); - descriptionLabel.setText("Enter a regular expression:"); + Label descriptionLabel = new Label(composite, SWT.NONE); + descriptionLabel.setText("Enter a regular expression:"); - patternText = new Text(composite, SWT.WRAP | SWT.MULTI); - GridData gData = new GridData(SWT.FILL, SWT.FILL, true, false); - gData.widthHint = 400; - gData.heightHint = 60; - patternText.setLayoutData(gData); - patternText.setText(pattern); + patternText = new Text(composite, SWT.WRAP | SWT.MULTI); + GridData gData = new GridData(SWT.FILL, SWT.FILL, true, false); + gData.widthHint = 400; + gData.heightHint = 60; + patternText.setLayoutData(gData); + patternText.setText(pattern); - return composite; - } + return composite; + } - @Override - protected void okPressed() { - pattern = patternText.getText(); + @Override + protected void okPressed() { + pattern = patternText.getText(); - super.okPressed(); - } + super.okPressed(); + } - public String getPattern() { - return pattern; - } + public String getPattern() { + return pattern; + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java index fed59c04..290540d0 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Martin Reiterer, Clemente Lodi-Fe, Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -41,441 +41,441 @@ public class CreateResourceBundleEntryDialog extends TitleAreaDialog { - private static int WIDTH_LEFT_COLUMN = 100; + private static int WIDTH_LEFT_COLUMN = 100; - private static final String DEFAULT_KEY = "defaultkey"; + private static final String DEFAULT_KEY = "defaultkey"; - private String projectName; + private String projectName; - private Text txtKey; - private Combo cmbRB; - private Text txtDefaultText; - private Combo cmbLanguage; + private Text txtKey; + private Combo cmbRB; + private Text txtDefaultText; + private Combo cmbLanguage; - private Button okButton; - private Button cancelButton; + private Button okButton; + private Button cancelButton; - /*** Dialog Model ***/ - String selectedRB = ""; - String selectedLocale = ""; - String selectedKey = ""; - String selectedDefaultText = ""; + /*** Dialog Model ***/ + String selectedRB = ""; + String selectedLocale = ""; + String selectedKey = ""; + String selectedDefaultText = ""; - /*** MODIFY LISTENER ***/ - ModifyListener rbModifyListener; + /*** MODIFY LISTENER ***/ + ModifyListener rbModifyListener; - public class DialogConfiguration { + public class DialogConfiguration { - String projectName; + String projectName; - String preselectedKey; - String preselectedMessage; - String preselectedBundle; - String preselectedLocale; + String preselectedKey; + String preselectedMessage; + String preselectedBundle; + String preselectedLocale; - public String getProjectName() { - return projectName; - } - - public void setProjectName(String projectName) { - this.projectName = projectName; - } - - public String getPreselectedKey() { - return preselectedKey; - } - - public void setPreselectedKey(String preselectedKey) { - this.preselectedKey = preselectedKey; - } + public String getProjectName() { + return projectName; + } - public String getPreselectedMessage() { - return preselectedMessage; - } + public void setProjectName(String projectName) { + this.projectName = projectName; + } - public void setPreselectedMessage(String preselectedMessage) { - this.preselectedMessage = preselectedMessage; - } + public String getPreselectedKey() { + return preselectedKey; + } - public String getPreselectedBundle() { - return preselectedBundle; - } + public void setPreselectedKey(String preselectedKey) { + this.preselectedKey = preselectedKey; + } - public void setPreselectedBundle(String preselectedBundle) { - this.preselectedBundle = preselectedBundle; - } + public String getPreselectedMessage() { + return preselectedMessage; + } - public String getPreselectedLocale() { - return preselectedLocale; - } + public void setPreselectedMessage(String preselectedMessage) { + this.preselectedMessage = preselectedMessage; + } - public void setPreselectedLocale(String preselectedLocale) { - this.preselectedLocale = preselectedLocale; - } + public String getPreselectedBundle() { + return preselectedBundle; + } + public void setPreselectedBundle(String preselectedBundle) { + this.preselectedBundle = preselectedBundle; } - public CreateResourceBundleEntryDialog(Shell parentShell) { - super(parentShell); + public String getPreselectedLocale() { + return preselectedLocale; } - public void setDialogConfiguration(DialogConfiguration config) { - String preselectedKey = config.getPreselectedKey(); - this.selectedKey = preselectedKey != null ? preselectedKey.trim() - : preselectedKey; - if ("".equals(this.selectedKey)) { - this.selectedKey = DEFAULT_KEY; - } - - this.selectedDefaultText = config.getPreselectedMessage(); - this.selectedRB = config.getPreselectedBundle(); - this.selectedLocale = config.getPreselectedLocale(); - this.projectName = config.getProjectName(); + public void setPreselectedLocale(String preselectedLocale) { + this.preselectedLocale = preselectedLocale; } - public String getSelectedResourceBundle() { - return selectedRB; + } + + public CreateResourceBundleEntryDialog(Shell parentShell) { + super(parentShell); + } + + public void setDialogConfiguration(DialogConfiguration config) { + String preselectedKey = config.getPreselectedKey(); + this.selectedKey = preselectedKey != null ? preselectedKey.trim() + : preselectedKey; + if ("".equals(this.selectedKey)) { + this.selectedKey = DEFAULT_KEY; } - public String getSelectedKey() { - return selectedKey; + this.selectedDefaultText = config.getPreselectedMessage(); + this.selectedRB = config.getPreselectedBundle(); + this.selectedLocale = config.getPreselectedLocale(); + this.projectName = config.getProjectName(); + } + + public String getSelectedResourceBundle() { + return selectedRB; + } + + public String getSelectedKey() { + return selectedKey; + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite dialogArea = (Composite) super.createDialogArea(parent); + initLayout(dialogArea); + constructRBSection(dialogArea); + constructDefaultSection(dialogArea); + initContent(); + return dialogArea; + } + + protected void initContent() { + cmbRB.removeAll(); + int iSel = -1; + int index = 0; + + Collection<String> availableBundles = ResourceBundleManager.getManager( + projectName).getResourceBundleNames(); + + for (String bundle : availableBundles) { + cmbRB.add(bundle); + if (bundle.equals(selectedRB)) { + cmbRB.select(index); + iSel = index; + cmbRB.setEnabled(false); + } + index++; } - @Override - protected Control createDialogArea(Composite parent) { - Composite dialogArea = (Composite) super.createDialogArea(parent); - initLayout(dialogArea); - constructRBSection(dialogArea); - constructDefaultSection(dialogArea); - initContent(); - return dialogArea; + if (availableBundles.size() > 0 && iSel < 0) { + cmbRB.select(0); + selectedRB = cmbRB.getText(); + cmbRB.setEnabled(true); } - protected void initContent() { - cmbRB.removeAll(); - int iSel = -1; - int index = 0; - - Collection<String> availableBundles = ResourceBundleManager.getManager( - projectName).getResourceBundleNames(); - - for (String bundle : availableBundles) { - cmbRB.add(bundle); - if (bundle.equals(selectedRB)) { - cmbRB.select(index); - iSel = index; - cmbRB.setEnabled(false); - } - index++; - } - - if (availableBundles.size() > 0 && iSel < 0) { - cmbRB.select(0); - selectedRB = cmbRB.getText(); - cmbRB.setEnabled(true); - } - - rbModifyListener = new ModifyListener() { - - @Override - public void modifyText(ModifyEvent e) { - selectedRB = cmbRB.getText(); - validate(); - } - }; - cmbRB.removeModifyListener(rbModifyListener); - cmbRB.addModifyListener(rbModifyListener); - - cmbRB.addSelectionListener(new SelectionListener() { - - @Override - public void widgetSelected(SelectionEvent e) { - selectedLocale = ""; - updateAvailableLanguages(); - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - - selectedLocale = ""; - updateAvailableLanguages(); - } - }); - updateAvailableLanguages(); + rbModifyListener = new ModifyListener() { + + @Override + public void modifyText(ModifyEvent e) { + selectedRB = cmbRB.getText(); validate(); - } + } + }; + cmbRB.removeModifyListener(rbModifyListener); + cmbRB.addModifyListener(rbModifyListener); - protected void updateAvailableLanguages() { - cmbLanguage.removeAll(); - String selectedBundle = cmbRB.getText(); - - if ("".equals(selectedBundle.trim())) { - return; - } - - ResourceBundleManager manager = ResourceBundleManager - .getManager(projectName); - - // Retrieve available locales for the selected resource-bundle - Set<Locale> locales = manager.getProvidedLocales(selectedBundle); - int index = 0; - int iSel = -1; - for (Locale l : manager.getProvidedLocales(selectedBundle)) { - String displayName = l == null ? ResourceBundleManager.defaultLocaleTag - : l.getDisplayName(); - if (displayName.equals(selectedLocale)) - iSel = index; - if (displayName.equals("")) - displayName = ResourceBundleManager.defaultLocaleTag; - cmbLanguage.add(displayName); - if (index == iSel) - cmbLanguage.select(iSel); - index++; - } - - if (locales.size() > 0) { - cmbLanguage.select(0); - selectedLocale = cmbLanguage.getText(); - } - - cmbLanguage.addModifyListener(new ModifyListener() { - @Override - public void modifyText(ModifyEvent e) { - selectedLocale = cmbLanguage.getText(); - validate(); - } - }); - } + cmbRB.addSelectionListener(new SelectionListener() { - protected void initLayout(Composite parent) { - final GridLayout layout = new GridLayout(1, true); - parent.setLayout(layout); - } + @Override + public void widgetSelected(SelectionEvent e) { + selectedLocale = ""; + updateAvailableLanguages(); + } - protected void constructRBSection(Composite parent) { - final Group group = new Group(parent, SWT.SHADOW_ETCHED_IN); - group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, - false, 1, 1)); - group.setText("Resource Bundle"); - - // define grid data for this group - GridData gridData = new GridData(); - gridData.horizontalAlignment = SWT.FILL; - gridData.grabExcessHorizontalSpace = true; - group.setLayoutData(gridData); - group.setLayout(new GridLayout(2, false)); - - final Label spacer = new Label(group, SWT.NONE | SWT.LEFT); - spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, - false, false, 1, 1)); - - final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT); - infoLabel.setLayoutData(new GridData(GridData.BEGINNING, - GridData.CENTER, false, false, 1, 1)); - infoLabel - .setText("Specify the key of the new resource as well as the Resource-Bundle in\n" - + "which the resource" + "should be added.\n"); - - // Schl�ssel - final Label lblKey = new Label(group, SWT.NONE | SWT.RIGHT); - GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER, - false, false, 1, 1); - lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN; - lblKey.setLayoutData(lblKeyGrid); - lblKey.setText("Key:"); - txtKey = new Text(group, SWT.BORDER); - txtKey.setText(selectedKey); - // grey ouut textfield if there already is a preset key - txtKey.setEditable(selectedKey.trim().length() == 0 - || selectedKey.indexOf("[Platzhalter]") >= 0 - || selectedKey.equals(DEFAULT_KEY)); - txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, - false, 1, 1)); - txtKey.addModifyListener(new ModifyListener() { - - @Override - public void modifyText(ModifyEvent e) { - selectedKey = txtKey.getText(); - validate(); - } - }); - - // Resource-Bundle - final Label lblRB = new Label(group, SWT.NONE); - lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, - false, 1, 1)); - lblRB.setText("Resource-Bundle:"); - - cmbRB = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE); - cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, - false, 1, 1)); - } + @Override + public void widgetDefaultSelected(SelectionEvent e) { - protected void constructDefaultSection(Composite parent) { - final Group group = new Group(parent, SWT.SHADOW_ETCHED_IN); - group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, - true, 1, 1)); - group.setText("Default-Text"); - - // define grid data for this group - GridData gridData = new GridData(); - gridData.horizontalAlignment = SWT.FILL; - gridData.grabExcessHorizontalSpace = true; - group.setLayoutData(gridData); - group.setLayout(new GridLayout(2, false)); - - final Label spacer = new Label(group, SWT.NONE | SWT.LEFT); - spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, - false, false, 1, 1)); - - final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT); - infoLabel.setLayoutData(new GridData(GridData.BEGINNING, - GridData.CENTER, false, false, 1, 1)); - infoLabel - .setText("Define a default text for the specified resource. Moreover, you need to\n" - + "select the locale for which the default text should be defined."); - - // Text - final Label lblText = new Label(group, SWT.NONE | SWT.RIGHT); - GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, - false, false, 1, 1); - lblTextGrid.heightHint = 80; - lblTextGrid.widthHint = 100; - lblText.setLayoutData(lblTextGrid); - lblText.setText("Text:"); - - txtDefaultText = new Text(group, SWT.MULTI | SWT.BORDER); - txtDefaultText.setText(selectedDefaultText); - txtDefaultText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, - true, true, 1, 1)); - txtDefaultText.addModifyListener(new ModifyListener() { - - @Override - public void modifyText(ModifyEvent e) { - selectedDefaultText = txtDefaultText.getText(); - validate(); - } - }); - - // Sprache - final Label lblLanguage = new Label(group, SWT.NONE); - lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, - false, false, 1, 1)); - lblLanguage.setText("Language (Country):"); - - cmbLanguage = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE); - cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, - true, false, 1, 1)); + selectedLocale = ""; + updateAvailableLanguages(); + } + }); + updateAvailableLanguages(); + validate(); + } + + protected void updateAvailableLanguages() { + cmbLanguage.removeAll(); + String selectedBundle = cmbRB.getText(); + + if ("".equals(selectedBundle.trim())) { + return; } - @Override - protected void okPressed() { - super.okPressed(); - // TODO debug - ResourceBundleManager manager = ResourceBundleManager - .getManager(projectName); - // Insert new Resource-Bundle reference - Locale locale = LocaleUtils.getLocaleByDisplayName( - manager.getProvidedLocales(selectedRB), selectedLocale); // new - // Locale(""); - // // - // retrieve - // locale - - try { - manager.addResourceBundleEntry(selectedRB, selectedKey, locale, - selectedDefaultText); - } catch (ResourceBundleException e) { - Logger.logError(e); - } + ResourceBundleManager manager = ResourceBundleManager + .getManager(projectName); + + // Retrieve available locales for the selected resource-bundle + Set<Locale> locales = manager.getProvidedLocales(selectedBundle); + int index = 0; + int iSel = -1; + for (Locale l : manager.getProvidedLocales(selectedBundle)) { + String displayName = l == null ? ResourceBundleManager.defaultLocaleTag + : l.getDisplayName(); + if (displayName.equals(selectedLocale)) + iSel = index; + if (displayName.equals("")) + displayName = ResourceBundleManager.defaultLocaleTag; + cmbLanguage.add(displayName); + if (index == iSel) + cmbLanguage.select(iSel); + index++; } - @Override - protected void configureShell(Shell newShell) { - super.configureShell(newShell); - newShell.setText("Create Resource-Bundle entry"); + if (locales.size() > 0) { + cmbLanguage.select(0); + selectedLocale = cmbLanguage.getText(); } - @Override - public void create() { - // TODO Auto-generated method stub - super.create(); - this.setTitle("New Resource-Bundle entry"); - this.setMessage("Please, specify details about the new Resource-Bundle entry"); + cmbLanguage.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + selectedLocale = cmbLanguage.getText(); + validate(); + } + }); + } + + protected void initLayout(Composite parent) { + final GridLayout layout = new GridLayout(1, true); + parent.setLayout(layout); + } + + protected void constructRBSection(Composite parent) { + final Group group = new Group(parent, SWT.SHADOW_ETCHED_IN); + group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, + false, 1, 1)); + group.setText("Resource Bundle"); + + // define grid data for this group + GridData gridData = new GridData(); + gridData.horizontalAlignment = SWT.FILL; + gridData.grabExcessHorizontalSpace = true; + group.setLayoutData(gridData); + group.setLayout(new GridLayout(2, false)); + + final Label spacer = new Label(group, SWT.NONE | SWT.LEFT); + spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, + false, false, 1, 1)); + + final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT); + infoLabel.setLayoutData(new GridData(GridData.BEGINNING, + GridData.CENTER, false, false, 1, 1)); + infoLabel + .setText("Specify the key of the new resource as well as the Resource-Bundle in\n" + + "which the resource" + "should be added.\n"); + + // Schl�ssel + final Label lblKey = new Label(group, SWT.NONE | SWT.RIGHT); + GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER, + false, false, 1, 1); + lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN; + lblKey.setLayoutData(lblKeyGrid); + lblKey.setText("Key:"); + txtKey = new Text(group, SWT.BORDER); + txtKey.setText(selectedKey); + // grey ouut textfield if there already is a preset key + txtKey.setEditable(selectedKey.trim().length() == 0 + || selectedKey.indexOf("[Platzhalter]") >= 0 + || selectedKey.equals(DEFAULT_KEY)); + txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, + false, 1, 1)); + txtKey.addModifyListener(new ModifyListener() { + + @Override + public void modifyText(ModifyEvent e) { + selectedKey = txtKey.getText(); + validate(); + } + }); + + // Resource-Bundle + final Label lblRB = new Label(group, SWT.NONE); + lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, + false, 1, 1)); + lblRB.setText("Resource-Bundle:"); + + cmbRB = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE); + cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, + false, 1, 1)); + } + + protected void constructDefaultSection(Composite parent) { + final Group group = new Group(parent, SWT.SHADOW_ETCHED_IN); + group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, + true, 1, 1)); + group.setText("Default-Text"); + + // define grid data for this group + GridData gridData = new GridData(); + gridData.horizontalAlignment = SWT.FILL; + gridData.grabExcessHorizontalSpace = true; + group.setLayoutData(gridData); + group.setLayout(new GridLayout(2, false)); + + final Label spacer = new Label(group, SWT.NONE | SWT.LEFT); + spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, + false, false, 1, 1)); + + final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT); + infoLabel.setLayoutData(new GridData(GridData.BEGINNING, + GridData.CENTER, false, false, 1, 1)); + infoLabel + .setText("Define a default text for the specified resource. Moreover, you need to\n" + + "select the locale for which the default text should be defined."); + + // Text + final Label lblText = new Label(group, SWT.NONE | SWT.RIGHT); + GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, + false, false, 1, 1); + lblTextGrid.heightHint = 80; + lblTextGrid.widthHint = 100; + lblText.setLayoutData(lblTextGrid); + lblText.setText("Text:"); + + txtDefaultText = new Text(group, SWT.MULTI | SWT.BORDER); + txtDefaultText.setText(selectedDefaultText); + txtDefaultText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, + true, true, 1, 1)); + txtDefaultText.addModifyListener(new ModifyListener() { + + @Override + public void modifyText(ModifyEvent e) { + selectedDefaultText = txtDefaultText.getText(); + validate(); + } + }); + + // Sprache + final Label lblLanguage = new Label(group, SWT.NONE); + lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, + false, false, 1, 1)); + lblLanguage.setText("Language (Country):"); + + cmbLanguage = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE); + cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, + true, false, 1, 1)); + } + + @Override + protected void okPressed() { + super.okPressed(); + // TODO debug + ResourceBundleManager manager = ResourceBundleManager + .getManager(projectName); + // Insert new Resource-Bundle reference + Locale locale = LocaleUtils.getLocaleByDisplayName( + manager.getProvidedLocales(selectedRB), selectedLocale); // new + // Locale(""); + // // + // retrieve + // locale + + try { + manager.addResourceBundleEntry(selectedRB, selectedKey, locale, + selectedDefaultText); + } catch (ResourceBundleException e) { + Logger.logError(e); } - - /** - * Validates all inputs of the CreateResourceBundleEntryDialog - */ - protected void validate() { - // Check Resource-Bundle ids - boolean keyValid = false; - boolean keyValidChar = ResourceUtils.isValidResourceKey(selectedKey); - boolean rbValid = false; - boolean textValid = false; - ResourceBundleManager manager = ResourceBundleManager - .getManager(projectName); - boolean localeValid = LocaleUtils.containsLocaleByDisplayName( - manager.getProvidedLocales(selectedRB), selectedLocale); - - for (String rbId : manager.getResourceBundleNames()) { - if (rbId.equals(selectedRB)) { - rbValid = true; - break; - } - } - - if (!manager.isResourceExisting(selectedRB, selectedKey)) - keyValid = true; - - if (selectedDefaultText.trim().length() > 0) - textValid = true; - - // print Validation summary - String errorMessage = null; - if (selectedKey.trim().length() == 0) - errorMessage = "No resource key specified."; - else if (!keyValidChar) - errorMessage = "The specified resource key contains invalid characters."; - else if (!keyValid) - errorMessage = "The specified resource key is already existing."; - else if (!rbValid) - errorMessage = "The specified Resource-Bundle does not exist."; - else if (!localeValid) - errorMessage = "The specified Locale does not exist for the selected Resource-Bundle."; - else if (!textValid) - errorMessage = "No default translation specified."; - else { - if (okButton != null) - okButton.setEnabled(true); - } - - setErrorMessage(errorMessage); - if (okButton != null && errorMessage != null) - okButton.setEnabled(false); + } + + @Override + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText("Create Resource-Bundle entry"); + } + + @Override + public void create() { + // TODO Auto-generated method stub + super.create(); + this.setTitle("New Resource-Bundle entry"); + this.setMessage("Please, specify details about the new Resource-Bundle entry"); + } + + /** + * Validates all inputs of the CreateResourceBundleEntryDialog + */ + protected void validate() { + // Check Resource-Bundle ids + boolean keyValid = false; + boolean keyValidChar = ResourceUtils.isValidResourceKey(selectedKey); + boolean rbValid = false; + boolean textValid = false; + ResourceBundleManager manager = ResourceBundleManager + .getManager(projectName); + boolean localeValid = LocaleUtils.containsLocaleByDisplayName( + manager.getProvidedLocales(selectedRB), selectedLocale); + + for (String rbId : manager.getResourceBundleNames()) { + if (rbId.equals(selectedRB)) { + rbValid = true; + break; + } } - @Override - protected void createButtonsForButtonBar(Composite parent) { - okButton = createButton(parent, OK, "Ok", true); - okButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - // Set return code - setReturnCode(OK); - close(); - } - }); - - cancelButton = createButton(parent, CANCEL, "Cancel", false); - cancelButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - setReturnCode(CANCEL); - close(); - } - }); - + if (!manager.isResourceExisting(selectedRB, selectedKey)) + keyValid = true; + + if (selectedDefaultText.trim().length() > 0) + textValid = true; + + // print Validation summary + String errorMessage = null; + if (selectedKey.trim().length() == 0) + errorMessage = "No resource key specified."; + else if (!keyValidChar) + errorMessage = "The specified resource key contains invalid characters."; + else if (!keyValid) + errorMessage = "The specified resource key is already existing."; + else if (!rbValid) + errorMessage = "The specified Resource-Bundle does not exist."; + else if (!localeValid) + errorMessage = "The specified Locale does not exist for the selected Resource-Bundle."; + else if (!textValid) + errorMessage = "No default translation specified."; + else { + if (okButton != null) okButton.setEnabled(true); - cancelButton.setEnabled(true); } + setErrorMessage(errorMessage); + if (okButton != null && errorMessage != null) + okButton.setEnabled(false); + } + + @Override + protected void createButtonsForButtonBar(Composite parent) { + okButton = createButton(parent, OK, "Ok", true); + okButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + // Set return code + setReturnCode(OK); + close(); + } + }); + + cancelButton = createButton(parent, CANCEL, "Cancel", false); + cancelButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + setReturnCode(CANCEL); + close(); + } + }); + + okButton.setEnabled(true); + cancelButton.setEnabled(true); + } + } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java index 6a503f64..14b637dd 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -25,100 +25,100 @@ import org.eclipse.ui.dialogs.ListDialog; public class FragmentProjectSelectionDialog extends ListDialog { - private IProject hostproject; - private List<IProject> allProjects; - - public FragmentProjectSelectionDialog(Shell parent, IProject hostproject, - List<IProject> fragmentprojects) { - super(parent); - this.hostproject = hostproject; - this.allProjects = new ArrayList<IProject>(fragmentprojects); - allProjects.add(0, hostproject); - - init(); + private IProject hostproject; + private List<IProject> allProjects; + + public FragmentProjectSelectionDialog(Shell parent, IProject hostproject, + List<IProject> fragmentprojects) { + super(parent); + this.hostproject = hostproject; + this.allProjects = new ArrayList<IProject>(fragmentprojects); + allProjects.add(0, hostproject); + + init(); + } + + private void init() { + this.setAddCancelButton(true); + this.setMessage("Select one of the following plug-ins:"); + this.setTitle("Project Selector"); + this.setContentProvider(new IProjectContentProvider()); + this.setLabelProvider(new IProjectLabelProvider()); + + this.setInput(allProjects); + } + + public IProject getSelectedProject() { + Object[] selection = this.getResult(); + if (selection != null && selection.length > 0) + return (IProject) selection[0]; + return null; + } + + // private classes-------------------------------------------------------- + class IProjectContentProvider implements IStructuredContentProvider { + + @Override + public Object[] getElements(Object inputElement) { + List<IProject> resources = (List<IProject>) inputElement; + return resources.toArray(); } - private void init() { - this.setAddCancelButton(true); - this.setMessage("Select one of the following plug-ins:"); - this.setTitle("Project Selector"); - this.setContentProvider(new IProjectContentProvider()); - this.setLabelProvider(new IProjectLabelProvider()); + @Override + public void dispose() { + // TODO Auto-generated method stub - this.setInput(allProjects); } - public IProject getSelectedProject() { - Object[] selection = this.getResult(); - if (selection != null && selection.length > 0) - return (IProject) selection[0]; - return null; + @Override + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + // TODO Auto-generated method stub } - // private classes-------------------------------------------------------- - class IProjectContentProvider implements IStructuredContentProvider { - - @Override - public Object[] getElements(Object inputElement) { - List<IProject> resources = (List<IProject>) inputElement; - return resources.toArray(); - } - - @Override - public void dispose() { - // TODO Auto-generated method stub + } - } - - @Override - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - // TODO Auto-generated method stub - } + class IProjectLabelProvider implements ILabelProvider { + @Override + public Image getImage(Object element) { + return PlatformUI.getWorkbench().getSharedImages() + .getImage(ISharedImages.IMG_OBJ_PROJECT); } - class IProjectLabelProvider implements ILabelProvider { - - @Override - public Image getImage(Object element) { - return PlatformUI.getWorkbench().getSharedImages() - .getImage(ISharedImages.IMG_OBJ_PROJECT); - } - - @Override - public String getText(Object element) { - IProject p = ((IProject) element); - String text = p.getName(); - if (p.equals(hostproject)) - text += " [host project]"; - else - text += " [fragment project]"; - return text; - } - - @Override - public void addListener(ILabelProviderListener listener) { - // TODO Auto-generated method stub + @Override + public String getText(Object element) { + IProject p = ((IProject) element); + String text = p.getName(); + if (p.equals(hostproject)) + text += " [host project]"; + else + text += " [fragment project]"; + return text; + } - } + @Override + public void addListener(ILabelProviderListener listener) { + // TODO Auto-generated method stub - @Override - public void dispose() { - // TODO Auto-generated method stub + } - } + @Override + public void dispose() { + // TODO Auto-generated method stub - @Override - public boolean isLabelProperty(Object element, String property) { - // TODO Auto-generated method stub - return false; - } + } - @Override - public void removeListener(ILabelProviderListener listener) { - // TODO Auto-generated method stub + @Override + public boolean isLabelProperty(Object element, String property) { + // TODO Auto-generated method stub + return false; + } - } + @Override + public void removeListener(ILabelProviderListener listener) { + // TODO Auto-generated method stub } + + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java index 841c7290..ac9fce7f 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -23,124 +23,124 @@ public class GenerateBundleAccessorDialog extends TitleAreaDialog { - private static int WIDTH_LEFT_COLUMN = 100; - - private Text bundleAccessor; - private Text packageName; - - public GenerateBundleAccessorDialog(Shell parentShell) { - super(parentShell); - } - - @Override - protected Control createDialogArea(Composite parent) { - Composite dialogArea = (Composite) super.createDialogArea(parent); - initLayout(dialogArea); - constructBASection(dialogArea); - // constructDefaultSection (dialogArea); - initContent(); - return dialogArea; - } - - protected void initLayout(Composite parent) { - final GridLayout layout = new GridLayout(1, true); - parent.setLayout(layout); - } - - protected void constructBASection(Composite parent) { - final Group group = new Group(parent, SWT.SHADOW_ETCHED_IN); - group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, - false, 1, 1)); - group.setText("Resource Bundle"); - - // define grid data for this group - GridData gridData = new GridData(); - gridData.horizontalAlignment = SWT.FILL; - gridData.grabExcessHorizontalSpace = true; - group.setLayoutData(gridData); - group.setLayout(new GridLayout(2, false)); - - final Label spacer = new Label(group, SWT.NONE | SWT.LEFT); - spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, - false, false, 1, 1)); - - final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT); - infoLabel.setLayoutData(new GridData(GridData.BEGINNING, - GridData.CENTER, false, false, 1, 1)); - infoLabel - .setText("Diese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.\nDiese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar."); - - // Schl�ssel - final Label lblBA = new Label(group, SWT.NONE | SWT.RIGHT); - GridData lblBAGrid = new GridData(GridData.END, GridData.CENTER, false, - false, 1, 1); - lblBAGrid.widthHint = WIDTH_LEFT_COLUMN; - lblBA.setLayoutData(lblBAGrid); - lblBA.setText("Class-Name:"); - - bundleAccessor = new Text(group, SWT.BORDER); - bundleAccessor.setLayoutData(new GridData(GridData.FILL, - GridData.CENTER, true, false, 1, 1)); - - // Resource-Bundle - final Label lblPkg = new Label(group, SWT.NONE); - lblPkg.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, - false, 1, 1)); - lblPkg.setText("Package:"); - - packageName = new Text(group, SWT.BORDER); - packageName.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, - true, false, 1, 1)); - } - - protected void initContent() { - bundleAccessor.setText("BundleAccessor"); - packageName.setText("a.b"); - } - - /* - * protected void constructDefaultSection(Composite parent) { final Group - * group = new Group (parent, SWT.SHADOW_ETCHED_IN); group.setLayoutData(new - * GridData(GridData.FILL, GridData.CENTER, true, true, 1, 1)); - * group.setText("Basis-Text"); - * - * // define grid data for this group GridData gridData = new GridData(); - * gridData.horizontalAlignment = SWT.FILL; - * gridData.grabExcessHorizontalSpace = true; group.setLayoutData(gridData); - * group.setLayout(new GridLayout(2, false)); - * - * final Label spacer = new Label (group, SWT.NONE | SWT.LEFT); - * spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, - * false, false, 1, 1)); - * - * final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT); - * infoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, - * false, false, 1, 1)); infoLabel.setText( - * "Diese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.\nDiese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar." - * ); - * - * // Text final Label lblText = new Label (group, SWT.NONE | SWT.RIGHT); - * GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, false, - * false, 1, 1); lblTextGrid.heightHint = 80; lblTextGrid.widthHint = 100; - * lblText.setLayoutData(lblTextGrid); lblText.setText("Text:"); - * - * txtDefaultText = new Text (group, SWT.MULTI | SWT.BORDER); - * txtDefaultText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, - * true, true, 1, 1)); - * - * // Sprache final Label lblLanguage = new Label (group, SWT.NONE); - * lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, - * false, false, 1, 1)); lblLanguage.setText("Sprache (Land):"); - * - * cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE); - * cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, - * true, false, 1, 1)); } - */ - - @Override - protected void configureShell(Shell newShell) { - super.configureShell(newShell); - newShell.setText("Create Resource-Bundle Accessor"); - } + private static int WIDTH_LEFT_COLUMN = 100; + + private Text bundleAccessor; + private Text packageName; + + public GenerateBundleAccessorDialog(Shell parentShell) { + super(parentShell); + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite dialogArea = (Composite) super.createDialogArea(parent); + initLayout(dialogArea); + constructBASection(dialogArea); + // constructDefaultSection (dialogArea); + initContent(); + return dialogArea; + } + + protected void initLayout(Composite parent) { + final GridLayout layout = new GridLayout(1, true); + parent.setLayout(layout); + } + + protected void constructBASection(Composite parent) { + final Group group = new Group(parent, SWT.SHADOW_ETCHED_IN); + group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, + false, 1, 1)); + group.setText("Resource Bundle"); + + // define grid data for this group + GridData gridData = new GridData(); + gridData.horizontalAlignment = SWT.FILL; + gridData.grabExcessHorizontalSpace = true; + group.setLayoutData(gridData); + group.setLayout(new GridLayout(2, false)); + + final Label spacer = new Label(group, SWT.NONE | SWT.LEFT); + spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, + false, false, 1, 1)); + + final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT); + infoLabel.setLayoutData(new GridData(GridData.BEGINNING, + GridData.CENTER, false, false, 1, 1)); + infoLabel + .setText("Diese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.\nDiese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar."); + + // Schl�ssel + final Label lblBA = new Label(group, SWT.NONE | SWT.RIGHT); + GridData lblBAGrid = new GridData(GridData.END, GridData.CENTER, false, + false, 1, 1); + lblBAGrid.widthHint = WIDTH_LEFT_COLUMN; + lblBA.setLayoutData(lblBAGrid); + lblBA.setText("Class-Name:"); + + bundleAccessor = new Text(group, SWT.BORDER); + bundleAccessor.setLayoutData(new GridData(GridData.FILL, + GridData.CENTER, true, false, 1, 1)); + + // Resource-Bundle + final Label lblPkg = new Label(group, SWT.NONE); + lblPkg.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, + false, 1, 1)); + lblPkg.setText("Package:"); + + packageName = new Text(group, SWT.BORDER); + packageName.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, + true, false, 1, 1)); + } + + protected void initContent() { + bundleAccessor.setText("BundleAccessor"); + packageName.setText("a.b"); + } + + /* + * protected void constructDefaultSection(Composite parent) { final Group + * group = new Group (parent, SWT.SHADOW_ETCHED_IN); group.setLayoutData(new + * GridData(GridData.FILL, GridData.CENTER, true, true, 1, 1)); + * group.setText("Basis-Text"); + * + * // define grid data for this group GridData gridData = new GridData(); + * gridData.horizontalAlignment = SWT.FILL; + * gridData.grabExcessHorizontalSpace = true; group.setLayoutData(gridData); + * group.setLayout(new GridLayout(2, false)); + * + * final Label spacer = new Label (group, SWT.NONE | SWT.LEFT); + * spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, + * false, false, 1, 1)); + * + * final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT); + * infoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, + * false, false, 1, 1)); infoLabel.setText( + * "Diese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar.\nDiese Zeile stellt einen Platzhalter f�r einen kurzen Infotext dar." + * ); + * + * // Text final Label lblText = new Label (group, SWT.NONE | SWT.RIGHT); + * GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, false, + * false, 1, 1); lblTextGrid.heightHint = 80; lblTextGrid.widthHint = 100; + * lblText.setLayoutData(lblTextGrid); lblText.setText("Text:"); + * + * txtDefaultText = new Text (group, SWT.MULTI | SWT.BORDER); + * txtDefaultText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, + * true, true, 1, 1)); + * + * // Sprache final Label lblLanguage = new Label (group, SWT.NONE); + * lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, + * false, false, 1, 1)); lblLanguage.setText("Sprache (Land):"); + * + * cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE); + * cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, + * true, false, 1, 1)); } + */ + + @Override + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText("Create Resource-Bundle Accessor"); + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java index 9c17b28c..2106194a 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -39,424 +39,424 @@ public class QueryResourceBundleEntryDialog extends TitleAreaDialog { - private static int WIDTH_LEFT_COLUMN = 100; - private static int SEARCH_FULLTEXT = 0; - private static int SEARCH_KEY = 1; - - private ResourceBundleManager manager; - private Collection<String> availableBundles; - private int searchOption = SEARCH_FULLTEXT; - private String resourceBundle = ""; - - private Combo cmbRB; - - private Text txtKey; - private Button btSearchText; - private Button btSearchKey; - private Combo cmbLanguage; - private ResourceSelector resourceSelector; - private Text txtPreviewText; - - private Button okButton; - private Button cancelButton; - - /*** DIALOG MODEL ***/ - private String selectedRB = ""; - private String preselectedRB = ""; - private Locale selectedLocale = null; - private String selectedKey = ""; - - public QueryResourceBundleEntryDialog(Shell parentShell, - ResourceBundleManager manager, String bundleName) { - super(parentShell); - this.manager = manager; - // init available resource bundles - this.availableBundles = manager.getResourceBundleNames(); - this.preselectedRB = bundleName; + private static int WIDTH_LEFT_COLUMN = 100; + private static int SEARCH_FULLTEXT = 0; + private static int SEARCH_KEY = 1; + + private ResourceBundleManager manager; + private Collection<String> availableBundles; + private int searchOption = SEARCH_FULLTEXT; + private String resourceBundle = ""; + + private Combo cmbRB; + + private Text txtKey; + private Button btSearchText; + private Button btSearchKey; + private Combo cmbLanguage; + private ResourceSelector resourceSelector; + private Text txtPreviewText; + + private Button okButton; + private Button cancelButton; + + /*** DIALOG MODEL ***/ + private String selectedRB = ""; + private String preselectedRB = ""; + private Locale selectedLocale = null; + private String selectedKey = ""; + + public QueryResourceBundleEntryDialog(Shell parentShell, + ResourceBundleManager manager, String bundleName) { + super(parentShell); + this.manager = manager; + // init available resource bundles + this.availableBundles = manager.getResourceBundleNames(); + this.preselectedRB = bundleName; + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite dialogArea = (Composite) super.createDialogArea(parent); + initLayout(dialogArea); + constructSearchSection(dialogArea); + initContent(); + return dialogArea; + } + + protected void initContent() { + // init available resource bundles + cmbRB.removeAll(); + int i = 0; + for (String bundle : availableBundles) { + cmbRB.add(bundle); + if (bundle.equals(preselectedRB)) { + cmbRB.select(i); + cmbRB.setEnabled(false); + } + i++; } - @Override - protected Control createDialogArea(Composite parent) { - Composite dialogArea = (Composite) super.createDialogArea(parent); - initLayout(dialogArea); - constructSearchSection(dialogArea); - initContent(); - return dialogArea; + if (availableBundles.size() > 0) { + if (preselectedRB.trim().length() == 0) { + cmbRB.select(0); + cmbRB.setEnabled(true); + } } - protected void initContent() { - // init available resource bundles - cmbRB.removeAll(); - int i = 0; - for (String bundle : availableBundles) { - cmbRB.add(bundle); - if (bundle.equals(preselectedRB)) { - cmbRB.select(i); - cmbRB.setEnabled(false); - } - i++; - } - - if (availableBundles.size() > 0) { - if (preselectedRB.trim().length() == 0) { - cmbRB.select(0); - cmbRB.setEnabled(true); - } - } - - cmbRB.addSelectionListener(new SelectionListener() { - - @Override - public void widgetSelected(SelectionEvent e) { - // updateAvailableLanguages(); - updateResourceSelector(); - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - // updateAvailableLanguages(); - updateResourceSelector(); - } - }); + cmbRB.addSelectionListener(new SelectionListener() { - // init available translations + @Override + public void widgetSelected(SelectionEvent e) { // updateAvailableLanguages(); - - // init resource selector updateResourceSelector(); + } - // update search options - updateSearchOptions(); - } - - protected void updateResourceSelector() { - resourceBundle = cmbRB.getText(); - resourceSelector.setResourceBundle(resourceBundle); - } - - protected void updateSearchOptions() { - searchOption = (btSearchKey.getSelection() ? SEARCH_KEY - : SEARCH_FULLTEXT); - // cmbLanguage.setEnabled(searchOption == SEARCH_FULLTEXT); - // lblLanguage.setEnabled(cmbLanguage.getEnabled()); - - // update ResourceSelector - resourceSelector - .setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT - : ResourceSelector.DISPLAY_KEYS); - } - - protected void updateAvailableLanguages() { - cmbLanguage.removeAll(); - String selectedBundle = cmbRB.getText(); - - if (selectedBundle.trim().equals("")) - return; - - // Retrieve available locales for the selected resource-bundle - Set<Locale> locales = manager.getProvidedLocales(selectedBundle); - for (Locale l : locales) { - String displayName = l.getDisplayName(); - if (displayName.equals("")) - displayName = ResourceBundleManager.defaultLocaleTag; - cmbLanguage.add(displayName); - } - - // if (locales.size() > 0) { - // cmbLanguage.select(0); - updateSelectedLocale(); - // } - } - - protected void updateSelectedLocale() { - String selectedBundle = cmbRB.getText(); - - if (selectedBundle.trim().equals("")) - return; - - Set<Locale> locales = manager.getProvidedLocales(selectedBundle); - Iterator<Locale> it = locales.iterator(); - String selectedLocale = cmbLanguage.getText(); - while (it.hasNext()) { - Locale l = it.next(); - if (l.getDisplayName().equals(selectedLocale)) { - resourceSelector.setDisplayLocale(l); - break; - } - } - } - - protected void initLayout(Composite parent) { - final GridLayout layout = new GridLayout(1, true); - parent.setLayout(layout); - } - - protected void constructSearchSection(Composite parent) { - final Group group = new Group(parent, SWT.NONE); - group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, - false, 1, 1)); - group.setText("Resource selection"); - - // define grid data for this group - GridData gridData = new GridData(); - gridData.horizontalAlignment = SWT.FILL; - gridData.grabExcessHorizontalSpace = true; - group.setLayoutData(gridData); - group.setLayout(new GridLayout(2, false)); - // TODO export as help text - - final Label spacer = new Label(group, SWT.NONE | SWT.LEFT); - spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, - false, false, 1, 1)); - - final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT); - GridData infoGrid = new GridData(GridData.BEGINNING, - GridData.BEGINNING, false, false, 1, 1); - infoGrid.heightHint = 70; - infoLabel.setLayoutData(infoGrid); - infoLabel - .setText("Select the resource that needs to be refrenced. This is achieved in two\n" - + "steps. First select the Resource-Bundle in which the resource is located. \n" - + "In a last step you need to choose the required resource."); - - // Resource-Bundle - final Label lblRB = new Label(group, SWT.NONE); - lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, - false, 1, 1)); - lblRB.setText("Resource-Bundle:"); - - cmbRB = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE); - cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, - false, 1, 1)); - cmbRB.addModifyListener(new ModifyListener() { - @Override - public void modifyText(ModifyEvent e) { - selectedRB = cmbRB.getText(); - validate(); - } - }); - - // Search-Options - final Label spacer2 = new Label(group, SWT.NONE | SWT.LEFT); - spacer2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, - false, false, 1, 1)); - - Composite searchOptions = new Composite(group, SWT.NONE); - searchOptions.setLayout(new GridLayout(2, true)); - - btSearchText = new Button(searchOptions, SWT.RADIO); - btSearchText.setText("Full-text"); - btSearchText.setSelection(searchOption == SEARCH_FULLTEXT); - btSearchText.addSelectionListener(new SelectionListener() { - - @Override - public void widgetSelected(SelectionEvent e) { - updateSearchOptions(); - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - updateSearchOptions(); - } - }); - - btSearchKey = new Button(searchOptions, SWT.RADIO); - btSearchKey.setText("Key"); - btSearchKey.setSelection(searchOption == SEARCH_KEY); - btSearchKey.addSelectionListener(new SelectionListener() { - - @Override - public void widgetSelected(SelectionEvent e) { - updateSearchOptions(); - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - updateSearchOptions(); - } - }); - - // Sprache - // lblLanguage = new Label (group, SWT.NONE); - // lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, - // false, false, 1, 1)); - // lblLanguage.setText("Language (Country):"); - // - // cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE); - // cmbLanguage.setLayoutData(new GridData(GridData.FILL, - // GridData.CENTER, true, false, 1, 1)); - // cmbLanguage.addSelectionListener(new SelectionListener () { - // - // @Override - // public void widgetDefaultSelected(SelectionEvent e) { - // updateSelectedLocale(); - // } - // - // @Override - // public void widgetSelected(SelectionEvent e) { - // updateSelectedLocale(); - // } - // - // }); - // cmbLanguage.addModifyListener(new ModifyListener() { - // @Override - // public void modifyText(ModifyEvent e) { - // selectedLocale = - // LocaleUtils.getLocaleByDisplayName(manager.getProvidedLocales(selectedRB), - // cmbLanguage.getText()); - // validate(); - // } - // }); - - // Filter - final Label lblKey = new Label(group, SWT.NONE | SWT.RIGHT); - GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER, - false, false, 1, 1); - lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN; - lblKey.setLayoutData(lblKeyGrid); - lblKey.setText("Filter:"); - - txtKey = new Text(group, SWT.BORDER); - txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, - false, 1, 1)); - - // Add selector for property keys - final Label lblKeys = new Label(group, SWT.NONE); - lblKeys.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, - false, false, 1, 1)); - lblKeys.setText("Resource:"); - - resourceSelector = new ResourceSelector(group, SWT.NONE); - - resourceSelector.setProjectName(manager.getProject().getName()); - resourceSelector.setResourceBundle(cmbRB.getText()); - resourceSelector.setDisplayMode(searchOption); - - GridData resourceSelectionData = new GridData(GridData.FILL, - GridData.CENTER, true, false, 1, 1); - resourceSelectionData.heightHint = 150; - resourceSelectionData.widthHint = 400; - resourceSelector.setLayoutData(resourceSelectionData); - resourceSelector - .addSelectionChangedListener(new IResourceSelectionListener() { - - @Override - public void selectionChanged(ResourceSelectionEvent e) { - selectedKey = e.getSelectedKey(); - updatePreviewLabel(e.getSelectionSummary()); - validate(); - } - }); - - // final Label spacer = new Label (group, SWT.SEPARATOR | - // SWT.HORIZONTAL); - // spacer.setLayoutData(new GridData(GridData.BEGINNING, - // GridData.CENTER, true, false, 2, 1)); - - // Preview - final Label lblText = new Label(group, SWT.NONE | SWT.RIGHT); - GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, - false, false, 1, 1); - lblTextGrid.heightHint = 120; - lblTextGrid.widthHint = 100; - lblText.setLayoutData(lblTextGrid); - lblText.setText("Preview:"); - - txtPreviewText = new Text(group, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL); - txtPreviewText.setEditable(false); - GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL, - true, true, 1, 1); - txtPreviewText.setLayoutData(lblTextGrid2); - } - - @Override - protected void configureShell(Shell newShell) { - super.configureShell(newShell); - newShell.setText("Insert Resource-Bundle-Reference"); + @Override + public void widgetDefaultSelected(SelectionEvent e) { + // updateAvailableLanguages(); + updateResourceSelector(); + } + }); + + // init available translations + // updateAvailableLanguages(); + + // init resource selector + updateResourceSelector(); + + // update search options + updateSearchOptions(); + } + + protected void updateResourceSelector() { + resourceBundle = cmbRB.getText(); + resourceSelector.setResourceBundle(resourceBundle); + } + + protected void updateSearchOptions() { + searchOption = (btSearchKey.getSelection() ? SEARCH_KEY + : SEARCH_FULLTEXT); + // cmbLanguage.setEnabled(searchOption == SEARCH_FULLTEXT); + // lblLanguage.setEnabled(cmbLanguage.getEnabled()); + + // update ResourceSelector + resourceSelector + .setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT + : ResourceSelector.DISPLAY_KEYS); + } + + protected void updateAvailableLanguages() { + cmbLanguage.removeAll(); + String selectedBundle = cmbRB.getText(); + + if (selectedBundle.trim().equals("")) + return; + + // Retrieve available locales for the selected resource-bundle + Set<Locale> locales = manager.getProvidedLocales(selectedBundle); + for (Locale l : locales) { + String displayName = l.getDisplayName(); + if (displayName.equals("")) + displayName = ResourceBundleManager.defaultLocaleTag; + cmbLanguage.add(displayName); } - @Override - public void create() { - // TODO Auto-generated method stub - super.create(); - this.setTitle("Reference a Resource"); - this.setMessage("Please, specify details about the required Resource-Bundle reference"); + // if (locales.size() > 0) { + // cmbLanguage.select(0); + updateSelectedLocale(); + // } + } + + protected void updateSelectedLocale() { + String selectedBundle = cmbRB.getText(); + + if (selectedBundle.trim().equals("")) + return; + + Set<Locale> locales = manager.getProvidedLocales(selectedBundle); + Iterator<Locale> it = locales.iterator(); + String selectedLocale = cmbLanguage.getText(); + while (it.hasNext()) { + Locale l = it.next(); + if (l.getDisplayName().equals(selectedLocale)) { + resourceSelector.setDisplayLocale(l); + break; + } } + } + + protected void initLayout(Composite parent) { + final GridLayout layout = new GridLayout(1, true); + parent.setLayout(layout); + } + + protected void constructSearchSection(Composite parent) { + final Group group = new Group(parent, SWT.NONE); + group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, + false, 1, 1)); + group.setText("Resource selection"); + + // define grid data for this group + GridData gridData = new GridData(); + gridData.horizontalAlignment = SWT.FILL; + gridData.grabExcessHorizontalSpace = true; + group.setLayoutData(gridData); + group.setLayout(new GridLayout(2, false)); + // TODO export as help text + + final Label spacer = new Label(group, SWT.NONE | SWT.LEFT); + spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, + false, false, 1, 1)); + + final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT); + GridData infoGrid = new GridData(GridData.BEGINNING, + GridData.BEGINNING, false, false, 1, 1); + infoGrid.heightHint = 70; + infoLabel.setLayoutData(infoGrid); + infoLabel + .setText("Select the resource that needs to be refrenced. This is achieved in two\n" + + "steps. First select the Resource-Bundle in which the resource is located. \n" + + "In a last step you need to choose the required resource."); + + // Resource-Bundle + final Label lblRB = new Label(group, SWT.NONE); + lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, + false, 1, 1)); + lblRB.setText("Resource-Bundle:"); + + cmbRB = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE); + cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, + false, 1, 1)); + cmbRB.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + selectedRB = cmbRB.getText(); + validate(); + } + }); + + // Search-Options + final Label spacer2 = new Label(group, SWT.NONE | SWT.LEFT); + spacer2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, + false, false, 1, 1)); + + Composite searchOptions = new Composite(group, SWT.NONE); + searchOptions.setLayout(new GridLayout(2, true)); + + btSearchText = new Button(searchOptions, SWT.RADIO); + btSearchText.setText("Full-text"); + btSearchText.setSelection(searchOption == SEARCH_FULLTEXT); + btSearchText.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { + updateSearchOptions(); + } - protected void updatePreviewLabel(String previewText) { - txtPreviewText.setText(previewText); - } + @Override + public void widgetDefaultSelected(SelectionEvent e) { + updateSearchOptions(); + } + }); - protected void validate() { - // Check Resource-Bundle ids - boolean rbValid = false; - boolean localeValid = false; - boolean keyValid = false; - - for (String rbId : this.availableBundles) { - if (rbId.equals(selectedRB)) { - rbValid = true; - break; - } - } - - if (selectedLocale != null) - localeValid = true; - - if (manager.isResourceExisting(selectedRB, selectedKey)) - keyValid = true; - - // print Validation summary - String errorMessage = null; - if (!rbValid) - errorMessage = "The specified Resource-Bundle does not exist"; - // else if (! localeValid) - // errorMessage = - // "The specified Locale does not exist for the selecte Resource-Bundle"; - else if (!keyValid) - errorMessage = "No resource selected"; - else { - if (okButton != null) - okButton.setEnabled(true); - } - - setErrorMessage(errorMessage); - if (okButton != null && errorMessage != null) - okButton.setEnabled(false); - } + btSearchKey = new Button(searchOptions, SWT.RADIO); + btSearchKey.setText("Key"); + btSearchKey.setSelection(searchOption == SEARCH_KEY); + btSearchKey.addSelectionListener(new SelectionListener() { - @Override - protected void createButtonsForButtonBar(Composite parent) { - okButton = createButton(parent, OK, "Ok", true); - okButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - // Set return code - setReturnCode(OK); - close(); - } - }); + @Override + public void widgetSelected(SelectionEvent e) { + updateSearchOptions(); + } - cancelButton = createButton(parent, CANCEL, "Cancel", false); - cancelButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - setReturnCode(CANCEL); - close(); - } + @Override + public void widgetDefaultSelected(SelectionEvent e) { + updateSearchOptions(); + } + }); + + // Sprache + // lblLanguage = new Label (group, SWT.NONE); + // lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, + // false, false, 1, 1)); + // lblLanguage.setText("Language (Country):"); + // + // cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE); + // cmbLanguage.setLayoutData(new GridData(GridData.FILL, + // GridData.CENTER, true, false, 1, 1)); + // cmbLanguage.addSelectionListener(new SelectionListener () { + // + // @Override + // public void widgetDefaultSelected(SelectionEvent e) { + // updateSelectedLocale(); + // } + // + // @Override + // public void widgetSelected(SelectionEvent e) { + // updateSelectedLocale(); + // } + // + // }); + // cmbLanguage.addModifyListener(new ModifyListener() { + // @Override + // public void modifyText(ModifyEvent e) { + // selectedLocale = + // LocaleUtils.getLocaleByDisplayName(manager.getProvidedLocales(selectedRB), + // cmbLanguage.getText()); + // validate(); + // } + // }); + + // Filter + final Label lblKey = new Label(group, SWT.NONE | SWT.RIGHT); + GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER, + false, false, 1, 1); + lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN; + lblKey.setLayoutData(lblKeyGrid); + lblKey.setText("Filter:"); + + txtKey = new Text(group, SWT.BORDER); + txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, + false, 1, 1)); + + // Add selector for property keys + final Label lblKeys = new Label(group, SWT.NONE); + lblKeys.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, + false, false, 1, 1)); + lblKeys.setText("Resource:"); + + resourceSelector = new ResourceSelector(group, SWT.NONE); + + resourceSelector.setProjectName(manager.getProject().getName()); + resourceSelector.setResourceBundle(cmbRB.getText()); + resourceSelector.setDisplayMode(searchOption); + + GridData resourceSelectionData = new GridData(GridData.FILL, + GridData.CENTER, true, false, 1, 1); + resourceSelectionData.heightHint = 150; + resourceSelectionData.widthHint = 400; + resourceSelector.setLayoutData(resourceSelectionData); + resourceSelector + .addSelectionChangedListener(new IResourceSelectionListener() { + + @Override + public void selectionChanged(ResourceSelectionEvent e) { + selectedKey = e.getSelectedKey(); + updatePreviewLabel(e.getSelectionSummary()); + validate(); + } }); - okButton.setEnabled(false); - cancelButton.setEnabled(true); + // final Label spacer = new Label (group, SWT.SEPARATOR | + // SWT.HORIZONTAL); + // spacer.setLayoutData(new GridData(GridData.BEGINNING, + // GridData.CENTER, true, false, 2, 1)); + + // Preview + final Label lblText = new Label(group, SWT.NONE | SWT.RIGHT); + GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, + false, false, 1, 1); + lblTextGrid.heightHint = 120; + lblTextGrid.widthHint = 100; + lblText.setLayoutData(lblTextGrid); + lblText.setText("Preview:"); + + txtPreviewText = new Text(group, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL); + txtPreviewText.setEditable(false); + GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL, + true, true, 1, 1); + txtPreviewText.setLayoutData(lblTextGrid2); + } + + @Override + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText("Insert Resource-Bundle-Reference"); + } + + @Override + public void create() { + // TODO Auto-generated method stub + super.create(); + this.setTitle("Reference a Resource"); + this.setMessage("Please, specify details about the required Resource-Bundle reference"); + } + + protected void updatePreviewLabel(String previewText) { + txtPreviewText.setText(previewText); + } + + protected void validate() { + // Check Resource-Bundle ids + boolean rbValid = false; + boolean localeValid = false; + boolean keyValid = false; + + for (String rbId : this.availableBundles) { + if (rbId.equals(selectedRB)) { + rbValid = true; + break; + } } - public String getSelectedResourceBundle() { - return selectedRB; + if (selectedLocale != null) + localeValid = true; + + if (manager.isResourceExisting(selectedRB, selectedKey)) + keyValid = true; + + // print Validation summary + String errorMessage = null; + if (!rbValid) + errorMessage = "The specified Resource-Bundle does not exist"; + // else if (! localeValid) + // errorMessage = + // "The specified Locale does not exist for the selecte Resource-Bundle"; + else if (!keyValid) + errorMessage = "No resource selected"; + else { + if (okButton != null) + okButton.setEnabled(true); } - public String getSelectedResource() { - return selectedKey; - } - - public Locale getSelectedLocale() { - return selectedLocale; - } + setErrorMessage(errorMessage); + if (okButton != null && errorMessage != null) + okButton.setEnabled(false); + } + + @Override + protected void createButtonsForButtonBar(Composite parent) { + okButton = createButton(parent, OK, "Ok", true); + okButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + // Set return code + setReturnCode(OK); + close(); + } + }); + + cancelButton = createButton(parent, CANCEL, "Cancel", false); + cancelButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + setReturnCode(CANCEL); + close(); + } + }); + + okButton.setEnabled(false); + cancelButton.setEnabled(true); + } + + public String getSelectedResourceBundle() { + return selectedRB; + } + + public String getSelectedResource() { + return selectedKey; + } + + public Locale getSelectedLocale() { + return selectedLocale; + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java index 17b8721c..b9a8d818 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -25,99 +25,99 @@ import org.eclipse.ui.dialogs.ListDialog; public class RemoveLanguageDialoge extends ListDialog { - private IProject project; - - public RemoveLanguageDialoge(IProject project, Shell shell) { - super(shell); - this.project = project; - - initDialog(); + private IProject project; + + public RemoveLanguageDialoge(IProject project, Shell shell) { + super(shell); + this.project = project; + + initDialog(); + } + + protected void initDialog() { + this.setAddCancelButton(true); + this.setMessage("Select one of the following languages to delete:"); + this.setTitle("Language Selector"); + this.setContentProvider(new RBContentProvider()); + this.setLabelProvider(new RBLabelProvider()); + + this.setInput(ResourceBundleManager.getManager(project) + .getProjectProvidedLocales()); + } + + public Locale getSelectedLanguage() { + Object[] selection = this.getResult(); + if (selection != null && selection.length > 0) + return (Locale) selection[0]; + return null; + } + + // private + // classes------------------------------------------------------------------------------------- + class RBContentProvider implements IStructuredContentProvider { + + @Override + public Object[] getElements(Object inputElement) { + Set<Locale> resources = (Set<Locale>) inputElement; + return resources.toArray(); } - protected void initDialog() { - this.setAddCancelButton(true); - this.setMessage("Select one of the following languages to delete:"); - this.setTitle("Language Selector"); - this.setContentProvider(new RBContentProvider()); - this.setLabelProvider(new RBLabelProvider()); - - this.setInput(ResourceBundleManager.getManager(project) - .getProjectProvidedLocales()); - } + @Override + public void dispose() { + // TODO Auto-generated method stub - public Locale getSelectedLanguage() { - Object[] selection = this.getResult(); - if (selection != null && selection.length > 0) - return (Locale) selection[0]; - return null; } - // private - // classes------------------------------------------------------------------------------------- - class RBContentProvider implements IStructuredContentProvider { - - @Override - public Object[] getElements(Object inputElement) { - Set<Locale> resources = (Set<Locale>) inputElement; - return resources.toArray(); - } - - @Override - public void dispose() { - // TODO Auto-generated method stub - - } - - @Override - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - // TODO Auto-generated method stub - - } + @Override + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + // TODO Auto-generated method stub } - class RBLabelProvider implements ILabelProvider { + } - @Override - public Image getImage(Object element) { - return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE); - } + class RBLabelProvider implements ILabelProvider { - @Override - public String getText(Object element) { - Locale l = ((Locale) element); - String text = l.getDisplayName(); - if (text == null || text.equals("")) - text = "default"; - else - text += " - " + l.getLanguage() + " " + l.getCountry() + " " - + l.getVariant(); - return text; - } + @Override + public Image getImage(Object element) { + return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE); + } - @Override - public void addListener(ILabelProviderListener listener) { - // TODO Auto-generated method stub + @Override + public String getText(Object element) { + Locale l = ((Locale) element); + String text = l.getDisplayName(); + if (text == null || text.equals("")) + text = "default"; + else + text += " - " + l.getLanguage() + " " + l.getCountry() + " " + + l.getVariant(); + return text; + } - } + @Override + public void addListener(ILabelProviderListener listener) { + // TODO Auto-generated method stub - @Override - public void dispose() { - // TODO Auto-generated method stub + } - } + @Override + public void dispose() { + // TODO Auto-generated method stub - @Override - public boolean isLabelProperty(Object element, String property) { - // TODO Auto-generated method stub - return false; - } + } - @Override - public void removeListener(ILabelProviderListener listener) { - // TODO Auto-generated method stub + @Override + public boolean isLabelProperty(Object element, String property) { + // TODO Auto-generated method stub + return false; + } - } + @Override + public void removeListener(ILabelProviderListener listener) { + // TODO Auto-generated method stub } + + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java index d204f767..9d2895a8 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -38,437 +38,437 @@ public class ResourceBundleEntrySelectionDialog extends TitleAreaDialog { - private static int WIDTH_LEFT_COLUMN = 100; - private static int SEARCH_FULLTEXT = 0; - private static int SEARCH_KEY = 1; - - private String projectName; - private String bundleName; - - private int searchOption = SEARCH_FULLTEXT; - private String resourceBundle = ""; - - private Combo cmbRB; - - private Button btSearchText; - private Button btSearchKey; - private Combo cmbLanguage; - private ResourceSelector resourceSelector; - private Text txtPreviewText; - - private Button okButton; - private Button cancelButton; - - /*** DIALOG MODEL ***/ - private String selectedRB = ""; - private String preselectedRB = ""; - private Locale selectedLocale = null; - private String selectedKey = ""; - - public ResourceBundleEntrySelectionDialog(Shell parentShell) { - super(parentShell); + private static int WIDTH_LEFT_COLUMN = 100; + private static int SEARCH_FULLTEXT = 0; + private static int SEARCH_KEY = 1; + + private String projectName; + private String bundleName; + + private int searchOption = SEARCH_FULLTEXT; + private String resourceBundle = ""; + + private Combo cmbRB; + + private Button btSearchText; + private Button btSearchKey; + private Combo cmbLanguage; + private ResourceSelector resourceSelector; + private Text txtPreviewText; + + private Button okButton; + private Button cancelButton; + + /*** DIALOG MODEL ***/ + private String selectedRB = ""; + private String preselectedRB = ""; + private Locale selectedLocale = null; + private String selectedKey = ""; + + public ResourceBundleEntrySelectionDialog(Shell parentShell) { + super(parentShell); + } + + @Override + protected Control createDialogArea(Composite parent) { + Composite dialogArea = (Composite) super.createDialogArea(parent); + initLayout(dialogArea); + constructSearchSection(dialogArea); + initContent(); + return dialogArea; + } + + protected void initContent() { + // init available resource bundles + cmbRB.removeAll(); + int i = 0; + for (String bundle : ResourceBundleManager.getManager(projectName) + .getResourceBundleNames()) { + cmbRB.add(bundle); + if (bundle.equals(preselectedRB)) { + cmbRB.select(i); + cmbRB.setEnabled(false); + } + i++; } - @Override - protected Control createDialogArea(Composite parent) { - Composite dialogArea = (Composite) super.createDialogArea(parent); - initLayout(dialogArea); - constructSearchSection(dialogArea); - initContent(); - return dialogArea; + if (ResourceBundleManager.getManager(projectName) + .getResourceBundleNames().size() > 0) { + if (preselectedRB.trim().length() == 0) { + cmbRB.select(0); + cmbRB.setEnabled(true); + } } - protected void initContent() { - // init available resource bundles - cmbRB.removeAll(); - int i = 0; - for (String bundle : ResourceBundleManager.getManager(projectName) - .getResourceBundleNames()) { - cmbRB.add(bundle); - if (bundle.equals(preselectedRB)) { - cmbRB.select(i); - cmbRB.setEnabled(false); - } - i++; - } - - if (ResourceBundleManager.getManager(projectName) - .getResourceBundleNames().size() > 0) { - if (preselectedRB.trim().length() == 0) { - cmbRB.select(0); - cmbRB.setEnabled(true); - } - } - - cmbRB.addSelectionListener(new SelectionListener() { - - @Override - public void widgetSelected(SelectionEvent e) { - // updateAvailableLanguages(); - updateResourceSelector(); - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - // updateAvailableLanguages(); - updateResourceSelector(); - } - }); + cmbRB.addSelectionListener(new SelectionListener() { - // init available translations + @Override + public void widgetSelected(SelectionEvent e) { // updateAvailableLanguages(); - - // init resource selector updateResourceSelector(); + } - // update search options - updateSearchOptions(); - } - - protected void updateResourceSelector() { - resourceBundle = cmbRB.getText(); - resourceSelector.setResourceBundle(resourceBundle); - } - - protected void updateSearchOptions() { - searchOption = (btSearchKey.getSelection() ? SEARCH_KEY - : SEARCH_FULLTEXT); - // cmbLanguage.setEnabled(searchOption == SEARCH_FULLTEXT); - // lblLanguage.setEnabled(cmbLanguage.getEnabled()); - - // update ResourceSelector - resourceSelector - .setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT - : ResourceSelector.DISPLAY_KEYS); - } - - protected void updateAvailableLanguages() { - cmbLanguage.removeAll(); - String selectedBundle = cmbRB.getText(); - - if (selectedBundle.trim().equals("")) - return; - - // Retrieve available locales for the selected resource-bundle - Set<Locale> locales = ResourceBundleManager.getManager(projectName) - .getProvidedLocales(selectedBundle); - for (Locale l : locales) { - String displayName = l.getDisplayName(); - if (displayName.equals("")) - displayName = ResourceBundleManager.defaultLocaleTag; - cmbLanguage.add(displayName); - } - - // if (locales.size() > 0) { - // cmbLanguage.select(0); - updateSelectedLocale(); - // } - } - - protected void updateSelectedLocale() { - String selectedBundle = cmbRB.getText(); - - if (selectedBundle.trim().equals("")) - return; - - Set<Locale> locales = ResourceBundleManager.getManager(projectName) - .getProvidedLocales(selectedBundle); - Iterator<Locale> it = locales.iterator(); - String selectedLocale = cmbLanguage.getText(); - while (it.hasNext()) { - Locale l = it.next(); - if (l.getDisplayName().equals(selectedLocale)) { - resourceSelector.setDisplayLocale(l); - break; - } - } - } - - protected void initLayout(Composite parent) { - final GridLayout layout = new GridLayout(1, true); - parent.setLayout(layout); - } - - protected void constructSearchSection(Composite parent) { - final Group group = new Group(parent, SWT.NONE); - group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, - false, 1, 1)); - group.setText("Resource selection"); - - // define grid data for this group - GridData gridData = new GridData(); - gridData.horizontalAlignment = SWT.FILL; - gridData.grabExcessHorizontalSpace = true; - group.setLayoutData(gridData); - group.setLayout(new GridLayout(2, false)); - // TODO export as help text - - final Label spacer = new Label(group, SWT.NONE | SWT.LEFT); - spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, - false, false, 1, 1)); - - final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT); - GridData infoGrid = new GridData(GridData.BEGINNING, - GridData.BEGINNING, false, false, 1, 1); - infoGrid.heightHint = 70; - infoLabel.setLayoutData(infoGrid); - infoLabel - .setText("Select the resource that needs to be refrenced. This is accomplished in two\n" - + "steps. First select the Resource-Bundle in which the resource is located. \n" - + "In a last step you need to choose a particular resource."); - - // Resource-Bundle - final Label lblRB = new Label(group, SWT.NONE); - lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, - false, 1, 1)); - lblRB.setText("Resource-Bundle:"); - - cmbRB = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE); - cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, - false, 1, 1)); - cmbRB.addModifyListener(new ModifyListener() { - @Override - public void modifyText(ModifyEvent e) { - selectedRB = cmbRB.getText(); - validate(); - } - }); - - // Search-Options - final Label spacer2 = new Label(group, SWT.NONE | SWT.LEFT); - spacer2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, - false, false, 1, 1)); - - Composite searchOptions = new Composite(group, SWT.NONE); - searchOptions.setLayout(new GridLayout(2, true)); - - btSearchText = new Button(searchOptions, SWT.RADIO); - btSearchText.setText("Flat"); - btSearchText.setSelection(searchOption == SEARCH_FULLTEXT); - btSearchText.addSelectionListener(new SelectionListener() { - - @Override - public void widgetSelected(SelectionEvent e) { - updateSearchOptions(); - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - updateSearchOptions(); - } - }); - - btSearchKey = new Button(searchOptions, SWT.RADIO); - btSearchKey.setText("Hierarchical"); - btSearchKey.setSelection(searchOption == SEARCH_KEY); - btSearchKey.addSelectionListener(new SelectionListener() { - - @Override - public void widgetSelected(SelectionEvent e) { - updateSearchOptions(); - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - updateSearchOptions(); - } - }); - - // Sprache - // lblLanguage = new Label (group, SWT.NONE); - // lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, - // false, false, 1, 1)); - // lblLanguage.setText("Language (Country):"); - // - // cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE); - // cmbLanguage.setLayoutData(new GridData(GridData.FILL, - // GridData.CENTER, true, false, 1, 1)); - // cmbLanguage.addSelectionListener(new SelectionListener () { - // - // @Override - // public void widgetDefaultSelected(SelectionEvent e) { - // updateSelectedLocale(); - // } - // - // @Override - // public void widgetSelected(SelectionEvent e) { - // updateSelectedLocale(); - // } - // - // }); - // cmbLanguage.addModifyListener(new ModifyListener() { - // @Override - // public void modifyText(ModifyEvent e) { - // selectedLocale = - // LocaleUtils.getLocaleByDisplayName(manager.getProvidedLocales(selectedRB), - // cmbLanguage.getText()); - // validate(); - // } - // }); - - // Filter - // final Label lblKey = new Label (group, SWT.NONE | SWT.RIGHT); - // GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER, - // false, false, 1, 1); - // lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN; - // lblKey.setLayoutData(lblKeyGrid); - // lblKey.setText("Filter:"); - // - // txtKey = new Text (group, SWT.BORDER); - // txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, - // true, false, 1, 1)); - - // Add selector for property keys - final Label lblKeys = new Label(group, SWT.NONE); - lblKeys.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, - false, false, 1, 1)); - lblKeys.setText("Resource:"); - - resourceSelector = new ResourceSelector(group, SWT.NONE); - - resourceSelector.setProjectName(projectName); - resourceSelector.setResourceBundle(cmbRB.getText()); - resourceSelector.setDisplayMode(searchOption); - - GridData resourceSelectionData = new GridData(GridData.FILL, - GridData.CENTER, true, false, 1, 1); - resourceSelectionData.heightHint = 150; - resourceSelectionData.widthHint = 400; - resourceSelector.setLayoutData(resourceSelectionData); - resourceSelector - .addSelectionChangedListener(new IResourceSelectionListener() { - - @Override - public void selectionChanged(ResourceSelectionEvent e) { - selectedKey = e.getSelectedKey(); - updatePreviewLabel(e.getSelectionSummary()); - validate(); - } - }); - - // final Label spacer = new Label (group, SWT.SEPARATOR | - // SWT.HORIZONTAL); - // spacer.setLayoutData(new GridData(GridData.BEGINNING, - // GridData.CENTER, true, false, 2, 1)); - - // Preview - final Label lblText = new Label(group, SWT.NONE | SWT.RIGHT); - GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, - false, false, 1, 1); - lblTextGrid.heightHint = 120; - lblTextGrid.widthHint = 100; - lblText.setLayoutData(lblTextGrid); - lblText.setText("Preview:"); - - txtPreviewText = new Text(group, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL); - txtPreviewText.setEditable(false); - GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL, - true, true, 1, 1); - txtPreviewText.setLayoutData(lblTextGrid2); - } - - @Override - protected void configureShell(Shell newShell) { - super.configureShell(newShell); - newShell.setText("Select Resource-Bundle entry"); + @Override + public void widgetDefaultSelected(SelectionEvent e) { + // updateAvailableLanguages(); + updateResourceSelector(); + } + }); + + // init available translations + // updateAvailableLanguages(); + + // init resource selector + updateResourceSelector(); + + // update search options + updateSearchOptions(); + } + + protected void updateResourceSelector() { + resourceBundle = cmbRB.getText(); + resourceSelector.setResourceBundle(resourceBundle); + } + + protected void updateSearchOptions() { + searchOption = (btSearchKey.getSelection() ? SEARCH_KEY + : SEARCH_FULLTEXT); + // cmbLanguage.setEnabled(searchOption == SEARCH_FULLTEXT); + // lblLanguage.setEnabled(cmbLanguage.getEnabled()); + + // update ResourceSelector + resourceSelector + .setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT + : ResourceSelector.DISPLAY_KEYS); + } + + protected void updateAvailableLanguages() { + cmbLanguage.removeAll(); + String selectedBundle = cmbRB.getText(); + + if (selectedBundle.trim().equals("")) + return; + + // Retrieve available locales for the selected resource-bundle + Set<Locale> locales = ResourceBundleManager.getManager(projectName) + .getProvidedLocales(selectedBundle); + for (Locale l : locales) { + String displayName = l.getDisplayName(); + if (displayName.equals("")) + displayName = ResourceBundleManager.defaultLocaleTag; + cmbLanguage.add(displayName); } - @Override - public void create() { - // TODO Auto-generated method stub - super.create(); - this.setTitle("Select a Resource-Bundle entry"); - this.setMessage("Please, select a resource of a particular Resource-Bundle"); + // if (locales.size() > 0) { + // cmbLanguage.select(0); + updateSelectedLocale(); + // } + } + + protected void updateSelectedLocale() { + String selectedBundle = cmbRB.getText(); + + if (selectedBundle.trim().equals("")) + return; + + Set<Locale> locales = ResourceBundleManager.getManager(projectName) + .getProvidedLocales(selectedBundle); + Iterator<Locale> it = locales.iterator(); + String selectedLocale = cmbLanguage.getText(); + while (it.hasNext()) { + Locale l = it.next(); + if (l.getDisplayName().equals(selectedLocale)) { + resourceSelector.setDisplayLocale(l); + break; + } } + } + + protected void initLayout(Composite parent) { + final GridLayout layout = new GridLayout(1, true); + parent.setLayout(layout); + } + + protected void constructSearchSection(Composite parent) { + final Group group = new Group(parent, SWT.NONE); + group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, + false, 1, 1)); + group.setText("Resource selection"); + + // define grid data for this group + GridData gridData = new GridData(); + gridData.horizontalAlignment = SWT.FILL; + gridData.grabExcessHorizontalSpace = true; + group.setLayoutData(gridData); + group.setLayout(new GridLayout(2, false)); + // TODO export as help text + + final Label spacer = new Label(group, SWT.NONE | SWT.LEFT); + spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, + false, false, 1, 1)); + + final Label infoLabel = new Label(group, SWT.NONE | SWT.LEFT); + GridData infoGrid = new GridData(GridData.BEGINNING, + GridData.BEGINNING, false, false, 1, 1); + infoGrid.heightHint = 70; + infoLabel.setLayoutData(infoGrid); + infoLabel + .setText("Select the resource that needs to be refrenced. This is accomplished in two\n" + + "steps. First select the Resource-Bundle in which the resource is located. \n" + + "In a last step you need to choose a particular resource."); + + // Resource-Bundle + final Label lblRB = new Label(group, SWT.NONE); + lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, + false, 1, 1)); + lblRB.setText("Resource-Bundle:"); + + cmbRB = new Combo(group, SWT.DROP_DOWN | SWT.SIMPLE); + cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, + false, 1, 1)); + cmbRB.addModifyListener(new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + selectedRB = cmbRB.getText(); + validate(); + } + }); + + // Search-Options + final Label spacer2 = new Label(group, SWT.NONE | SWT.LEFT); + spacer2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, + false, false, 1, 1)); + + Composite searchOptions = new Composite(group, SWT.NONE); + searchOptions.setLayout(new GridLayout(2, true)); + + btSearchText = new Button(searchOptions, SWT.RADIO); + btSearchText.setText("Flat"); + btSearchText.setSelection(searchOption == SEARCH_FULLTEXT); + btSearchText.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { + updateSearchOptions(); + } - protected void updatePreviewLabel(String previewText) { - txtPreviewText.setText(previewText); - } + @Override + public void widgetDefaultSelected(SelectionEvent e) { + updateSearchOptions(); + } + }); - protected void validate() { - // Check Resource-Bundle ids - boolean rbValid = false; - boolean localeValid = false; - boolean keyValid = false; - - for (String rbId : ResourceBundleManager.getManager(projectName) - .getResourceBundleNames()) { - if (rbId.equals(selectedRB)) { - rbValid = true; - break; - } - } - - if (selectedLocale != null) - localeValid = true; - - if (ResourceBundleManager.getManager(projectName).isResourceExisting( - selectedRB, selectedKey)) - keyValid = true; - - // print Validation summary - String errorMessage = null; - if (!rbValid) - errorMessage = "The specified Resource-Bundle does not exist"; - // else if (! localeValid) - // errorMessage = - // "The specified Locale does not exist for the selecte Resource-Bundle"; - else if (!keyValid) - errorMessage = "No resource selected"; - else { - if (okButton != null) - okButton.setEnabled(true); - } - - setErrorMessage(errorMessage); - if (okButton != null && errorMessage != null) - okButton.setEnabled(false); - } + btSearchKey = new Button(searchOptions, SWT.RADIO); + btSearchKey.setText("Hierarchical"); + btSearchKey.setSelection(searchOption == SEARCH_KEY); + btSearchKey.addSelectionListener(new SelectionListener() { - @Override - protected void createButtonsForButtonBar(Composite parent) { - okButton = createButton(parent, OK, "Ok", true); - okButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - // Set return code - setReturnCode(OK); - close(); - } - }); + @Override + public void widgetSelected(SelectionEvent e) { + updateSearchOptions(); + } - cancelButton = createButton(parent, CANCEL, "Cancel", false); - cancelButton.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - setReturnCode(CANCEL); - close(); - } + @Override + public void widgetDefaultSelected(SelectionEvent e) { + updateSearchOptions(); + } + }); + + // Sprache + // lblLanguage = new Label (group, SWT.NONE); + // lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, + // false, false, 1, 1)); + // lblLanguage.setText("Language (Country):"); + // + // cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE); + // cmbLanguage.setLayoutData(new GridData(GridData.FILL, + // GridData.CENTER, true, false, 1, 1)); + // cmbLanguage.addSelectionListener(new SelectionListener () { + // + // @Override + // public void widgetDefaultSelected(SelectionEvent e) { + // updateSelectedLocale(); + // } + // + // @Override + // public void widgetSelected(SelectionEvent e) { + // updateSelectedLocale(); + // } + // + // }); + // cmbLanguage.addModifyListener(new ModifyListener() { + // @Override + // public void modifyText(ModifyEvent e) { + // selectedLocale = + // LocaleUtils.getLocaleByDisplayName(manager.getProvidedLocales(selectedRB), + // cmbLanguage.getText()); + // validate(); + // } + // }); + + // Filter + // final Label lblKey = new Label (group, SWT.NONE | SWT.RIGHT); + // GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER, + // false, false, 1, 1); + // lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN; + // lblKey.setLayoutData(lblKeyGrid); + // lblKey.setText("Filter:"); + // + // txtKey = new Text (group, SWT.BORDER); + // txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, + // true, false, 1, 1)); + + // Add selector for property keys + final Label lblKeys = new Label(group, SWT.NONE); + lblKeys.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, + false, false, 1, 1)); + lblKeys.setText("Resource:"); + + resourceSelector = new ResourceSelector(group, SWT.NONE); + + resourceSelector.setProjectName(projectName); + resourceSelector.setResourceBundle(cmbRB.getText()); + resourceSelector.setDisplayMode(searchOption); + + GridData resourceSelectionData = new GridData(GridData.FILL, + GridData.CENTER, true, false, 1, 1); + resourceSelectionData.heightHint = 150; + resourceSelectionData.widthHint = 400; + resourceSelector.setLayoutData(resourceSelectionData); + resourceSelector + .addSelectionChangedListener(new IResourceSelectionListener() { + + @Override + public void selectionChanged(ResourceSelectionEvent e) { + selectedKey = e.getSelectedKey(); + updatePreviewLabel(e.getSelectionSummary()); + validate(); + } }); - okButton.setEnabled(false); - cancelButton.setEnabled(true); + // final Label spacer = new Label (group, SWT.SEPARATOR | + // SWT.HORIZONTAL); + // spacer.setLayoutData(new GridData(GridData.BEGINNING, + // GridData.CENTER, true, false, 2, 1)); + + // Preview + final Label lblText = new Label(group, SWT.NONE | SWT.RIGHT); + GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, + false, false, 1, 1); + lblTextGrid.heightHint = 120; + lblTextGrid.widthHint = 100; + lblText.setLayoutData(lblTextGrid); + lblText.setText("Preview:"); + + txtPreviewText = new Text(group, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL); + txtPreviewText.setEditable(false); + GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL, + true, true, 1, 1); + txtPreviewText.setLayoutData(lblTextGrid2); + } + + @Override + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText("Select Resource-Bundle entry"); + } + + @Override + public void create() { + // TODO Auto-generated method stub + super.create(); + this.setTitle("Select a Resource-Bundle entry"); + this.setMessage("Please, select a resource of a particular Resource-Bundle"); + } + + protected void updatePreviewLabel(String previewText) { + txtPreviewText.setText(previewText); + } + + protected void validate() { + // Check Resource-Bundle ids + boolean rbValid = false; + boolean localeValid = false; + boolean keyValid = false; + + for (String rbId : ResourceBundleManager.getManager(projectName) + .getResourceBundleNames()) { + if (rbId.equals(selectedRB)) { + rbValid = true; + break; + } } - public String getSelectedResourceBundle() { - return selectedRB; + if (selectedLocale != null) + localeValid = true; + + if (ResourceBundleManager.getManager(projectName).isResourceExisting( + selectedRB, selectedKey)) + keyValid = true; + + // print Validation summary + String errorMessage = null; + if (!rbValid) + errorMessage = "The specified Resource-Bundle does not exist"; + // else if (! localeValid) + // errorMessage = + // "The specified Locale does not exist for the selecte Resource-Bundle"; + else if (!keyValid) + errorMessage = "No resource selected"; + else { + if (okButton != null) + okButton.setEnabled(true); } - public String getSelectedResource() { - return selectedKey; - } - - public Locale getSelectedLocale() { - return selectedLocale; - } - - public void setProjectName(String projectName) { - this.projectName = projectName; - } - - public void setBundleName(String bundleName) { - this.bundleName = bundleName; - - if (preselectedRB.isEmpty()) { - preselectedRB = this.bundleName; - } + setErrorMessage(errorMessage); + if (okButton != null && errorMessage != null) + okButton.setEnabled(false); + } + + @Override + protected void createButtonsForButtonBar(Composite parent) { + okButton = createButton(parent, OK, "Ok", true); + okButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + // Set return code + setReturnCode(OK); + close(); + } + }); + + cancelButton = createButton(parent, CANCEL, "Cancel", false); + cancelButton.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent e) { + setReturnCode(CANCEL); + close(); + } + }); + + okButton.setEnabled(false); + cancelButton.setEnabled(true); + } + + public String getSelectedResourceBundle() { + return selectedRB; + } + + public String getSelectedResource() { + return selectedKey; + } + + public Locale getSelectedLocale() { + return selectedLocale; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public void setBundleName(String bundleName) { + this.bundleName = bundleName; + + if (preselectedRB.isEmpty()) { + preselectedRB = this.bundleName; } + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java index c01fb367..de01395f 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Martin Reiterer, Matthias Lettmayer. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -26,96 +26,96 @@ public class ResourceBundleSelectionDialog extends ListDialog { - private IProject project; - - public ResourceBundleSelectionDialog(Shell parent, IProject project) { - super(parent); - this.project = project; - - initDialog(); + private IProject project; + + public ResourceBundleSelectionDialog(Shell parent, IProject project) { + super(parent); + this.project = project; + + initDialog(); + } + + protected void initDialog() { + this.setAddCancelButton(true); + this.setMessage("Select one of the following Resource-Bundle to open:"); + this.setTitle("Resource-Bundle Selector"); + this.setContentProvider(new RBContentProvider()); + this.setLabelProvider(new RBLabelProvider()); + this.setBlockOnOpen(true); + + if (project != null) + this.setInput(RBManager.getInstance(project) + .getMessagesBundleGroupNames()); + else + this.setInput(RBManager.getAllMessagesBundleGroupNames()); + } + + public String getSelectedBundleId() { + Object[] selection = this.getResult(); + if (selection != null && selection.length > 0) + return (String) selection[0]; + return null; + } + + class RBContentProvider implements IStructuredContentProvider { + + @Override + public Object[] getElements(Object inputElement) { + List<String> resources = (List<String>) inputElement; + return resources.toArray(); } - protected void initDialog() { - this.setAddCancelButton(true); - this.setMessage("Select one of the following Resource-Bundle to open:"); - this.setTitle("Resource-Bundle Selector"); - this.setContentProvider(new RBContentProvider()); - this.setLabelProvider(new RBLabelProvider()); - this.setBlockOnOpen(true); - - if (project != null) - this.setInput(RBManager.getInstance(project) - .getMessagesBundleGroupNames()); - else - this.setInput(RBManager.getAllMessagesBundleGroupNames()); - } + @Override + public void dispose() { + // TODO Auto-generated method stub - public String getSelectedBundleId() { - Object[] selection = this.getResult(); - if (selection != null && selection.length > 0) - return (String) selection[0]; - return null; } - class RBContentProvider implements IStructuredContentProvider { - - @Override - public Object[] getElements(Object inputElement) { - List<String> resources = (List<String>) inputElement; - return resources.toArray(); - } - - @Override - public void dispose() { - // TODO Auto-generated method stub - - } - - @Override - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - // TODO Auto-generated method stub - - } + @Override + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + // TODO Auto-generated method stub } - class RBLabelProvider implements ILabelProvider { + } - @Override - public Image getImage(Object element) { - // TODO Auto-generated method stub - return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE); - } + class RBLabelProvider implements ILabelProvider { - @Override - public String getText(Object element) { - // TODO Auto-generated method stub - return ((String) element); - } + @Override + public Image getImage(Object element) { + // TODO Auto-generated method stub + return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE); + } - @Override - public void addListener(ILabelProviderListener listener) { - // TODO Auto-generated method stub + @Override + public String getText(Object element) { + // TODO Auto-generated method stub + return ((String) element); + } - } + @Override + public void addListener(ILabelProviderListener listener) { + // TODO Auto-generated method stub - @Override - public void dispose() { - // TODO Auto-generated method stub + } - } + @Override + public void dispose() { + // TODO Auto-generated method stub - @Override - public boolean isLabelProperty(Object element, String property) { - // TODO Auto-generated method stub - return false; - } + } - @Override - public void removeListener(ILabelProviderListener listener) { - // TODO Auto-generated method stub + @Override + public boolean isLabelProperty(Object element, String property) { + // TODO Auto-generated method stub + return false; + } - } + @Override + public void removeListener(ILabelProviderListener listener) { + // TODO Auto-generated method stub } + + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nAuditor.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nAuditor.java index 79fcfda6..61b9615f 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nAuditor.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nAuditor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -18,56 +18,56 @@ public abstract class I18nAuditor { - /** - * Audits a project resource for I18N problems. This method is triggered - * during the project's build process. - * - * @param resource - * The project resource - */ - public abstract void audit(IResource resource); + /** + * Audits a project resource for I18N problems. This method is triggered + * during the project's build process. + * + * @param resource + * The project resource + */ + public abstract void audit(IResource resource); - /** - * Returns a characterizing identifier of the implemented auditing - * functionality. The specified identifier is used for discriminating - * registered builder extensions. - * - * @return The String id of the implemented auditing functionality - */ - public abstract String getContextId(); + /** + * Returns a characterizing identifier of the implemented auditing + * functionality. The specified identifier is used for discriminating + * registered builder extensions. + * + * @return The String id of the implemented auditing functionality + */ + public abstract String getContextId(); - /** - * Returns a list of supported file endings. - * - * @return The supported file endings - */ - public abstract String[] getFileEndings(); + /** + * Returns a list of supported file endings. + * + * @return The supported file endings + */ + public abstract String[] getFileEndings(); - /** - * Returns a list of quick fixes of a reported Internationalization problem. - * - * @param marker - * The warning marker of the Internationalization problem - * @param cause - * The problem type - * @return The list of marker resolution proposals - */ - public abstract List<IMarkerResolution> getMarkerResolutions(IMarker marker); + /** + * Returns a list of quick fixes of a reported Internationalization problem. + * + * @param marker + * The warning marker of the Internationalization problem + * @param cause + * The problem type + * @return The list of marker resolution proposals + */ + public abstract List<IMarkerResolution> getMarkerResolutions(IMarker marker); - /** - * Checks if the provided resource auditor is responsible for a particular - * resource. - * - * @param resource - * The resource reference - * @return True if the resource auditor is responsible for the referenced - * resource - */ - public boolean isResourceOfType(IResource resource) { - for (String ending : getFileEndings()) { - if (resource.getFileExtension().equalsIgnoreCase(ending)) - return true; - } - return false; + /** + * Checks if the provided resource auditor is responsible for a particular + * resource. + * + * @param resource + * The resource reference + * @return True if the resource auditor is responsible for the referenced + * resource + */ + public boolean isResourceOfType(IResource resource) { + for (String ending : getFileEndings()) { + if (resource.getFileExtension().equalsIgnoreCase(ending)) + return true; } + return false; + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nRBAuditor.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nRBAuditor.java index 9c0f6c5b..eb103821 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nRBAuditor.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nRBAuditor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -21,37 +21,37 @@ */ public abstract class I18nRBAuditor extends I18nAuditor { - /** - * Mark the end of a audit and reset all problemlists - */ - public abstract void resetProblems(); - - /** - * Returns the list of missing keys or no specified Resource-Bundle-key - * refernces. Each list entry describes the textual position on which this - * type of error has been detected. - * - * @return The list of positions of no specified RB-key refernces - */ - public abstract List<ILocation> getUnspecifiedKeyReferences(); - - /** - * Returns the list of same Resource-Bundle-value refernces. Each list entry - * describes the textual position on which this type of error has been - * detected. - * - * @return The list of positions of same RB-value refernces - */ - public abstract Map<ILocation, ILocation> getSameValuesReferences(); - - /** - * Returns the list of missing Resource-Bundle-languages compared with the - * Resource-Bundles of the hole project. Each list entry describes the - * textual position on which this type of error has been detected. - * - * @return - */ - public abstract List<ILocation> getMissingLanguageReferences(); - - // public abstract List<ILocation> getUnusedKeyReferences(); + /** + * Mark the end of a audit and reset all problemlists + */ + public abstract void resetProblems(); + + /** + * Returns the list of missing keys or no specified Resource-Bundle-key + * refernces. Each list entry describes the textual position on which this + * type of error has been detected. + * + * @return The list of positions of no specified RB-key refernces + */ + public abstract List<ILocation> getUnspecifiedKeyReferences(); + + /** + * Returns the list of same Resource-Bundle-value refernces. Each list entry + * describes the textual position on which this type of error has been + * detected. + * + * @return The list of positions of same RB-value refernces + */ + public abstract Map<ILocation, ILocation> getSameValuesReferences(); + + /** + * Returns the list of missing Resource-Bundle-languages compared with the + * Resource-Bundles of the hole project. Each list entry describes the + * textual position on which this type of error has been detected. + * + * @return + */ + public abstract List<ILocation> getMissingLanguageReferences(); + + // public abstract List<ILocation> getUnusedKeyReferences(); } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nResourceAuditor.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nResourceAuditor.java index 65fff9ec..ac69fc0f 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nResourceAuditor.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/extensions/I18nResourceAuditor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -24,84 +24,84 @@ * the help of problem categorized getter methods. */ public abstract class I18nResourceAuditor extends I18nAuditor { - /** - * Audits a project resource for I18N problems. This method is triggered - * during the project's build process. - * - * @param resource - * The project resource - */ - public abstract void audit(IResource resource); + /** + * Audits a project resource for I18N problems. This method is triggered + * during the project's build process. + * + * @param resource + * The project resource + */ + public abstract void audit(IResource resource); - /** - * Returns a list of supported file endings. - * - * @return The supported file endings - */ - public abstract String[] getFileEndings(); + /** + * Returns a list of supported file endings. + * + * @return The supported file endings + */ + public abstract String[] getFileEndings(); - /** - * Returns the list of found need-to-translate string literals. Each list - * entry describes the textual position on which this type of error has been - * detected. - * - * @return The list of need-to-translate string literal positions - */ - public abstract List<ILocation> getConstantStringLiterals(); + /** + * Returns the list of found need-to-translate string literals. Each list + * entry describes the textual position on which this type of error has been + * detected. + * + * @return The list of need-to-translate string literal positions + */ + public abstract List<ILocation> getConstantStringLiterals(); - /** - * Returns the list of broken Resource-Bundle references. Each list entry - * describes the textual position on which this type of error has been - * detected. - * - * @return The list of positions of broken Resource-Bundle references - */ - public abstract List<ILocation> getBrokenResourceReferences(); + /** + * Returns the list of broken Resource-Bundle references. Each list entry + * describes the textual position on which this type of error has been + * detected. + * + * @return The list of positions of broken Resource-Bundle references + */ + public abstract List<ILocation> getBrokenResourceReferences(); - /** - * Returns the list of broken references to Resource-Bundle entries. Each - * list entry describes the textual position on which this type of error has - * been detected - * - * @return The list of positions of broken references to locale-sensitive - * resources - */ - public abstract List<ILocation> getBrokenBundleReferences(); + /** + * Returns the list of broken references to Resource-Bundle entries. Each + * list entry describes the textual position on which this type of error has + * been detected + * + * @return The list of positions of broken references to locale-sensitive + * resources + */ + public abstract List<ILocation> getBrokenBundleReferences(); - /** - * Returns a characterizing identifier of the implemented auditing - * functionality. The specified identifier is used for discriminating - * registered builder extensions. - * - * @return The String id of the implemented auditing functionality - */ - public abstract String getContextId(); + /** + * Returns a characterizing identifier of the implemented auditing + * functionality. The specified identifier is used for discriminating + * registered builder extensions. + * + * @return The String id of the implemented auditing functionality + */ + public abstract String getContextId(); - /** - * Returns a list of quick fixes of a reported Internationalization problem. - * - * @param marker - * The warning marker of the Internationalization problem - * @param cause - * The problem type - * @return The list of marker resolution proposals - */ - public abstract List<IMarkerResolution> getMarkerResolutions(IMarker marker); + /** + * Returns a list of quick fixes of a reported Internationalization problem. + * + * @param marker + * The warning marker of the Internationalization problem + * @param cause + * The problem type + * @return The list of marker resolution proposals + */ + public abstract List<IMarkerResolution> getMarkerResolutions(IMarker marker); - /** - * Checks if the provided resource auditor is responsible for a particular - * resource. - * - * @param resource - * The resource reference - * @return True if the resource auditor is responsible for the referenced - * resource - */ - public boolean isResourceOfType(IResource resource) { - for (String ending : getFileEndings()) { - if (resource.getFileExtension().equalsIgnoreCase(ending)) - return true; - } - return false; + /** + * Checks if the provided resource auditor is responsible for a particular + * resource. + * + * @param resource + * The resource reference + * @return True if the resource auditor is responsible for the referenced + * resource + */ + public boolean isResourceOfType(IResource resource) { + for (String ending : getFileEndings()) { + if (resource.getFileExtension().equalsIgnoreCase(ending)) + return true; } + return false; + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/filters/PropertiesFileFilter.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/filters/PropertiesFileFilter.java index 13f6408d..d79d4be9 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/filters/PropertiesFileFilter.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/filters/PropertiesFileFilter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -16,26 +16,26 @@ public class PropertiesFileFilter extends ViewerFilter { - private boolean debugEnabled = true; + private boolean debugEnabled = true; - public PropertiesFileFilter() { + public PropertiesFileFilter() { - } + } - @Override - public boolean select(Viewer viewer, Object parentElement, Object element) { - if (debugEnabled) - return true; + @Override + public boolean select(Viewer viewer, Object parentElement, Object element) { + if (debugEnabled) + return true; - if (element.getClass().getSimpleName().equals("CompilationUnit")) - return false; + if (element.getClass().getSimpleName().equals("CompilationUnit")) + return false; - if (!(element instanceof IFile)) - return true; + if (!(element instanceof IFile)) + return true; - IFile file = (IFile) element; + IFile file = (IFile) element; - return file.getFileExtension().equalsIgnoreCase("properties"); - } + return file.getFileExtension().equalsIgnoreCase("properties"); + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java index 5ff02055..6c6ec3fc 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/MarkerUpdater.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Matthias Lettmayer. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -19,29 +19,29 @@ public class MarkerUpdater implements IMarkerUpdater { - @Override - public String getMarkerType() { - return "org.eclipse.core.resources.problemmarker"; - } + @Override + public String getMarkerType() { + return "org.eclipse.core.resources.problemmarker"; + } - @Override - public String[] getAttribute() { - // TODO Auto-generated method stub - return null; - } + @Override + public String[] getAttribute() { + // TODO Auto-generated method stub + return null; + } - @Override - public boolean updateMarker(IMarker marker, IDocument document, - Position position) { - try { - int start = position.getOffset(); - int end = position.getOffset() + position.getLength(); - marker.setAttribute(IMarker.CHAR_START, start); - marker.setAttribute(IMarker.CHAR_END, end); - return true; - } catch (CoreException e) { - Logger.logError(e); - return false; - } + @Override + public boolean updateMarker(IMarker marker, IDocument document, + Position position) { + try { + int start = position.getOffset(); + int end = position.getOffset() + position.getLength(); + marker.setAttribute(IMarker.CHAR_START, start); + marker.setAttribute(IMarker.CHAR_END, end); + return true; + } catch (CoreException e) { + Logger.logError(e); + return false; } + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/StringLiterals.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/StringLiterals.java deleted file mode 100644 index 0588ee2e..00000000 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/markers/StringLiterals.java +++ /dev/null @@ -1,15 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 TapiJI. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -package org.eclipse.babel.tapiji.tools.core.ui.markers; - -public class StringLiterals { - -} diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java index 3c09af58..65b92112 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/memento/ResourceBundleManagerStateLoader.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -33,95 +33,88 @@ */ public class ResourceBundleManagerStateLoader implements IStateLoader { - private static final String TAG_INTERNATIONALIZATION = "Internationalization"; - private static final String TAG_EXCLUDED = "Excluded"; - private static final String TAG_RES_DESC = "ResourceDescription"; - private static final String TAG_RES_DESC_ABS = "AbsolutePath"; - private static final String TAG_RES_DESC_REL = "RelativePath"; - private static final String TAB_RES_DESC_PRO = "ProjectName"; - private static final String TAB_RES_DESC_BID = "BundleId"; - - private HashSet<IResourceDescriptor> excludedResources; - - /** - * {@inheritDoc} - */ - @Override - public void loadState() { + private static final String TAG_INTERNATIONALIZATION = "Internationalization"; + private static final String TAG_EXCLUDED = "Excluded"; + private static final String TAG_RES_DESC = "ResourceDescription"; + private static final String TAG_RES_DESC_ABS = "AbsolutePath"; + private static final String TAG_RES_DESC_REL = "RelativePath"; + private static final String TAB_RES_DESC_PRO = "ProjectName"; + private static final String TAB_RES_DESC_BID = "BundleId"; - excludedResources = new HashSet<IResourceDescriptor>(); - FileReader reader = null; - try { - reader = new FileReader(FileUtils.getRBManagerStateFile()); - loadManagerState(XMLMemento.createReadRoot(reader)); - } catch (Exception e) { - Logger.logError(e); - } - -// changelistener = new RBChangeListner(); -// ResourcesPlugin.getWorkspace().addResourceChangeListener( -// changelistener, -// IResourceChangeEvent.PRE_DELETE -// | IResourceChangeEvent.POST_CHANGE); - } - + private HashSet<IResourceDescriptor> excludedResources; - private void loadManagerState(XMLMemento memento) { - IMemento excludedChild = memento.getChild(TAG_EXCLUDED); - for (IMemento excluded : excludedChild.getChildren(TAG_RES_DESC)) { - IResourceDescriptor descriptor = new ResourceDescriptor(); - descriptor.setAbsolutePath(excluded.getString(TAG_RES_DESC_ABS)); - descriptor.setRelativePath(excluded.getString(TAG_RES_DESC_REL)); - descriptor.setProjectName(excluded.getString(TAB_RES_DESC_PRO)); - descriptor.setBundleId(excluded.getString(TAB_RES_DESC_BID)); - excludedResources.add(descriptor); - } + /** + * {@inheritDoc} + */ + @Override + public void loadState() { + + excludedResources = new HashSet<IResourceDescriptor>(); + FileReader reader = null; + try { + reader = new FileReader(FileUtils.getRBManagerStateFile()); + loadManagerState(XMLMemento.createReadRoot(reader)); + } catch (Exception e) { + Logger.logError(e); } + } - /** - * {@inheritDoc} - */ - @Override - public Set<IResourceDescriptor> getExcludedResources() { - return excludedResources; + private void loadManagerState(XMLMemento memento) { + IMemento excludedChild = memento.getChild(TAG_EXCLUDED); + for (IMemento excluded : excludedChild.getChildren(TAG_RES_DESC)) { + IResourceDescriptor descriptor = new ResourceDescriptor(); + descriptor.setAbsolutePath(excluded.getString(TAG_RES_DESC_ABS)); + descriptor.setRelativePath(excluded.getString(TAG_RES_DESC_REL)); + descriptor.setProjectName(excluded.getString(TAB_RES_DESC_PRO)); + descriptor.setBundleId(excluded.getString(TAB_RES_DESC_BID)); + excludedResources.add(descriptor); } + } - /** - * {@inheritDoc} - */ - @Override - public void saveState() { - if (excludedResources == null) { - return; - } - XMLMemento memento = XMLMemento - .createWriteRoot(TAG_INTERNATIONALIZATION); - IMemento exclChild = memento.createChild(TAG_EXCLUDED); + /** + * {@inheritDoc} + */ + @Override + public Set<IResourceDescriptor> getExcludedResources() { + return excludedResources; + } - Iterator<IResourceDescriptor> itExcl = excludedResources.iterator(); - while (itExcl.hasNext()) { - IResourceDescriptor desc = itExcl.next(); - IMemento resDesc = exclChild.createChild(TAG_RES_DESC); - resDesc.putString(TAB_RES_DESC_PRO, desc.getProjectName()); - resDesc.putString(TAG_RES_DESC_ABS, desc.getAbsolutePath()); - resDesc.putString(TAG_RES_DESC_REL, desc.getRelativePath()); - resDesc.putString(TAB_RES_DESC_BID, desc.getBundleId()); - } - FileWriter writer = null; - try { - writer = new FileWriter(FileUtils.getRBManagerStateFile()); - memento.save(writer); - } catch (Exception e) { - Logger.logError(e); - } finally { - try { - if (writer != null) { - writer.close(); - } - } catch (Exception e) { - Logger.logError(e); - } + /** + * {@inheritDoc} + */ + @Override + public void saveState() { + if (excludedResources == null) { + return; + } + XMLMemento memento = XMLMemento + .createWriteRoot(TAG_INTERNATIONALIZATION); + IMemento exclChild = memento.createChild(TAG_EXCLUDED); + + Iterator<IResourceDescriptor> itExcl = excludedResources.iterator(); + while (itExcl.hasNext()) { + IResourceDescriptor desc = itExcl.next(); + IMemento resDesc = exclChild.createChild(TAG_RES_DESC); + resDesc.putString(TAB_RES_DESC_PRO, desc.getProjectName()); + resDesc.putString(TAG_RES_DESC_ABS, desc.getAbsolutePath()); + resDesc.putString(TAG_RES_DESC_REL, desc.getRelativePath()); + resDesc.putString(TAB_RES_DESC_BID, desc.getBundleId()); + } + FileWriter writer = null; + try { + writer = new FileWriter(FileUtils.getRBManagerStateFile()); + memento.save(writer); + } catch (Exception e) { + Logger.logError(e); + } finally { + try { + if (writer != null) { + writer.close(); } + } catch (Exception e) { + Logger.logError(e); + } } + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/menus/InternationalizationMenu.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/menus/InternationalizationMenu.java index 5eaca5a5..64053b4a 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/menus/InternationalizationMenu.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/menus/InternationalizationMenu.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -53,380 +53,381 @@ import org.eclipse.ui.progress.IProgressService; public class InternationalizationMenu extends ContributionItem { - private boolean excludeMode = true; - private boolean internationalizationEnabled = false; + private boolean excludeMode = true; + private boolean internationalizationEnabled = false; - private MenuItem mnuToggleInt; - private MenuItem excludeResource; - private MenuItem addLanguage; - private MenuItem removeLanguage; + private MenuItem mnuToggleInt; + private MenuItem excludeResource; + private MenuItem addLanguage; + private MenuItem removeLanguage; - public InternationalizationMenu() { - } - - public InternationalizationMenu(String id) { - super(id); - } - - @Override - public void fill(Menu menu, int index) { - if (getSelectedProjects().size() == 0 || !projectsSupported()) { - return; - } - - // Toggle Internatinalization - mnuToggleInt = new MenuItem(menu, SWT.PUSH); - mnuToggleInt.addSelectionListener(new SelectionAdapter() { - - @Override - public void widgetSelected(SelectionEvent e) { - runToggleInt(); - } - - }); + public InternationalizationMenu() { + } - // Exclude Resource - excludeResource = new MenuItem(menu, SWT.PUSH); - excludeResource.addSelectionListener(new SelectionAdapter() { - - @Override - public void widgetSelected(SelectionEvent e) { - runExclude(); - } - - }); - - new MenuItem(menu, SWT.SEPARATOR); - - // Add Language - addLanguage = new MenuItem(menu, SWT.PUSH); - addLanguage.addSelectionListener(new SelectionAdapter() { - - @Override - public void widgetSelected(SelectionEvent e) { - runAddLanguage(); - } - - }); + public InternationalizationMenu(String id) { + super(id); + } - // Remove Language - removeLanguage = new MenuItem(menu, SWT.PUSH); - removeLanguage.addSelectionListener(new SelectionAdapter() { - - @Override - public void widgetSelected(SelectionEvent e) { - runRemoveLanguage(); - } - - }); - - menu.addMenuListener(new MenuAdapter() { - @Override - public void menuShown(MenuEvent e) { - updateStateToggleInt(mnuToggleInt); - // updateStateGenRBAccessor (generateAccessor); - updateStateExclude(excludeResource); - updateStateAddLanguage(addLanguage); - updateStateRemoveLanguage(removeLanguage); - } - }); + @Override + public void fill(Menu menu, int index) { + if (getSelectedProjects().size() == 0 || !projectsSupported()) { + return; } - protected void runGenRBAccessor() { - GenerateBundleAccessorDialog dlg = new GenerateBundleAccessorDialog( - Display.getDefault().getActiveShell()); - if (dlg.open() != InputDialog.OK) { - return; - } + // Toggle Internatinalization + mnuToggleInt = new MenuItem(menu, SWT.PUSH); + mnuToggleInt.addSelectionListener(new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent e) { + runToggleInt(); + } + + }); + + // Exclude Resource + excludeResource = new MenuItem(menu, SWT.PUSH); + excludeResource.addSelectionListener(new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent e) { + runExclude(); + } + + }); + + new MenuItem(menu, SWT.SEPARATOR); + + // Add Language + addLanguage = new MenuItem(menu, SWT.PUSH); + addLanguage.addSelectionListener(new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent e) { + runAddLanguage(); + } + + }); + + // Remove Language + removeLanguage = new MenuItem(menu, SWT.PUSH); + removeLanguage.addSelectionListener(new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent e) { + runRemoveLanguage(); + } + + }); + + menu.addMenuListener(new MenuAdapter() { + @Override + public void menuShown(MenuEvent e) { + updateStateToggleInt(mnuToggleInt); + // updateStateGenRBAccessor (generateAccessor); + updateStateExclude(excludeResource); + updateStateAddLanguage(addLanguage); + updateStateRemoveLanguage(removeLanguage); + } + }); + } + + protected void runGenRBAccessor() { + GenerateBundleAccessorDialog dlg = new GenerateBundleAccessorDialog( + Display.getDefault().getActiveShell()); + if (dlg.open() != InputDialog.OK) { + return; } - - protected void updateStateGenRBAccessor(MenuItem menuItem) { - Collection<IPackageFragment> frags = getSelectedPackageFragments(); - menuItem.setEnabled(frags.size() > 0); + } + + protected void updateStateGenRBAccessor(MenuItem menuItem) { + Collection<IPackageFragment> frags = getSelectedPackageFragments(); + menuItem.setEnabled(frags.size() > 0); + } + + protected void updateStateToggleInt(MenuItem menuItem) { + Collection<IProject> projects = getSelectedProjects(); + boolean enabled = projects.size() > 0; + menuItem.setEnabled(enabled); + setVisible(enabled); + internationalizationEnabled = InternationalizationNature + .hasNature(projects.iterator().next()); + // menuItem.setSelection(enabled && internationalizationEnabled); + + if (internationalizationEnabled) { + menuItem.setText("Disable Internationalization"); + } else { + menuItem.setText("Enable Internationalization"); } - - protected void updateStateToggleInt(MenuItem menuItem) { - Collection<IProject> projects = getSelectedProjects(); - boolean enabled = projects.size() > 0; - menuItem.setEnabled(enabled); - setVisible(enabled); - internationalizationEnabled = InternationalizationNature - .hasNature(projects.iterator().next()); - // menuItem.setSelection(enabled && internationalizationEnabled); - - if (internationalizationEnabled) { - menuItem.setText("Disable Internationalization"); - } else { - menuItem.setText("Enable Internationalization"); + } + + private Collection<IPackageFragment> getSelectedPackageFragments() { + Collection<IPackageFragment> frags = new HashSet<IPackageFragment>(); + IWorkbenchWindow window = PlatformUI.getWorkbench() + .getActiveWorkbenchWindow(); + ISelection selection = window.getActivePage().getSelection(); + if (selection instanceof IStructuredSelection) { + for (Iterator<?> iter = ((IStructuredSelection) selection) + .iterator(); iter.hasNext();) { + Object elem = iter.next(); + if (elem instanceof IPackageFragment) { + IPackageFragment frag = (IPackageFragment) elem; + if (!frag.isReadOnly()) { + frags.add(frag); + } } + } } - - private Collection<IPackageFragment> getSelectedPackageFragments() { - Collection<IPackageFragment> frags = new HashSet<IPackageFragment>(); - IWorkbenchWindow window = PlatformUI.getWorkbench() - .getActiveWorkbenchWindow(); - ISelection selection = window.getActivePage().getSelection(); - if (selection instanceof IStructuredSelection) { - for (Iterator<?> iter = ((IStructuredSelection) selection) - .iterator(); iter.hasNext();) { - Object elem = iter.next(); - if (elem instanceof IPackageFragment) { - IPackageFragment frag = (IPackageFragment) elem; - if (!frag.isReadOnly()) { - frags.add(frag); - } - } - } + return frags; + } + + private Collection<IProject> getSelectedProjects() { + Collection<IProject> projects = new HashSet<IProject>(); + IWorkbenchWindow window = PlatformUI.getWorkbench() + .getActiveWorkbenchWindow(); + ISelection selection = window.getActivePage().getSelection(); + if (selection instanceof IStructuredSelection) { + for (Iterator<?> iter = ((IStructuredSelection) selection) + .iterator(); iter.hasNext();) { + Object elem = iter.next(); + if (!(elem instanceof IResource)) { + if (!(elem instanceof IAdaptable)) { + continue; + } + elem = ((IAdaptable) elem).getAdapter(IResource.class); + if (!(elem instanceof IResource)) { + continue; + } } - return frags; - } - - private Collection<IProject> getSelectedProjects() { - Collection<IProject> projects = new HashSet<IProject>(); - IWorkbenchWindow window = PlatformUI.getWorkbench() - .getActiveWorkbenchWindow(); - ISelection selection = window.getActivePage().getSelection(); - if (selection instanceof IStructuredSelection) { - for (Iterator<?> iter = ((IStructuredSelection) selection) - .iterator(); iter.hasNext();) { - Object elem = iter.next(); - if (!(elem instanceof IResource)) { - if (!(elem instanceof IAdaptable)) { - continue; - } - elem = ((IAdaptable) elem).getAdapter(IResource.class); - if (!(elem instanceof IResource)) { - continue; - } - } - if (!(elem instanceof IProject)) { - elem = ((IResource) elem).getProject(); - if (!(elem instanceof IProject)) { - continue; - } - } - if (((IProject) elem).isAccessible()) { - projects.add((IProject) elem); - } - - } + if (!(elem instanceof IProject)) { + elem = ((IResource) elem).getProject(); + if (!(elem instanceof IProject)) { + continue; + } } - return projects; - } - - protected boolean projectsSupported() { - Collection<IProject> projects = getSelectedProjects(); - for (IProject project : projects) { - if (!InternationalizationNature.supportsNature(project)) { - return false; - } + if (((IProject) elem).isAccessible()) { + projects.add((IProject) elem); } - return true; + } + } + return projects; + } + + protected boolean projectsSupported() { + Collection<IProject> projects = getSelectedProjects(); + for (IProject project : projects) { + if (!InternationalizationNature.supportsNature(project)) { + return false; + } } - protected void runToggleInt() { - Collection<IProject> projects = getSelectedProjects(); - for (IProject project : projects) { - toggleNature(project); - } + return true; + } + + protected void runToggleInt() { + Collection<IProject> projects = getSelectedProjects(); + for (IProject project : projects) { + toggleNature(project); } + } - private void toggleNature(IProject project) { - if (InternationalizationNature.hasNature(project)) { - InternationalizationNature.removeNature(project); - } else { - InternationalizationNature.addNature(project); + private void toggleNature(IProject project) { + if (InternationalizationNature.hasNature(project)) { + InternationalizationNature.removeNature(project); + } else { + InternationalizationNature.addNature(project); + } + } + + protected void updateStateExclude(MenuItem menuItem) { + Collection<IResource> resources = getSelectedResources(); + menuItem.setEnabled(resources.size() > 0 && internationalizationEnabled); + ResourceBundleManager manager = null; + excludeMode = false; + + for (IResource res : resources) { + if (manager == null || (manager.getProject() != res.getProject())) { + manager = ResourceBundleManager.getManager(res.getProject()); + } + try { + if (!ResourceBundleManager.isResourceExcluded(res)) { + excludeMode = true; } + } catch (Exception e) { + } } - protected void updateStateExclude(MenuItem menuItem) { - Collection<IResource> resources = getSelectedResources(); - menuItem.setEnabled(resources.size() > 0 && internationalizationEnabled); - ResourceBundleManager manager = null; - excludeMode = false; - - for (IResource res : resources) { - if (manager == null || (manager.getProject() != res.getProject())) { - manager = ResourceBundleManager.getManager(res.getProject()); - } - try { - if (!ResourceBundleManager.isResourceExcluded(res)) { - excludeMode = true; - } - } catch (Exception e) { - } + if (!excludeMode) { + menuItem.setText("Include Resource"); + } else { + menuItem.setText("Exclude Resource"); + } + } + + private Collection<IResource> getSelectedResources() { + Collection<IResource> resources = new HashSet<IResource>(); + IWorkbenchWindow window = PlatformUI.getWorkbench() + .getActiveWorkbenchWindow(); + ISelection selection = window.getActivePage().getSelection(); + if (selection instanceof IStructuredSelection) { + for (Iterator<?> iter = ((IStructuredSelection) selection) + .iterator(); iter.hasNext();) { + Object elem = iter.next(); + if (elem instanceof IProject) { + continue; } - if (!excludeMode) { - menuItem.setText("Include Resource"); - } else { - menuItem.setText("Exclude Resource"); + if (elem instanceof IResource) { + resources.add((IResource) elem); + } else if (elem instanceof IJavaElement) { + resources.add(((IJavaElement) elem).getResource()); } + } } - - private Collection<IResource> getSelectedResources() { - Collection<IResource> resources = new HashSet<IResource>(); - IWorkbenchWindow window = PlatformUI.getWorkbench() - .getActiveWorkbenchWindow(); - ISelection selection = window.getActivePage().getSelection(); - if (selection instanceof IStructuredSelection) { - for (Iterator<?> iter = ((IStructuredSelection) selection) - .iterator(); iter.hasNext();) { - Object elem = iter.next(); - if (elem instanceof IProject) { - continue; - } - - if (elem instanceof IResource) { - resources.add((IResource) elem); - } else if (elem instanceof IJavaElement) { - resources.add(((IJavaElement) elem).getResource()); - } + return resources; + } + + protected void runExclude() { + final Collection<IResource> selectedResources = getSelectedResources(); + + IWorkbench wb = PlatformUI.getWorkbench(); + IProgressService ps = wb.getProgressService(); + try { + ps.busyCursorWhile(new IRunnableWithProgress() { + @Override + public void run(IProgressMonitor pm) { + + ResourceBundleManager manager = null; + pm.beginTask("Including resources to Internationalization", + selectedResources.size()); + + for (IResource res : selectedResources) { + if (manager == null + || (manager.getProject() != res.getProject())) { + manager = ResourceBundleManager.getManager(res + .getProject()); + } + if (excludeMode) { + manager.excludeResource(res, pm); + } else { + manager.includeResource(res, pm); } + pm.worked(1); + } + pm.done(); } - return resources; + }); + } catch (Exception e) { } - - protected void runExclude() { - final Collection<IResource> selectedResources = getSelectedResources(); - - IWorkbench wb = PlatformUI.getWorkbench(); - IProgressService ps = wb.getProgressService(); - try { - ps.busyCursorWhile(new IRunnableWithProgress() { - @Override - public void run(IProgressMonitor pm) { - - ResourceBundleManager manager = null; - pm.beginTask("Including resources to Internationalization", - selectedResources.size()); - - for (IResource res : selectedResources) { - if (manager == null - || (manager.getProject() != res.getProject())) { - manager = ResourceBundleManager.getManager(res - .getProject()); - } - if (excludeMode) { - manager.excludeResource(res, pm); - } else { - manager.includeResource(res, pm); - } - pm.worked(1); - } - pm.done(); - } - }); - } catch (Exception e) { - } + } + + protected void updateStateAddLanguage(MenuItem menuItem) { + Collection<IProject> projects = getSelectedProjects(); + boolean hasResourceBundles = false; + for (IProject p : projects) { + ResourceBundleManager rbmanager = ResourceBundleManager + .getManager(p); + hasResourceBundles = rbmanager.getResourceBundleIdentifiers() + .size() > 0 ? true : false; } - protected void updateStateAddLanguage(MenuItem menuItem) { - Collection<IProject> projects = getSelectedProjects(); - boolean hasResourceBundles = false; - for (IProject p : projects) { - ResourceBundleManager rbmanager = ResourceBundleManager - .getManager(p); - hasResourceBundles = rbmanager.getResourceBundleIdentifiers() - .size() > 0 ? true : false; + menuItem.setText("Add Language To Project"); + menuItem.setEnabled(projects.size() > 0 && hasResourceBundles); + } + + protected void runAddLanguage() { + AddLanguageDialoge dialog = new AddLanguageDialoge(new Shell( + Display.getCurrent())); + if (dialog.open() == InputDialog.OK) { + final Locale locale = dialog.getSelectedLanguage(); + + Collection<IProject> selectedProjects = getSelectedProjects(); + for (IProject project : selectedProjects) { + // check if project is fragmentproject and continue working with + // the hostproject, if host not member of selectedProjects + if (FragmentProjectUtils.isFragment(project)) { + IProject host = FragmentProjectUtils + .getFragmentHost(project); + if (!selectedProjects.contains(host)) { + project = host; + } else { + continue; + } } - menuItem.setText("Add Language To Project"); - menuItem.setEnabled(projects.size() > 0 && hasResourceBundles); - } - - protected void runAddLanguage() { - AddLanguageDialoge dialog = new AddLanguageDialoge(new Shell( - Display.getCurrent())); - if (dialog.open() == InputDialog.OK) { - final Locale locale = dialog.getSelectedLanguage(); - - Collection<IProject> selectedProjects = getSelectedProjects(); - for (IProject project : selectedProjects) { - // check if project is fragmentproject and continue working with - // the hostproject, if host not member of selectedProjects - if (FragmentProjectUtils.isFragment(project)) { - IProject host = FragmentProjectUtils - .getFragmentHost(project); - if (!selectedProjects.contains(host)) { - project = host; - } else { - continue; - } - } - - List<IProject> fragments = FragmentProjectUtils - .getFragments(project); + List<IProject> fragments = FragmentProjectUtils + .getFragments(project); - if (!fragments.isEmpty()) { - FragmentProjectSelectionDialog fragmentDialog = new FragmentProjectSelectionDialog( - Display.getCurrent().getActiveShell(), project, - fragments); + if (!fragments.isEmpty()) { + FragmentProjectSelectionDialog fragmentDialog = new FragmentProjectSelectionDialog( + Display.getCurrent().getActiveShell(), project, + fragments); - if (fragmentDialog.open() == InputDialog.OK) { - project = fragmentDialog.getSelectedProject(); - } - } + if (fragmentDialog.open() == InputDialog.OK) { + project = fragmentDialog.getSelectedProject(); + } + } - final IProject selectedProject = project; - BusyIndicator.showWhile(Display.getCurrent(), new Runnable() { - @Override - public void run() { - LanguageUtils.addLanguageToProject(selectedProject, - locale); - } + final IProject selectedProject = project; + BusyIndicator.showWhile(Display.getCurrent(), new Runnable() { + @Override + public void run() { + LanguageUtils.addLanguageToProject(selectedProject, + locale); + } - }); + }); - } - } + } } - - protected void updateStateRemoveLanguage(MenuItem menuItem) { - Collection<IProject> projects = getSelectedProjects(); - boolean hasResourceBundles = false; - if (projects.size() == 1) { - IProject project = projects.iterator().next(); - ResourceBundleManager rbmanager = ResourceBundleManager - .getManager(project); - hasResourceBundles = rbmanager.getResourceBundleIdentifiers() - .size() > 0 ? true : false; - } - menuItem.setText("Remove Language From Project"); - menuItem.setEnabled(projects.size() == 1 && hasResourceBundles/* - * && more - * than one - * common - * languages - * contained - */); + } + + protected void updateStateRemoveLanguage(MenuItem menuItem) { + Collection<IProject> projects = getSelectedProjects(); + boolean hasResourceBundles = false; + if (projects.size() == 1) { + IProject project = projects.iterator().next(); + ResourceBundleManager rbmanager = ResourceBundleManager + .getManager(project); + hasResourceBundles = rbmanager.getResourceBundleIdentifiers() + .size() > 0 ? true : false; } - - protected void runRemoveLanguage() { - final IProject project = getSelectedProjects().iterator().next(); - RemoveLanguageDialoge dialog = new RemoveLanguageDialoge(project, - new Shell(Display.getCurrent())); - - if (dialog.open() == InputDialog.OK) { - final Locale locale = dialog.getSelectedLanguage(); - if (locale != null) { - if (MessageDialog.openConfirm(Display.getCurrent() - .getActiveShell(), "Confirm", - "Do you really want remove all properties-files for " - + locale.getDisplayName() + "?")) { - BusyIndicator.showWhile(Display.getCurrent(), - new Runnable() { - @Override - public void run() { - RBFileUtils.removeLanguageFromProject( - project, locale); - } - }); + menuItem.setText("Remove Language From Project"); + menuItem.setEnabled(projects.size() == 1 && hasResourceBundles/* + * && more + * than + * one + * common + * languages + * contained + */); + } + + protected void runRemoveLanguage() { + final IProject project = getSelectedProjects().iterator().next(); + RemoveLanguageDialoge dialog = new RemoveLanguageDialoge(project, + new Shell(Display.getCurrent())); + + if (dialog.open() == InputDialog.OK) { + final Locale locale = dialog.getSelectedLanguage(); + if (locale != null) { + if (MessageDialog.openConfirm(Display.getCurrent() + .getActiveShell(), "Confirm", + "Do you really want remove all properties-files for " + + locale.getDisplayName() + "?")) { + BusyIndicator.showWhile(Display.getCurrent(), + new Runnable() { + @Override + public void run() { + RBFileUtils.removeLanguageFromProject( + project, locale); } - - } + }); } + + } } + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/BuilderPreferencePage.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/BuilderPreferencePage.java index 015af438..d7493305 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/BuilderPreferencePage.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/BuilderPreferencePage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -26,131 +26,131 @@ import org.eclipse.ui.IWorkbenchPreferencePage; public class BuilderPreferencePage extends PreferencePage implements - IWorkbenchPreferencePage { - private static final int INDENT = 20; - - private Button checkSameValueButton; - private Button checkMissingValueButton; - private Button checkMissingLanguageButton; - - private Button rbAuditButton; - - private Button sourceAuditButton; - - @Override - public void init(IWorkbench workbench) { - setPreferenceStore(Activator.getDefault().getPreferenceStore()); - } - - @Override - protected Control createContents(Composite parent) { - IPreferenceStore prefs = getPreferenceStore(); - Composite composite = new Composite(parent, SWT.SHADOW_OUT); - - composite.setLayout(new GridLayout(1, false)); - composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true)); - - Composite field = createComposite(parent, 0, 10); - Label descriptionLabel = new Label(composite, SWT.NONE); - descriptionLabel.setText("Select types of reported problems:"); - - field = createComposite(composite, 0, 0); - sourceAuditButton = new Button(field, SWT.CHECK); - sourceAuditButton.setSelection(prefs - .getBoolean(TapiJIPreferences.AUDIT_RESOURCE)); - sourceAuditButton - .setText("Check source code for non externalizated Strings"); - - field = createComposite(composite, 0, 0); - rbAuditButton = new Button(field, SWT.CHECK); - rbAuditButton - .setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_RB)); - rbAuditButton - .setText("Check ResourceBundles on the following problems:"); - rbAuditButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - setRBAudits(); - } - }); - - field = createComposite(composite, INDENT, 0); - checkMissingValueButton = new Button(field, SWT.CHECK); - checkMissingValueButton.setSelection(prefs - .getBoolean(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)); - checkMissingValueButton.setText("Missing translation for a key"); - - field = createComposite(composite, INDENT, 0); - checkSameValueButton = new Button(field, SWT.CHECK); - checkSameValueButton.setSelection(prefs - .getBoolean(TapiJIPreferences.AUDIT_SAME_VALUE)); - checkSameValueButton - .setText("Same translations for one key in diffrent languages"); - - field = createComposite(composite, INDENT, 0); - checkMissingLanguageButton = new Button(field, SWT.CHECK); - checkMissingLanguageButton.setSelection(prefs - .getBoolean(TapiJIPreferences.AUDIT_MISSING_LANGUAGE)); - checkMissingLanguageButton - .setText("Missing languages in a ResourceBundle"); - + IWorkbenchPreferencePage { + private static final int INDENT = 20; + + private Button checkSameValueButton; + private Button checkMissingValueButton; + private Button checkMissingLanguageButton; + + private Button rbAuditButton; + + private Button sourceAuditButton; + + @Override + public void init(IWorkbench workbench) { + setPreferenceStore(Activator.getDefault().getPreferenceStore()); + } + + @Override + protected Control createContents(Composite parent) { + IPreferenceStore prefs = getPreferenceStore(); + Composite composite = new Composite(parent, SWT.SHADOW_OUT); + + composite.setLayout(new GridLayout(1, false)); + composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true)); + + Composite field = createComposite(parent, 0, 10); + Label descriptionLabel = new Label(composite, SWT.NONE); + descriptionLabel.setText("Select types of reported problems:"); + + field = createComposite(composite, 0, 0); + sourceAuditButton = new Button(field, SWT.CHECK); + sourceAuditButton.setSelection(prefs + .getBoolean(TapiJIPreferences.AUDIT_RESOURCE)); + sourceAuditButton + .setText("Check source code for non externalizated Strings"); + + field = createComposite(composite, 0, 0); + rbAuditButton = new Button(field, SWT.CHECK); + rbAuditButton + .setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_RB)); + rbAuditButton + .setText("Check ResourceBundles on the following problems:"); + rbAuditButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { setRBAudits(); - - composite.pack(); - - return composite; - } - - @Override - protected void performDefaults() { - IPreferenceStore prefs = getPreferenceStore(); - - sourceAuditButton.setSelection(prefs - .getDefaultBoolean(TapiJIPreferences.AUDIT_RESOURCE)); - rbAuditButton.setSelection(prefs - .getDefaultBoolean(TapiJIPreferences.AUDIT_RB)); - checkMissingValueButton.setSelection(prefs - .getDefaultBoolean(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)); - checkSameValueButton.setSelection(prefs - .getDefaultBoolean(TapiJIPreferences.AUDIT_SAME_VALUE)); - checkMissingLanguageButton.setSelection(prefs - .getDefaultBoolean(TapiJIPreferences.AUDIT_MISSING_LANGUAGE)); - } - - @Override - public boolean performOk() { - IPreferenceStore prefs = getPreferenceStore(); - - prefs.setValue(TapiJIPreferences.AUDIT_RESOURCE, - sourceAuditButton.getSelection()); - prefs.setValue(TapiJIPreferences.AUDIT_RB, rbAuditButton.getSelection()); - prefs.setValue(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY, - checkMissingValueButton.getSelection()); - prefs.setValue(TapiJIPreferences.AUDIT_SAME_VALUE, - checkSameValueButton.getSelection()); - prefs.setValue(TapiJIPreferences.AUDIT_MISSING_LANGUAGE, - checkMissingLanguageButton.getSelection()); - - return super.performOk(); - } - - private Composite createComposite(Composite parent, int marginWidth, - int marginHeight) { - Composite composite = new Composite(parent, SWT.NONE); - - GridLayout indentLayout = new GridLayout(1, false); - indentLayout.marginWidth = marginWidth; - indentLayout.marginHeight = marginHeight; - indentLayout.verticalSpacing = 0; - composite.setLayout(indentLayout); - - return composite; - } - - protected void setRBAudits() { - boolean selected = rbAuditButton.getSelection(); - checkMissingValueButton.setEnabled(selected); - checkSameValueButton.setEnabled(selected); - checkMissingLanguageButton.setEnabled(selected); - } + } + }); + + field = createComposite(composite, INDENT, 0); + checkMissingValueButton = new Button(field, SWT.CHECK); + checkMissingValueButton.setSelection(prefs + .getBoolean(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)); + checkMissingValueButton.setText("Missing translation for a key"); + + field = createComposite(composite, INDENT, 0); + checkSameValueButton = new Button(field, SWT.CHECK); + checkSameValueButton.setSelection(prefs + .getBoolean(TapiJIPreferences.AUDIT_SAME_VALUE)); + checkSameValueButton + .setText("Same translations for one key in diffrent languages"); + + field = createComposite(composite, INDENT, 0); + checkMissingLanguageButton = new Button(field, SWT.CHECK); + checkMissingLanguageButton.setSelection(prefs + .getBoolean(TapiJIPreferences.AUDIT_MISSING_LANGUAGE)); + checkMissingLanguageButton + .setText("Missing languages in a ResourceBundle"); + + setRBAudits(); + + composite.pack(); + + return composite; + } + + @Override + protected void performDefaults() { + IPreferenceStore prefs = getPreferenceStore(); + + sourceAuditButton.setSelection(prefs + .getDefaultBoolean(TapiJIPreferences.AUDIT_RESOURCE)); + rbAuditButton.setSelection(prefs + .getDefaultBoolean(TapiJIPreferences.AUDIT_RB)); + checkMissingValueButton.setSelection(prefs + .getDefaultBoolean(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)); + checkSameValueButton.setSelection(prefs + .getDefaultBoolean(TapiJIPreferences.AUDIT_SAME_VALUE)); + checkMissingLanguageButton.setSelection(prefs + .getDefaultBoolean(TapiJIPreferences.AUDIT_MISSING_LANGUAGE)); + } + + @Override + public boolean performOk() { + IPreferenceStore prefs = getPreferenceStore(); + + prefs.setValue(TapiJIPreferences.AUDIT_RESOURCE, + sourceAuditButton.getSelection()); + prefs.setValue(TapiJIPreferences.AUDIT_RB, rbAuditButton.getSelection()); + prefs.setValue(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY, + checkMissingValueButton.getSelection()); + prefs.setValue(TapiJIPreferences.AUDIT_SAME_VALUE, + checkSameValueButton.getSelection()); + prefs.setValue(TapiJIPreferences.AUDIT_MISSING_LANGUAGE, + checkMissingLanguageButton.getSelection()); + + return super.performOk(); + } + + private Composite createComposite(Composite parent, int marginWidth, + int marginHeight) { + Composite composite = new Composite(parent, SWT.NONE); + + GridLayout indentLayout = new GridLayout(1, false); + indentLayout.marginWidth = marginWidth; + indentLayout.marginHeight = marginHeight; + indentLayout.verticalSpacing = 0; + composite.setLayout(indentLayout); + + return composite; + } + + protected void setRBAudits() { + boolean selected = rbAuditButton.getSelection(); + checkMissingValueButton.setEnabled(selected); + checkSameValueButton.setEnabled(selected); + checkMissingLanguageButton.setEnabled(selected); + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/CheckItem.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/CheckItem.java index e974c241..541f8043 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/CheckItem.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/CheckItem.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -11,25 +11,24 @@ ******************************************************************************/ package org.eclipse.babel.tapiji.tools.core.ui.preferences; - public class CheckItem { - boolean checked; - String name; + boolean checked; + String name; - public CheckItem(String item, boolean checked) { - this.name = item; - this.checked = checked; - } + public CheckItem(String item, boolean checked) { + this.name = item; + this.checked = checked; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public boolean getChecked() { - return checked; - } + public boolean getChecked() { + return checked; + } - public boolean equals(CheckItem item) { - return name.equals(item.getName()); - } + public boolean equals(CheckItem item) { + return name.equals(item.getName()); + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/FilePreferencePage.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/FilePreferencePage.java index e1633cd8..aa382f14 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/FilePreferencePage.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/FilePreferencePage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -36,192 +36,192 @@ import org.eclipse.ui.IWorkbenchPreferencePage; public class FilePreferencePage extends PreferencePage implements - IWorkbenchPreferencePage { - - private Table table; - protected Object dialoge; - - private Button editPatternButton; - private Button removePatternButton; - - @Override - public void init(IWorkbench workbench) { - setPreferenceStore(Activator.getDefault().getPreferenceStore()); + IWorkbenchPreferencePage { + + private Table table; + protected Object dialoge; + + private Button editPatternButton; + private Button removePatternButton; + + @Override + public void init(IWorkbench workbench) { + setPreferenceStore(Activator.getDefault().getPreferenceStore()); + } + + @Override + protected Control createContents(Composite parent) { + IPreferenceStore prefs = getPreferenceStore(); + Composite composite = new Composite(parent, SWT.SHADOW_OUT); + + composite.setLayout(new GridLayout(2, false)); + composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true)); + + Label descriptionLabel = new Label(composite, SWT.WRAP); + GridData descriptionData = new GridData(SWT.FILL, SWT.TOP, false, false); + descriptionData.horizontalSpan = 2; + descriptionLabel.setLayoutData(descriptionData); + descriptionLabel + .setText("Properties-files which match the following pattern, will not be interpreted as ResourceBundle-files"); + + table = new Table(composite, SWT.SINGLE | SWT.BORDER + | SWT.FULL_SELECTION | SWT.CHECK); + GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); + table.setLayoutData(data); + + table.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent e) { + TableItem[] selection = table.getSelection(); + if (selection.length > 0) { + editPatternButton.setEnabled(true); + removePatternButton.setEnabled(true); + } else { + editPatternButton.setEnabled(false); + removePatternButton.setEnabled(false); + } + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + // TODO Auto-generated method stub + } + }); + + List<CheckItem> patternItems = TapiJIPreferences + .getNonRbPatternAsList(); + for (CheckItem s : patternItems) { + toTableItem(table, s); } - @Override - protected Control createContents(Composite parent) { - IPreferenceStore prefs = getPreferenceStore(); - Composite composite = new Composite(parent, SWT.SHADOW_OUT); - - composite.setLayout(new GridLayout(2, false)); - composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true)); - - Label descriptionLabel = new Label(composite, SWT.WRAP); - GridData descriptionData = new GridData(SWT.FILL, SWT.TOP, false, false); - descriptionData.horizontalSpan = 2; - descriptionLabel.setLayoutData(descriptionData); - descriptionLabel - .setText("Properties-files which match the following pattern, will not be interpreted as ResourceBundle-files"); - - table = new Table(composite, SWT.SINGLE | SWT.BORDER - | SWT.FULL_SELECTION | SWT.CHECK); - GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); - table.setLayoutData(data); - - table.addSelectionListener(new SelectionListener() { - @Override - public void widgetSelected(SelectionEvent e) { - TableItem[] selection = table.getSelection(); - if (selection.length > 0) { - editPatternButton.setEnabled(true); - removePatternButton.setEnabled(true); - } else { - editPatternButton.setEnabled(false); - removePatternButton.setEnabled(false); - } - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - // TODO Auto-generated method stub - } - }); - - List<CheckItem> patternItems = TapiJIPreferences - .getNonRbPatternAsList(); - for (CheckItem s : patternItems) { - toTableItem(table, s); + Composite sitebar = new Composite(composite, SWT.NONE); + sitebar.setLayout(new GridLayout(1, false)); + sitebar.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, true)); + + Button addPatternButton = new Button(sitebar, SWT.NONE); + addPatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, + true)); + addPatternButton.setText("Add Pattern"); + addPatternButton.addMouseListener(new MouseListener() { + @Override + public void mouseUp(MouseEvent e) { + // TODO Auto-generated method stub + } + + @Override + public void mouseDown(MouseEvent e) { + String pattern = "^.*/<BASENAME>" + + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?" + + "\\.properties$"; + CreatePatternDialoge dialog = new CreatePatternDialoge(Display + .getDefault().getActiveShell(), pattern); + if (dialog.open() == InputDialog.OK) { + pattern = dialog.getPattern(); + + TableItem item = new TableItem(table, SWT.NONE); + item.setText(pattern); + item.setChecked(true); } + } + + @Override + public void mouseDoubleClick(MouseEvent e) { + // TODO Auto-generated method stub + } + }); + + editPatternButton = new Button(sitebar, SWT.NONE); + editPatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, + true)); + editPatternButton.setText("Edit"); + editPatternButton.addMouseListener(new MouseListener() { + @Override + public void mouseUp(MouseEvent e) { + // TODO Auto-generated method stub + } + + @Override + public void mouseDown(MouseEvent e) { + TableItem[] selection = table.getSelection(); + if (selection.length > 0) { + String pattern = selection[0].getText(); + + CreatePatternDialoge dialog = new CreatePatternDialoge( + Display.getDefault().getActiveShell(), pattern); + if (dialog.open() == InputDialog.OK) { + pattern = dialog.getPattern(); + TableItem item = selection[0]; + item.setText(pattern); + } + } + } + + @Override + public void mouseDoubleClick(MouseEvent e) { + // TODO Auto-generated method stub + } + }); + + removePatternButton = new Button(sitebar, SWT.NONE); + removePatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, + true)); + removePatternButton.setText("Remove"); + removePatternButton.addMouseListener(new MouseListener() { + @Override + public void mouseUp(MouseEvent e) { + // TODO Auto-generated method stub + } + + @Override + public void mouseDown(MouseEvent e) { + TableItem[] selection = table.getSelection(); + if (selection.length > 0) { + table.remove(table.indexOf(selection[0])); + } + } - Composite sitebar = new Composite(composite, SWT.NONE); - sitebar.setLayout(new GridLayout(1, false)); - sitebar.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, true)); - - Button addPatternButton = new Button(sitebar, SWT.NONE); - addPatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, - true)); - addPatternButton.setText("Add Pattern"); - addPatternButton.addMouseListener(new MouseListener() { - @Override - public void mouseUp(MouseEvent e) { - // TODO Auto-generated method stub - } - - @Override - public void mouseDown(MouseEvent e) { - String pattern = "^.*/<BASENAME>" - + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?" - + "\\.properties$"; - CreatePatternDialoge dialog = new CreatePatternDialoge(Display - .getDefault().getActiveShell(), pattern); - if (dialog.open() == InputDialog.OK) { - pattern = dialog.getPattern(); - - TableItem item = new TableItem(table, SWT.NONE); - item.setText(pattern); - item.setChecked(true); - } - } - - @Override - public void mouseDoubleClick(MouseEvent e) { - // TODO Auto-generated method stub - } - }); - - editPatternButton = new Button(sitebar, SWT.NONE); - editPatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, - true)); - editPatternButton.setText("Edit"); - editPatternButton.addMouseListener(new MouseListener() { - @Override - public void mouseUp(MouseEvent e) { - // TODO Auto-generated method stub - } - - @Override - public void mouseDown(MouseEvent e) { - TableItem[] selection = table.getSelection(); - if (selection.length > 0) { - String pattern = selection[0].getText(); - - CreatePatternDialoge dialog = new CreatePatternDialoge( - Display.getDefault().getActiveShell(), pattern); - if (dialog.open() == InputDialog.OK) { - pattern = dialog.getPattern(); - TableItem item = selection[0]; - item.setText(pattern); - } - } - } - - @Override - public void mouseDoubleClick(MouseEvent e) { - // TODO Auto-generated method stub - } - }); - - removePatternButton = new Button(sitebar, SWT.NONE); - removePatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, - true)); - removePatternButton.setText("Remove"); - removePatternButton.addMouseListener(new MouseListener() { - @Override - public void mouseUp(MouseEvent e) { - // TODO Auto-generated method stub - } - - @Override - public void mouseDown(MouseEvent e) { - TableItem[] selection = table.getSelection(); - if (selection.length > 0) { - table.remove(table.indexOf(selection[0])); - } - } - - @Override - public void mouseDoubleClick(MouseEvent e) { - // TODO Auto-generated method stub - } - }); - - composite.pack(); - - return composite; - } + @Override + public void mouseDoubleClick(MouseEvent e) { + // TODO Auto-generated method stub + } + }); - @Override - protected void performDefaults() { - IPreferenceStore prefs = getPreferenceStore(); + composite.pack(); - table.removeAll(); + return composite; + } - List<CheckItem> patterns = TapiJIPreferences.convertStringToList(prefs - .getDefaultString(TapiJIPreferences.NON_RB_PATTERN)); - for (CheckItem s : patterns) { - toTableItem(table, s); - } - } - - @Override - public boolean performOk() { - IPreferenceStore prefs = getPreferenceStore(); - List<CheckItem> patterns = new LinkedList<CheckItem>(); - for (TableItem i : table.getItems()) { - patterns.add(new CheckItem(i.getText(), i.getChecked())); - } + @Override + protected void performDefaults() { + IPreferenceStore prefs = getPreferenceStore(); - prefs.setValue(TapiJIPreferences.NON_RB_PATTERN, - TapiJIPreferences.convertListToString(patterns)); + table.removeAll(); - return super.performOk(); + List<CheckItem> patterns = TapiJIPreferences.convertStringToList(prefs + .getDefaultString(TapiJIPreferences.NON_RB_PATTERN)); + for (CheckItem s : patterns) { + toTableItem(table, s); } - - private TableItem toTableItem(Table table, CheckItem s) { - TableItem item = new TableItem(table, SWT.NONE); - item.setText(s.getName()); - item.setChecked(s.getChecked()); - return item; + } + + @Override + public boolean performOk() { + IPreferenceStore prefs = getPreferenceStore(); + List<CheckItem> patterns = new LinkedList<CheckItem>(); + for (TableItem i : table.getItems()) { + patterns.add(new CheckItem(i.getText(), i.getChecked())); } + + prefs.setValue(TapiJIPreferences.NON_RB_PATTERN, + TapiJIPreferences.convertListToString(patterns)); + + return super.performOk(); + } + + private TableItem toTableItem(Table table, CheckItem s) { + TableItem item = new TableItem(table, SWT.NONE); + item.setText(s.getName()); + item.setChecked(s.getChecked()); + return item; + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiHomePreferencePage.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiHomePreferencePage.java index b5f7d7ca..107e777a 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiHomePreferencePage.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiHomePreferencePage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -21,24 +21,24 @@ import org.eclipse.ui.IWorkbenchPreferencePage; public class TapiHomePreferencePage extends PreferencePage implements - IWorkbenchPreferencePage { + IWorkbenchPreferencePage { - @Override - public void init(IWorkbench workbench) { - // TODO Auto-generated method stub + @Override + public void init(IWorkbench workbench) { + // TODO Auto-generated method stub - } + } - @Override - protected Control createContents(Composite parent) { - Composite composite = new Composite(parent, SWT.NONE); - composite.setLayout(new GridLayout(1, true)); - composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); + @Override + protected Control createContents(Composite parent) { + Composite composite = new Composite(parent, SWT.NONE); + composite.setLayout(new GridLayout(1, true)); + composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - Label description = new Label(composite, SWT.WRAP); - description.setText("See sub-pages for settings."); + Label description = new Label(composite, SWT.WRAP); + description.setText("See sub-pages for settings."); - return parent; - } + return parent; + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferenceInitializer.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferenceInitializer.java index 95e4b264..b22c86e3 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferenceInitializer.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferenceInitializer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -19,28 +19,28 @@ public class TapiJIPreferenceInitializer extends AbstractPreferenceInitializer { - public TapiJIPreferenceInitializer() { - // TODO Auto-generated constructor stub - } - - @Override - public void initializeDefaultPreferences() { - IPreferenceStore prefs = Activator.getDefault().getPreferenceStore(); - - // ResourceBundle-Settings - List<CheckItem> patterns = new LinkedList<CheckItem>(); - patterns.add(new CheckItem("^(.)*/build\\.properties", true)); - patterns.add(new CheckItem("^(.)*/config\\.properties", true)); - patterns.add(new CheckItem("^(.)*/targetplatform/(.)*", true)); - prefs.setDefault(TapiJIPreferences.NON_RB_PATTERN, - TapiJIPreferences.convertListToString(patterns)); - - // Builder - prefs.setDefault(TapiJIPreferences.AUDIT_RESOURCE, true); - prefs.setDefault(TapiJIPreferences.AUDIT_RB, true); - prefs.setDefault(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY, true); - prefs.setDefault(TapiJIPreferences.AUDIT_SAME_VALUE, false); - prefs.setDefault(TapiJIPreferences.AUDIT_MISSING_LANGUAGE, true); - } + public TapiJIPreferenceInitializer() { + // TODO Auto-generated constructor stub + } + + @Override + public void initializeDefaultPreferences() { + IPreferenceStore prefs = Activator.getDefault().getPreferenceStore(); + + // ResourceBundle-Settings + List<CheckItem> patterns = new LinkedList<CheckItem>(); + patterns.add(new CheckItem("^(.)*/build\\.properties", true)); + patterns.add(new CheckItem("^(.)*/config\\.properties", true)); + patterns.add(new CheckItem("^(.)*/targetplatform/(.)*", true)); + prefs.setDefault(TapiJIPreferences.NON_RB_PATTERN, + TapiJIPreferences.convertListToString(patterns)); + + // Builder + prefs.setDefault(TapiJIPreferences.AUDIT_RESOURCE, true); + prefs.setDefault(TapiJIPreferences.AUDIT_RB, true); + prefs.setDefault(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY, true); + prefs.setDefault(TapiJIPreferences.AUDIT_SAME_VALUE, false); + prefs.setDefault(TapiJIPreferences.AUDIT_MISSING_LANGUAGE, true); + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferences.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferences.java index e9506c6d..e8035f11 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferences.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/preferences/TapiJIPreferences.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -21,104 +21,104 @@ public class TapiJIPreferences implements IConfiguration { - public static final String AUDIT_SAME_VALUE = "auditSameValue"; - public static final String AUDIT_UNSPEZIFIED_KEY = "auditMissingValue"; - public static final String AUDIT_MISSING_LANGUAGE = "auditMissingLanguage"; - public static final String AUDIT_RB = "auditResourceBundle"; - public static final String AUDIT_RESOURCE = "auditResource"; - - public static final String NON_RB_PATTERN = "NoRBPattern"; - - private static final IPreferenceStore PREF = Activator.getDefault() - .getPreferenceStore(); - - private static final String DELIMITER = ";"; - private static final String ATTRIBUTE_DELIMITER = ":"; - - @Override - public boolean getAuditSameValue() { - return PREF.getBoolean(AUDIT_SAME_VALUE); - } - - @Override - public boolean getAuditMissingValue() { - return PREF.getBoolean(AUDIT_UNSPEZIFIED_KEY); - } - - @Override - public boolean getAuditMissingLanguage() { - return PREF.getBoolean(AUDIT_MISSING_LANGUAGE); - } - - @Override - public boolean getAuditRb() { - return PREF.getBoolean(AUDIT_RB); - } - - @Override - public boolean getAuditResource() { - return PREF.getBoolean(AUDIT_RESOURCE); + public static final String AUDIT_SAME_VALUE = "auditSameValue"; + public static final String AUDIT_UNSPEZIFIED_KEY = "auditMissingValue"; + public static final String AUDIT_MISSING_LANGUAGE = "auditMissingLanguage"; + public static final String AUDIT_RB = "auditResourceBundle"; + public static final String AUDIT_RESOURCE = "auditResource"; + + public static final String NON_RB_PATTERN = "NoRBPattern"; + + private static final IPreferenceStore PREF = Activator.getDefault() + .getPreferenceStore(); + + private static final String DELIMITER = ";"; + private static final String ATTRIBUTE_DELIMITER = ":"; + + @Override + public boolean getAuditSameValue() { + return PREF.getBoolean(AUDIT_SAME_VALUE); + } + + @Override + public boolean getAuditMissingValue() { + return PREF.getBoolean(AUDIT_UNSPEZIFIED_KEY); + } + + @Override + public boolean getAuditMissingLanguage() { + return PREF.getBoolean(AUDIT_MISSING_LANGUAGE); + } + + @Override + public boolean getAuditRb() { + return PREF.getBoolean(AUDIT_RB); + } + + @Override + public boolean getAuditResource() { + return PREF.getBoolean(AUDIT_RESOURCE); + } + + @Override + public String getNonRbPattern() { + return PREF.getString(NON_RB_PATTERN); + } + + public static List<CheckItem> getNonRbPatternAsList() { + return convertStringToList(PREF.getString(NON_RB_PATTERN)); + } + + public static List<CheckItem> convertStringToList(String string) { + StringTokenizer tokenizer = new StringTokenizer(string, DELIMITER); + int tokenCount = tokenizer.countTokens(); + List<CheckItem> elements = new LinkedList<CheckItem>(); + + for (int i = 0; i < tokenCount; i++) { + StringTokenizer attribute = new StringTokenizer( + tokenizer.nextToken(), ATTRIBUTE_DELIMITER); + String name = attribute.nextToken(); + boolean checked; + if (attribute.nextToken().equals("true")) { + checked = true; + } else { + checked = false; + } + + elements.add(new CheckItem(name, checked)); } - - @Override - public String getNonRbPattern() { - return PREF.getString(NON_RB_PATTERN); - } - - public static List<CheckItem> getNonRbPatternAsList() { - return convertStringToList(PREF.getString(NON_RB_PATTERN)); - } - - public static List<CheckItem> convertStringToList(String string) { - StringTokenizer tokenizer = new StringTokenizer(string, DELIMITER); - int tokenCount = tokenizer.countTokens(); - List<CheckItem> elements = new LinkedList<CheckItem>(); - - for (int i = 0; i < tokenCount; i++) { - StringTokenizer attribute = new StringTokenizer( - tokenizer.nextToken(), ATTRIBUTE_DELIMITER); - String name = attribute.nextToken(); - boolean checked; - if (attribute.nextToken().equals("true")) { - checked = true; - } else { - checked = false; - } - - elements.add(new CheckItem(name, checked)); - } - return elements; - } - - public static String convertListToString(List<CheckItem> patterns) { - StringBuilder sb = new StringBuilder(); - int tokenCount = 0; - - for (CheckItem s : patterns) { - sb.append(s.getName()); - sb.append(ATTRIBUTE_DELIMITER); - if (s.checked) { - sb.append("true"); - } else { - sb.append("false"); - } - - if (++tokenCount != patterns.size()) { - sb.append(DELIMITER); - } - } - return sb.toString(); - } - - public static void addPropertyChangeListener( - IPropertyChangeListener listener) { - Activator.getDefault().getPreferenceStore() - .addPropertyChangeListener(listener); - } - - public static void removePropertyChangeListener( - IPropertyChangeListener listener) { - Activator.getDefault().getPreferenceStore() - .removePropertyChangeListener(listener); + return elements; + } + + public static String convertListToString(List<CheckItem> patterns) { + StringBuilder sb = new StringBuilder(); + int tokenCount = 0; + + for (CheckItem s : patterns) { + sb.append(s.getName()); + sb.append(ATTRIBUTE_DELIMITER); + if (s.checked) { + sb.append("true"); + } else { + sb.append("false"); + } + + if (++tokenCount != patterns.size()) { + sb.append(DELIMITER); + } } + return sb.toString(); + } + + public static void addPropertyChangeListener( + IPropertyChangeListener listener) { + Activator.getDefault().getPreferenceStore() + .addPropertyChangeListener(listener); + } + + public static void removePropertyChangeListener( + IPropertyChangeListener listener) { + Activator.getDefault().getPreferenceStore() + .removePropertyChangeListener(listener); + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundle.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundle.java index 1ef75780..2e8ee6ed 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundle.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundle.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -38,164 +38,164 @@ public class CreateResourceBundle implements IMarkerResolution2 { - private IResource resource; - private int start; - private int end; - private String key; - private boolean jsfContext; - private final String newBunldeWizard = "org.eclipse.babel.editor.wizards.ResourceBundleWizard"; - - public CreateResourceBundle(String key, IResource resource, int start, - int end) { - this.key = ResourceUtils.deriveNonExistingRBName(key, - ResourceBundleManager.getManager(resource.getProject())); - this.resource = resource; - this.start = start; - this.end = end; - this.jsfContext = jsfContext; + private IResource resource; + private int start; + private int end; + private String key; + private boolean jsfContext; + private final String newBunldeWizard = "org.eclipse.babel.editor.wizards.ResourceBundleWizard"; + + public CreateResourceBundle(String key, IResource resource, int start, + int end) { + this.key = ResourceUtils.deriveNonExistingRBName(key, + ResourceBundleManager.getManager(resource.getProject())); + this.resource = resource; + this.start = start; + this.end = end; + this.jsfContext = jsfContext; + } + + @Override + public String getDescription() { + return "Creates a new Resource-Bundle with the id '" + key + "'"; + } + + @Override + public Image getImage() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getLabel() { + return "Create Resource-Bundle '" + key + "'"; + } + + @Override + public void run(IMarker marker) { + runAction(); + } + + protected void runAction() { + // First see if this is a "new wizard". + IWizardDescriptor descriptor = PlatformUI.getWorkbench() + .getNewWizardRegistry().findWizard(newBunldeWizard); + // If not check if it is an "import wizard". + if (descriptor == null) { + descriptor = PlatformUI.getWorkbench().getImportWizardRegistry() + .findWizard(newBunldeWizard); } - - @Override - public String getDescription() { - return "Creates a new Resource-Bundle with the id '" + key + "'"; - } - - @Override - public Image getImage() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getLabel() { - return "Create Resource-Bundle '" + key + "'"; + // Or maybe an export wizard + if (descriptor == null) { + descriptor = PlatformUI.getWorkbench().getExportWizardRegistry() + .findWizard(newBunldeWizard); } - - @Override - public void run(IMarker marker) { - runAction(); - } - - protected void runAction() { - // First see if this is a "new wizard". - IWizardDescriptor descriptor = PlatformUI.getWorkbench() - .getNewWizardRegistry().findWizard(newBunldeWizard); - // If not check if it is an "import wizard". - if (descriptor == null) { - descriptor = PlatformUI.getWorkbench().getImportWizardRegistry() - .findWizard(newBunldeWizard); + try { + // Then if we have a wizard, open it. + if (descriptor != null) { + IWizard wizard = descriptor.createWizard(); + if (!(wizard instanceof IResourceBundleWizard)) { + return; } - // Or maybe an export wizard - if (descriptor == null) { - descriptor = PlatformUI.getWorkbench().getExportWizardRegistry() - .findWizard(newBunldeWizard); + + IResourceBundleWizard rbw = (IResourceBundleWizard) wizard; + String[] keySilbings = key.split("\\."); + String rbName = keySilbings[keySilbings.length - 1]; + String packageName = ""; + + rbw.setBundleId(rbName); + + // Set the default path according to the specified package name + String pathName = ""; + if (keySilbings.length > 1) { + try { + IJavaProject jp = JavaCore + .create(resource.getProject()); + packageName = key.substring(0, key.lastIndexOf(".")); + + for (IPackageFragmentRoot fr : jp + .getAllPackageFragmentRoots()) { + IPackageFragment pf = fr + .getPackageFragment(packageName); + if (pf.exists()) { + pathName = pf.getResource().getFullPath() + .removeFirstSegments(0).toOSString(); + break; + } + } + } catch (Exception e) { + pathName = ""; + } } + try { - // Then if we have a wizard, open it. - if (descriptor != null) { - IWizard wizard = descriptor.createWizard(); - if (!(wizard instanceof IResourceBundleWizard)) { - return; - } - - IResourceBundleWizard rbw = (IResourceBundleWizard) wizard; - String[] keySilbings = key.split("\\."); - String rbName = keySilbings[keySilbings.length - 1]; - String packageName = ""; - - rbw.setBundleId(rbName); - - // Set the default path according to the specified package name - String pathName = ""; - if (keySilbings.length > 1) { - try { - IJavaProject jp = JavaCore - .create(resource.getProject()); - packageName = key.substring(0, key.lastIndexOf(".")); - - for (IPackageFragmentRoot fr : jp - .getAllPackageFragmentRoots()) { - IPackageFragment pf = fr - .getPackageFragment(packageName); - if (pf.exists()) { - pathName = pf.getResource().getFullPath() - .removeFirstSegments(0).toOSString(); - break; - } - } - } catch (Exception e) { - pathName = ""; - } - } - - try { - IJavaProject jp = JavaCore.create(resource.getProject()); - if (pathName.trim().equals("")) { - for (IPackageFragmentRoot fr : jp - .getAllPackageFragmentRoots()) { - if (!fr.isReadOnly()) { - pathName = fr.getResource().getFullPath() - .removeFirstSegments(0).toOSString(); - break; - } - } - } - } catch (Exception e) { - pathName = ""; - } - - rbw.setDefaultPath(pathName); - - WizardDialog wd = new WizardDialog(Display.getDefault() - .getActiveShell(), wizard); - wd.setTitle(wizard.getWindowTitle()); - if (wd.open() == WizardDialog.OK) { - try { - resource.getProject().build( - IncrementalProjectBuilder.FULL_BUILD, - I18nBuilder.BUILDER_ID, null, null); - } catch (CoreException e) { - Logger.logError(e); - } - - ITextFileBufferManager bufferManager = FileBuffers - .getTextFileBufferManager(); - IPath path = resource.getRawLocation(); - try { - bufferManager.connect(path, null); - ITextFileBuffer textFileBuffer = bufferManager - .getTextFileBuffer(path); - IDocument document = textFileBuffer.getDocument(); - - if (document.get().charAt(start - 1) == '"' - && document.get().charAt(start) != '"') { - start--; - end++; - } - if (document.get().charAt(end + 1) == '"' - && document.get().charAt(end) != '"') { - end++; - } - - document.replace(start, end - start, "\"" - + (packageName.equals("") ? "" : packageName - + ".") + rbName + "\""); - - textFileBuffer.commit(null, false); - } catch (Exception e) { - Logger.logError(e); - } finally { - try { - bufferManager.disconnect(path, null); - } catch (CoreException e) { - Logger.logError(e); - } - } - } + IJavaProject jp = JavaCore.create(resource.getProject()); + if (pathName.trim().equals("")) { + for (IPackageFragmentRoot fr : jp + .getAllPackageFragmentRoots()) { + if (!fr.isReadOnly()) { + pathName = fr.getResource().getFullPath() + .removeFirstSegments(0).toOSString(); + break; + } } - } catch (CoreException e) { + } + } catch (Exception e) { + pathName = ""; + } + + rbw.setDefaultPath(pathName); + + WizardDialog wd = new WizardDialog(Display.getDefault() + .getActiveShell(), wizard); + wd.setTitle(wizard.getWindowTitle()); + if (wd.open() == WizardDialog.OK) { + try { + resource.getProject().build( + IncrementalProjectBuilder.FULL_BUILD, + I18nBuilder.BUILDER_ID, null, null); + } catch (CoreException e) { Logger.logError(e); + } + + ITextFileBufferManager bufferManager = FileBuffers + .getTextFileBufferManager(); + IPath path = resource.getRawLocation(); + try { + bufferManager.connect(path, null); + ITextFileBuffer textFileBuffer = bufferManager + .getTextFileBuffer(path); + IDocument document = textFileBuffer.getDocument(); + + if (document.get().charAt(start - 1) == '"' + && document.get().charAt(start) != '"') { + start--; + end++; + } + if (document.get().charAt(end + 1) == '"' + && document.get().charAt(end) != '"') { + end++; + } + + document.replace(start, end - start, "\"" + + (packageName.equals("") ? "" : packageName + + ".") + rbName + "\""); + + textFileBuffer.commit(null, false); + } catch (Exception e) { + Logger.logError(e); + } finally { + try { + bufferManager.disconnect(path, null); + } catch (CoreException e) { + Logger.logError(e); + } + } } + } + } catch (CoreException e) { + Logger.logError(e); } + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java index f93a94e0..14a3f30a 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -31,73 +31,73 @@ public class CreateResourceBundleEntry implements IMarkerResolution2 { - private String key; - private String bundleId; + private String key; + private String bundleId; - public CreateResourceBundleEntry(String key, String bundleId) { - this.key = key; - this.bundleId = bundleId; - } - - @Override - public String getDescription() { - return "Creates a new Resource-Bundle entry for the property-key '" - + key + "'"; - } + public CreateResourceBundleEntry(String key, String bundleId) { + this.key = key; + this.bundleId = bundleId; + } - @Override - public Image getImage() { - // TODO Auto-generated method stub - return null; - } + @Override + public String getDescription() { + return "Creates a new Resource-Bundle entry for the property-key '" + + key + "'"; + } - @Override - public String getLabel() { - return "Create Resource-Bundle entry for '" + key + "'"; - } + @Override + public Image getImage() { + // TODO Auto-generated method stub + return null; + } - @Override - public void run(IMarker marker) { - int startPos = marker.getAttribute(IMarker.CHAR_START, 0); - int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos; - IResource resource = marker.getResource(); + @Override + public String getLabel() { + return "Create Resource-Bundle entry for '" + key + "'"; + } - ITextFileBufferManager bufferManager = FileBuffers - .getTextFileBufferManager(); - IPath path = resource.getRawLocation(); - try { - bufferManager.connect(path, null); - ITextFileBuffer textFileBuffer = bufferManager - .getTextFileBuffer(path); - IDocument document = textFileBuffer.getDocument(); + @Override + public void run(IMarker marker) { + int startPos = marker.getAttribute(IMarker.CHAR_START, 0); + int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos; + IResource resource = marker.getResource(); - CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( - Display.getDefault().getActiveShell()); + ITextFileBufferManager bufferManager = FileBuffers + .getTextFileBufferManager(); + IPath path = resource.getRawLocation(); + try { + bufferManager.connect(path, null); + ITextFileBuffer textFileBuffer = bufferManager + .getTextFileBuffer(path); + IDocument document = textFileBuffer.getDocument(); - DialogConfiguration config = dialog.new DialogConfiguration(); - config.setPreselectedKey(key != null ? key : ""); - config.setPreselectedMessage(""); - config.setPreselectedBundle(bundleId); - config.setPreselectedLocale(""); - config.setProjectName(resource.getProject().getName()); + CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( + Display.getDefault().getActiveShell()); - dialog.setDialogConfiguration(config); + DialogConfiguration config = dialog.new DialogConfiguration(); + config.setPreselectedKey(key != null ? key : ""); + config.setPreselectedMessage(""); + config.setPreselectedBundle(bundleId); + config.setPreselectedLocale(""); + config.setProjectName(resource.getProject().getName()); - if (dialog.open() != InputDialog.OK) { - return; - } - } catch (Exception e) { - Logger.logError(e); - } finally { - try { - resource.getProject().build( - IncrementalProjectBuilder.FULL_BUILD, - I18nBuilder.BUILDER_ID, null, null); - } catch (CoreException e) { - Logger.logError(e); - } - } + dialog.setDialogConfiguration(config); + if (dialog.open() != InputDialog.OK) { + return; + } + } catch (Exception e) { + Logger.logError(e); + } finally { + try { + resource.getProject().build( + IncrementalProjectBuilder.FULL_BUILD, + I18nBuilder.BUILDER_ID, null, null); + } catch (CoreException e) { + Logger.logError(e); + } } + } + } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/IncludeResource.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/IncludeResource.java index ea69e187..d4d389c8 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/IncludeResource.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/quickfix/IncludeResource.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -25,55 +25,55 @@ public class IncludeResource implements IMarkerResolution2 { - private String bundleName; - private Set<IResource> bundleResources; + private String bundleName; + private Set<IResource> bundleResources; - public IncludeResource(String bundleName, Set<IResource> bundleResources) { - this.bundleResources = bundleResources; - this.bundleName = bundleName; - } + public IncludeResource(String bundleName, Set<IResource> bundleResources) { + this.bundleResources = bundleResources; + this.bundleName = bundleName; + } - @Override - public String getDescription() { - return "The Resource-Bundle with id '" - + bundleName - + "' has been " - + "excluded from Internationalization. Based on this fact, no internationalization " - + "supoort is provided for this Resource-Bundle. Performing this action, internationalization " - + "support for '" + bundleName + "' will be enabled"; - } + @Override + public String getDescription() { + return "The Resource-Bundle with id '" + + bundleName + + "' has been " + + "excluded from Internationalization. Based on this fact, no internationalization " + + "supoort is provided for this Resource-Bundle. Performing this action, internationalization " + + "support for '" + bundleName + "' will be enabled"; + } - @Override - public Image getImage() { - // TODO Auto-generated method stub - return null; - } + @Override + public Image getImage() { + // TODO Auto-generated method stub + return null; + } - @Override - public String getLabel() { - return "Include excluded Resource-Bundle '" + bundleName + "'"; - } + @Override + public String getLabel() { + return "Include excluded Resource-Bundle '" + bundleName + "'"; + } - @Override - public void run(final IMarker marker) { - IWorkbench wb = PlatformUI.getWorkbench(); - IProgressService ps = wb.getProgressService(); - try { - ps.busyCursorWhile(new IRunnableWithProgress() { - public void run(IProgressMonitor pm) { - ResourceBundleManager manager = ResourceBundleManager - .getManager(marker.getResource().getProject()); - pm.beginTask("Including resources to Internationalization", - bundleResources.size()); - for (IResource resource : bundleResources) { - manager.includeResource(resource, pm); - pm.worked(1); - } - pm.done(); - } - }); - } catch (Exception e) { + @Override + public void run(final IMarker marker) { + IWorkbench wb = PlatformUI.getWorkbench(); + IProgressService ps = wb.getProgressService(); + try { + ps.busyCursorWhile(new IRunnableWithProgress() { + public void run(IProgressMonitor pm) { + ResourceBundleManager manager = ResourceBundleManager + .getManager(marker.getResource().getProject()); + pm.beginTask("Including resources to Internationalization", + bundleResources.size()); + for (IResource resource : bundleResources) { + manager.includeResource(resource, pm); + pm.worked(1); + } + pm.done(); } + }); + } catch (Exception e) { } + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/FontUtils.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/FontUtils.java index fd0942a5..858644a4 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/FontUtils.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/FontUtils.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -19,84 +19,84 @@ public class FontUtils { - /** - * Gets a system color. - * - * @param colorId - * SWT constant - * @return system color - */ - public static Color getSystemColor(int colorId) { - return Activator.getDefault().getWorkbench().getDisplay() - .getSystemColor(colorId); - } + /** + * Gets a system color. + * + * @param colorId + * SWT constant + * @return system color + */ + public static Color getSystemColor(int colorId) { + return Activator.getDefault().getWorkbench().getDisplay() + .getSystemColor(colorId); + } - /** - * Creates a font by altering the font associated with the given control and - * applying the provided style (size is unaffected). - * - * @param control - * control we base our font data on - * @param style - * style to apply to the new font - * @return newly created font - */ - public static Font createFont(Control control, int style) { - // TODO consider dropping in favor of control-less version? - return createFont(control, style, 0); - } + /** + * Creates a font by altering the font associated with the given control and + * applying the provided style (size is unaffected). + * + * @param control + * control we base our font data on + * @param style + * style to apply to the new font + * @return newly created font + */ + public static Font createFont(Control control, int style) { + // TODO consider dropping in favor of control-less version? + return createFont(control, style, 0); + } - /** - * Creates a font by altering the font associated with the given control and - * applying the provided style and relative size. - * - * @param control - * control we base our font data on - * @param style - * style to apply to the new font - * @param relSize - * size to add or remove from the control size - * @return newly created font - */ - public static Font createFont(Control control, int style, int relSize) { - // TODO consider dropping in favor of control-less version? - FontData[] fontData = control.getFont().getFontData(); - for (int i = 0; i < fontData.length; i++) { - fontData[i].setHeight(fontData[i].getHeight() + relSize); - fontData[i].setStyle(style); - } - return new Font(control.getDisplay(), fontData); + /** + * Creates a font by altering the font associated with the given control and + * applying the provided style and relative size. + * + * @param control + * control we base our font data on + * @param style + * style to apply to the new font + * @param relSize + * size to add or remove from the control size + * @return newly created font + */ + public static Font createFont(Control control, int style, int relSize) { + // TODO consider dropping in favor of control-less version? + FontData[] fontData = control.getFont().getFontData(); + for (int i = 0; i < fontData.length; i++) { + fontData[i].setHeight(fontData[i].getHeight() + relSize); + fontData[i].setStyle(style); } + return new Font(control.getDisplay(), fontData); + } - /** - * Creates a font by altering the system font and applying the provided - * style and relative size. - * - * @param style - * style to apply to the new font - * @return newly created font - */ - public static Font createFont(int style) { - return createFont(style, 0); - } + /** + * Creates a font by altering the system font and applying the provided + * style and relative size. + * + * @param style + * style to apply to the new font + * @return newly created font + */ + public static Font createFont(int style) { + return createFont(style, 0); + } - /** - * Creates a font by altering the system font and applying the provided - * style and relative size. - * - * @param style - * style to apply to the new font - * @param relSize - * size to add or remove from the control size - * @return newly created font - */ - public static Font createFont(int style, int relSize) { - Display display = Activator.getDefault().getWorkbench().getDisplay(); - FontData[] fontData = display.getSystemFont().getFontData(); - for (int i = 0; i < fontData.length; i++) { - fontData[i].setHeight(fontData[i].getHeight() + relSize); - fontData[i].setStyle(style); - } - return new Font(display, fontData); + /** + * Creates a font by altering the system font and applying the provided + * style and relative size. + * + * @param style + * style to apply to the new font + * @param relSize + * size to add or remove from the control size + * @return newly created font + */ + public static Font createFont(int style, int relSize) { + Display display = Activator.getDefault().getWorkbench().getDisplay(); + FontData[] fontData = display.getSystemFont().getFontData(); + for (int i = 0; i < fontData.length; i++) { + fontData[i].setHeight(fontData[i].getHeight() + relSize); + fontData[i].setStyle(style); } + return new Font(display, fontData); + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ImageUtils.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ImageUtils.java index 52e56608..409e3743 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ImageUtils.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ImageUtils.java @@ -1,12 +1,13 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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: - * Martin Reiterer - initial API and implementation + * Pascal Essiembre - initial API and implementation + * Martin Reiterer - extracting image handling from UIUtils ******************************************************************************/ package org.eclipse.babel.tapiji.tools.core.ui.utils; @@ -14,12 +15,6 @@ import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.swt.graphics.Image; -/** - * Utility methods related to application UI. - * - * @author Pascal Essiembre ([email protected]) - * @version $Author: nl_carnage $ $Revision: 1.12 $ $Date: 2007/09/11 16:11:10 $ - */ public final class ImageUtils { /** Name of resource bundle image. */ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LanguageUtils.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LanguageUtils.java index a3889000..ecadce35 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LanguageUtils.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LanguageUtils.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -31,107 +31,107 @@ import org.eclipse.core.runtime.jobs.Job; public class LanguageUtils { - private static final String INITIALISATION_STRING = PropertiesSerializer.GENERATED_BY; + private static final String INITIALISATION_STRING = PropertiesSerializer.GENERATED_BY; - private static IFile createFile(IContainer container, String fileName, - IProgressMonitor monitor) throws CoreException, IOException { - if (!container.exists()) { - if (container instanceof IFolder) { - ((IFolder) container).create(false, false, monitor); - } - } - - IFile file = container.getFile(new Path(fileName)); - if (!file.exists()) { - InputStream s = new StringBufferInputStream(INITIALISATION_STRING); - file.create(s, true, monitor); - s.close(); - } - - return file; + private static IFile createFile(IContainer container, String fileName, + IProgressMonitor monitor) throws CoreException, IOException { + if (!container.exists()) { + if (container instanceof IFolder) { + ((IFolder) container).create(false, false, monitor); + } } - /** - * Checks if ResourceBundle provides a given locale. If the locale is not - * provided, creates a new properties-file with the ResourceBundle-basename - * and the index of the given locale. - * - * @param project - * @param rbId - * @param locale - */ - public static void addLanguageToResourceBundle(IProject project, - final String rbId, final Locale locale) { - ResourceBundleManager rbManager = ResourceBundleManager - .getManager(project); - - if (rbManager.getProvidedLocales(rbId).contains(locale)) { - return; - } + IFile file = container.getFile(new Path(fileName)); + if (!file.exists()) { + InputStream s = new StringBufferInputStream(INITIALISATION_STRING); + file.create(s, true, monitor); + s.close(); + } - final IResource file = rbManager.getRandomFile(rbId); - final IContainer c = ResourceUtils.getCorrespondingFolders( - file.getParent(), project); + return file; + } - new Job("create new propertfile") { - @Override - protected IStatus run(IProgressMonitor monitor) { - try { - String newFilename = ResourceBundleManager - .getResourceBundleName(file); - if (locale.getLanguage() != null - && !locale.getLanguage().equalsIgnoreCase( - ResourceBundleManager.defaultLocaleTag) - && !locale.getLanguage().equals("")) { - newFilename += "_" + locale.getLanguage(); - } - if (locale.getCountry() != null - && !locale.getCountry().equals("")) { - newFilename += "_" + locale.getCountry(); - } - if (locale.getVariant() != null - && !locale.getCountry().equals("")) { - newFilename += "_" + locale.getVariant(); - } - newFilename += ".properties"; + /** + * Checks if ResourceBundle provides a given locale. If the locale is not + * provided, creates a new properties-file with the ResourceBundle-basename + * and the index of the given locale. + * + * @param project + * @param rbId + * @param locale + */ + public static void addLanguageToResourceBundle(IProject project, + final String rbId, final Locale locale) { + ResourceBundleManager rbManager = ResourceBundleManager + .getManager(project); - createFile(c, newFilename, monitor); - } catch (CoreException e) { - Logger.logError( - "File for locale " - + locale - + " could not be created in ResourceBundle " - + rbId, e); - } catch (IOException e) { - Logger.logError( - "File for locale " - + locale - + " could not be created in ResourceBundle " - + rbId, e); - } - monitor.done(); - return Status.OK_STATUS; - } - }.schedule(); + if (rbManager.getProvidedLocales(rbId).contains(locale)) { + return; } - /** - * Adds new properties-files for a given locale to all ResourceBundles of a - * project. If a ResourceBundle already contains the language, happens - * nothing. - * - * @param project - * @param locale - */ - public static void addLanguageToProject(IProject project, Locale locale) { - ResourceBundleManager rbManager = ResourceBundleManager - .getManager(project); + final IResource file = rbManager.getRandomFile(rbId); + final IContainer c = ResourceUtils.getCorrespondingFolders( + file.getParent(), project); + + new Job("create new propertfile") { + @Override + protected IStatus run(IProgressMonitor monitor) { + try { + String newFilename = ResourceBundleManager + .getResourceBundleName(file); + if (locale.getLanguage() != null + && !locale.getLanguage().equalsIgnoreCase( + ResourceBundleManager.defaultLocaleTag) + && !locale.getLanguage().equals("")) { + newFilename += "_" + locale.getLanguage(); + } + if (locale.getCountry() != null + && !locale.getCountry().equals("")) { + newFilename += "_" + locale.getCountry(); + } + if (locale.getVariant() != null + && !locale.getCountry().equals("")) { + newFilename += "_" + locale.getVariant(); + } + newFilename += ".properties"; - // Audit if all resourecbundles provide this locale. if not - add new - // file - for (String rbId : rbManager.getResourceBundleIdentifiers()) { - addLanguageToResourceBundle(project, rbId, locale); + createFile(c, newFilename, monitor); + } catch (CoreException e) { + Logger.logError( + "File for locale " + + locale + + " could not be created in ResourceBundle " + + rbId, e); + } catch (IOException e) { + Logger.logError( + "File for locale " + + locale + + " could not be created in ResourceBundle " + + rbId, e); } + monitor.done(); + return Status.OK_STATUS; + } + }.schedule(); + } + + /** + * Adds new properties-files for a given locale to all ResourceBundles of a + * project. If a ResourceBundle already contains the language, happens + * nothing. + * + * @param project + * @param locale + */ + public static void addLanguageToProject(IProject project, Locale locale) { + ResourceBundleManager rbManager = ResourceBundleManager + .getManager(project); + + // Audit if all resourecbundles provide this locale. if not - add new + // file + for (String rbId : rbManager.getResourceBundleIdentifiers()) { + addLanguageToResourceBundle(project, rbId, locale); } + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LocaleUtils.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LocaleUtils.java index 5a104dd3..6f0bb4f4 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LocaleUtils.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/LocaleUtils.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -17,34 +17,34 @@ public class LocaleUtils { - public static Locale getLocaleByDisplayName(Set<Locale> locales, - String displayName) { - for (Locale l : locales) { - String name = l == null ? ResourceBundleManager.defaultLocaleTag - : l.getDisplayName(); - if (name.equals(displayName) - || (name.trim().length() == 0 && displayName - .equals(ResourceBundleManager.defaultLocaleTag))) { - return l; - } - } - - return null; + public static Locale getLocaleByDisplayName(Set<Locale> locales, + String displayName) { + for (Locale l : locales) { + String name = l == null ? ResourceBundleManager.defaultLocaleTag + : l.getDisplayName(); + if (name.equals(displayName) + || (name.trim().length() == 0 && displayName + .equals(ResourceBundleManager.defaultLocaleTag))) { + return l; + } } - public static boolean containsLocaleByDisplayName(Set<Locale> locales, - String displayName) { - for (Locale l : locales) { - String name = l == null ? ResourceBundleManager.defaultLocaleTag - : l.getDisplayName(); - if (name.equals(displayName) - || (name.trim().length() == 0 && displayName - .equals(ResourceBundleManager.defaultLocaleTag))) { - return true; - } - } - - return false; + return null; + } + + public static boolean containsLocaleByDisplayName(Set<Locale> locales, + String displayName) { + for (Locale l : locales) { + String name = l == null ? ResourceBundleManager.defaultLocaleTag + : l.getDisplayName(); + if (name.equals(displayName) + || (name.trim().length() == 0 && displayName + .equals(ResourceBundleManager.defaultLocaleTag))) { + return true; + } } + return false; + } + } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/RBFileUtils.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/RBFileUtils.java index dd0b1591..5f8ff62d 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/RBFileUtils.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/RBFileUtils.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -39,211 +39,211 @@ * */ public class RBFileUtils extends Action { - public static final String PROPERTIES_EXT = "properties"; - - /** - * Returns true if a file is a ResourceBundle-file - */ - public static boolean isResourceBundleFile(IResource file) { - boolean isValied = false; - - if (file != null && file instanceof IFile && !file.isDerived() - && file.getFileExtension() != null - && file.getFileExtension().equalsIgnoreCase("properties")) { - isValied = true; - - // Check if file is not in the blacklist - IPreferenceStore pref = null; - if (Activator.getDefault() != null) { - pref = Activator.getDefault().getPreferenceStore(); - } - - if (pref != null) { - List<CheckItem> list = TapiJIPreferences - .getNonRbPatternAsList(); - for (CheckItem item : list) { - if (item.getChecked() - && file.getFullPath().toString() - .matches(item.getName())) { - isValied = false; - - // if properties-file is not RB-file and has - // ResouceBundleMarker, deletes all ResouceBundleMarker - // of the file - if (org.eclipse.babel.tapiji.tools.core.util.RBFileUtils - .hasResourceBundleMarker(file)) { - try { - file.deleteMarkers(EditorUtils.RB_MARKER_ID, - true, IResource.DEPTH_INFINITE); - } catch (CoreException e) { - } - } - } - } + public static final String PROPERTIES_EXT = "properties"; + + /** + * Returns true if a file is a ResourceBundle-file + */ + public static boolean isResourceBundleFile(IResource file) { + boolean isValied = false; + + if (file != null && file instanceof IFile && !file.isDerived() + && file.getFileExtension() != null + && file.getFileExtension().equalsIgnoreCase("properties")) { + isValied = true; + + // Check if file is not in the blacklist + IPreferenceStore pref = null; + if (Activator.getDefault() != null) { + pref = Activator.getDefault().getPreferenceStore(); + } + + if (pref != null) { + List<CheckItem> list = TapiJIPreferences + .getNonRbPatternAsList(); + for (CheckItem item : list) { + if (item.getChecked() + && file.getFullPath().toString() + .matches(item.getName())) { + isValied = false; + + // if properties-file is not RB-file and has + // ResouceBundleMarker, deletes all ResouceBundleMarker + // of the file + if (org.eclipse.babel.tapiji.tools.core.util.RBFileUtils + .hasResourceBundleMarker(file)) { + try { + file.deleteMarkers(EditorUtils.RB_MARKER_ID, + true, IResource.DEPTH_INFINITE); + } catch (CoreException e) { + } } + } } - - return isValied; + } } - /** - * @param container - * @return Set with all ResourceBundles in this container - */ - public static Set<String> getResourceBundleIds(IContainer container) { - Set<String> resourcebundles = new HashSet<String>(); - - try { - for (IResource r : container.members()) { - if (r instanceof IFile) { - String resourcebundle = getCorrespondingResourceBundleId((IFile) r); - if (resourcebundle != null) { - resourcebundles.add(resourcebundle); - } - } - } - } catch (CoreException e) {/* resourcebundle.size()==0 */ + return isValied; + } + + /** + * @param container + * @return Set with all ResourceBundles in this container + */ + public static Set<String> getResourceBundleIds(IContainer container) { + Set<String> resourcebundles = new HashSet<String>(); + + try { + for (IResource r : container.members()) { + if (r instanceof IFile) { + String resourcebundle = getCorrespondingResourceBundleId((IFile) r); + if (resourcebundle != null) { + resourcebundles.add(resourcebundle); + } } - - return resourcebundles; + } + } catch (CoreException e) {/* resourcebundle.size()==0 */ } - /** - * - * @param file - * @return ResourceBundle-name or null if no ResourceBundle contains the - * file - */ - // TODO integrate in ResourceBundleManager - public static String getCorrespondingResourceBundleId(IFile file) { - ResourceBundleManager rbmanager = ResourceBundleManager.getManager(file - .getProject()); - String possibleRBId = null; - - if (isResourceBundleFile(file)) { - possibleRBId = ResourceBundleManager.getResourceBundleId(file); - - for (String rbId : rbmanager.getResourceBundleIdentifiers()) { - if (possibleRBId.equals(rbId)) { - return possibleRBId; - } - } + return resourcebundles; + } + + /** + * + * @param file + * @return ResourceBundle-name or null if no ResourceBundle contains the + * file + */ + // TODO integrate in ResourceBundleManager + public static String getCorrespondingResourceBundleId(IFile file) { + ResourceBundleManager rbmanager = ResourceBundleManager.getManager(file + .getProject()); + String possibleRBId = null; + + if (isResourceBundleFile(file)) { + possibleRBId = ResourceBundleManager.getResourceBundleId(file); + + for (String rbId : rbmanager.getResourceBundleIdentifiers()) { + if (possibleRBId.equals(rbId)) { + return possibleRBId; } - return null; + } } - - /** - * Removes the properties-file of a given locale from a ResourceBundle, if - * the ResourceBundle provides the locale. - * - * @param project - * @param rbId - * @param locale - */ - public static void removeFileFromResourceBundle(IProject project, - String rbId, Locale locale) { - ResourceBundleManager rbManager = ResourceBundleManager - .getManager(project); - - if (!rbManager.getProvidedLocales(rbId).contains(locale)) { - return; - } - - final IFile file = rbManager.getResourceBundleFile(rbId, locale); - final String filename = file.getName(); - - new Job("remove properties-file") { - @Override - protected IStatus run(IProgressMonitor monitor) { - try { - EditorUtils.deleteAuditMarkersForResource(file); - file.delete(true, monitor); - } catch (CoreException e) { - // MessageDialog.openError(Display.getCurrent().getActiveShell(), - // "Confirm", "File could not be deleted"); - Logger.logError("File could not be deleted", e); - } - return Status.OK_STATUS; - } - }.schedule(); + return null; + } + + /** + * Removes the properties-file of a given locale from a ResourceBundle, if + * the ResourceBundle provides the locale. + * + * @param project + * @param rbId + * @param locale + */ + public static void removeFileFromResourceBundle(IProject project, + String rbId, Locale locale) { + ResourceBundleManager rbManager = ResourceBundleManager + .getManager(project); + + if (!rbManager.getProvidedLocales(rbId).contains(locale)) { + return; } - /** - * Removes all properties-files of a given locale from all ResourceBundles - * of a project. - * - * @param rbManager - * @param locale - * @return - */ - public static void removeLanguageFromProject(IProject project, Locale locale) { - ResourceBundleManager rbManager = ResourceBundleManager - .getManager(project); - - for (String rbId : rbManager.getResourceBundleIdentifiers()) { - removeFileFromResourceBundle(project, rbId, locale); - } + final IFile file = rbManager.getResourceBundleFile(rbId, locale); + final String filename = file.getName(); - } - - /** - * @return the locale of a given properties-file - */ - public static Locale getLocale(IFile file) { - String localeID = file.getName(); - localeID = localeID.substring(0, - localeID.length() - "properties".length() - 1); - String baseBundleName = ResourceBundleManager - .getResourceBundleName(file); - - Locale locale; - if (localeID.length() == baseBundleName.length()) { - locale = null; // Default locale - } else { - localeID = localeID.substring(baseBundleName.length() + 1); - String[] localeTokens = localeID.split("_"); - switch (localeTokens.length) { - case 1: - locale = new Locale(localeTokens[0]); - break; - case 2: - locale = new Locale(localeTokens[0], localeTokens[1]); - break; - case 3: - locale = new Locale(localeTokens[0], localeTokens[1], - localeTokens[2]); - break; - default: - locale = new Locale(""); - break; - } + new Job("remove properties-file") { + @Override + protected IStatus run(IProgressMonitor monitor) { + try { + EditorUtils.deleteAuditMarkersForResource(file); + file.delete(true, monitor); + } catch (CoreException e) { + // MessageDialog.openError(Display.getCurrent().getActiveShell(), + // "Confirm", "File could not be deleted"); + Logger.logError("File could not be deleted", e); } - return locale; + return Status.OK_STATUS; + } + }.schedule(); + } + + /** + * Removes all properties-files of a given locale from all ResourceBundles + * of a project. + * + * @param rbManager + * @param locale + * @return + */ + public static void removeLanguageFromProject(IProject project, Locale locale) { + ResourceBundleManager rbManager = ResourceBundleManager + .getManager(project); + + for (String rbId : rbManager.getResourceBundleIdentifiers()) { + removeFileFromResourceBundle(project, rbId, locale); } - /** - * @return number of ResourceBundles in the subtree - */ - public static int countRecursiveResourceBundle(IContainer container) { - return getSubResourceBundle(container).size(); + } + + /** + * @return the locale of a given properties-file + */ + public static Locale getLocale(IFile file) { + String localeID = file.getName(); + localeID = localeID.substring(0, + localeID.length() - "properties".length() - 1); + String baseBundleName = ResourceBundleManager + .getResourceBundleName(file); + + Locale locale; + if (localeID.length() == baseBundleName.length()) { + locale = null; // Default locale + } else { + localeID = localeID.substring(baseBundleName.length() + 1); + String[] localeTokens = localeID.split("_"); + switch (localeTokens.length) { + case 1: + locale = new Locale(localeTokens[0]); + break; + case 2: + locale = new Locale(localeTokens[0], localeTokens[1]); + break; + case 3: + locale = new Locale(localeTokens[0], localeTokens[1], + localeTokens[2]); + break; + default: + locale = new Locale(""); + break; + } } - - private static List<String> getSubResourceBundle(IContainer container) { - ResourceBundleManager rbmanager = ResourceBundleManager - .getManager(container.getProject()); - - String conatinerId = container.getFullPath().toString(); - List<String> subResourceBundles = new ArrayList<String>(); - - for (String rbId : rbmanager.getResourceBundleIdentifiers()) { - for (IResource r : rbmanager.getResourceBundles(rbId)) { - if (r.getFullPath().toString().contains(conatinerId) - && (!subResourceBundles.contains(rbId))) { - subResourceBundles.add(rbId); - } - } + return locale; + } + + /** + * @return number of ResourceBundles in the subtree + */ + public static int countRecursiveResourceBundle(IContainer container) { + return getSubResourceBundle(container).size(); + } + + private static List<String> getSubResourceBundle(IContainer container) { + ResourceBundleManager rbmanager = ResourceBundleManager + .getManager(container.getProject()); + + String conatinerId = container.getFullPath().toString(); + List<String> subResourceBundles = new ArrayList<String>(); + + for (String rbId : rbmanager.getResourceBundleIdentifiers()) { + for (IResource r : rbmanager.getResourceBundles(rbId)) { + if (r.getFullPath().toString().contains(conatinerId) + && (!subResourceBundles.contains(rbId))) { + subResourceBundles.add(rbId); } - return subResourceBundles; + } } + return subResourceBundles; + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ResourceUtils.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ResourceUtils.java index 61217032..d43d8401 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ResourceUtils.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/utils/ResourceUtils.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -21,100 +21,100 @@ public class ResourceUtils { - private final static String REGEXP_RESOURCE_KEY = "[\\p{Alnum}\\.]*"; - private final static String REGEXP_RESOURCE_NO_BUNDLENAME = "[^\\p{Alnum}\\.]*"; + private final static String REGEXP_RESOURCE_KEY = "[\\p{Alnum}\\.]*"; + private final static String REGEXP_RESOURCE_NO_BUNDLENAME = "[^\\p{Alnum}\\.]*"; - public static boolean isValidResourceKey(String key) { - boolean isValid = false; + public static boolean isValidResourceKey(String key) { + boolean isValid = false; - if (key != null && key.trim().length() > 0) { - isValid = key.matches(REGEXP_RESOURCE_KEY); - } - - return isValid; - } - - public static String deriveNonExistingRBName(String nameProposal, - ResourceBundleManager manager) { - // Adapt the proposal to the requirements for Resource-Bundle names - nameProposal = nameProposal.replaceAll(REGEXP_RESOURCE_NO_BUNDLENAME, - ""); - - int i = 0; - do { - if (manager.getResourceBundleIdentifiers().contains(nameProposal) - || nameProposal.length() == 0) { - nameProposal = nameProposal + (++i); - } else { - break; - } - } while (true); - - return nameProposal; + if (key != null && key.trim().length() > 0) { + isValid = key.matches(REGEXP_RESOURCE_KEY); } - public static boolean isJavaCompUnit(IResource res) { - boolean result = false; - - if (res.getType() == IResource.FILE && !res.isDerived() - && res.getFileExtension().equalsIgnoreCase("java")) { - result = true; - } - - return result; + return isValid; + } + + public static String deriveNonExistingRBName(String nameProposal, + ResourceBundleManager manager) { + // Adapt the proposal to the requirements for Resource-Bundle names + nameProposal = nameProposal.replaceAll(REGEXP_RESOURCE_NO_BUNDLENAME, + ""); + + int i = 0; + do { + if (manager.getResourceBundleIdentifiers().contains(nameProposal) + || nameProposal.length() == 0) { + nameProposal = nameProposal + (++i); + } else { + break; + } + } while (true); + + return nameProposal; + } + + public static boolean isJavaCompUnit(IResource res) { + boolean result = false; + + if (res.getType() == IResource.FILE && !res.isDerived() + && res.getFileExtension().equalsIgnoreCase("java")) { + result = true; } - public static boolean isJSPResource(IResource res) { - boolean result = false; + return result; + } - if (res.getType() == IResource.FILE - && !res.isDerived() - && (res.getFileExtension().equalsIgnoreCase("jsp") || res - .getFileExtension().equalsIgnoreCase("xhtml"))) { - result = true; - } + public static boolean isJSPResource(IResource res) { + boolean result = false; - return result; + if (res.getType() == IResource.FILE + && !res.isDerived() + && (res.getFileExtension().equalsIgnoreCase("jsp") || res + .getFileExtension().equalsIgnoreCase("xhtml"))) { + result = true; } - /** - * - * @param baseFolder - * @param targetProjects - * Projects with a same structure - * @return List of - */ - public static List<IContainer> getCorrespondingFolders( - IContainer baseFolder, List<IProject> targetProjects) { - List<IContainer> correspondingFolder = new ArrayList<IContainer>(); - - for (IProject p : targetProjects) { - IContainer c = getCorrespondingFolders(baseFolder, p); - if (c.exists()) { - correspondingFolder.add(c); - } - } - - return correspondingFolder; + return result; + } + + /** + * + * @param baseFolder + * @param targetProjects + * Projects with a same structure + * @return List of + */ + public static List<IContainer> getCorrespondingFolders( + IContainer baseFolder, List<IProject> targetProjects) { + List<IContainer> correspondingFolder = new ArrayList<IContainer>(); + + for (IProject p : targetProjects) { + IContainer c = getCorrespondingFolders(baseFolder, p); + if (c.exists()) { + correspondingFolder.add(c); + } } - /** - * - * @param baseFolder - * @param targetProject - * @return a Container with the corresponding path as the baseFolder. The - * Container doesn't must exist. - */ - public static IContainer getCorrespondingFolders(IContainer baseFolder, - IProject targetProject) { - IPath relativ_folder = baseFolder.getFullPath().makeRelativeTo( - baseFolder.getProject().getFullPath()); - - if (!relativ_folder.isEmpty()) { - return targetProject.getFolder(relativ_folder); - } else { - return targetProject; - } + return correspondingFolder; + } + + /** + * + * @param baseFolder + * @param targetProject + * @return a Container with the corresponding path as the baseFolder. The + * Container doesn't must exist. + */ + public static IContainer getCorrespondingFolders(IContainer baseFolder, + IProject targetProject) { + IPath relativ_folder = baseFolder.getFullPath().makeRelativeTo( + baseFolder.getProject().getFullPath()); + + if (!relativ_folder.isEmpty()) { + return targetProject.getFolder(relativ_folder); + } else { + return targetProject; } + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesView.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesView.java index 24c66b0d..603d08b4 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesView.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesView.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -54,506 +54,506 @@ import org.eclipse.ui.progress.UIJob; public class MessagesView extends ViewPart implements - IResourceBundleChangedListener { + IResourceBundleChangedListener { + + /** + * The ID of the view as specified by the extension. + */ + public static final String ID = "org.eclipse.babel.tapiji.tools.core.views.MessagesView"; + + // View State + private MessagesViewState viewState; + + // Search-Bar + private Text filter; + + // Property-Key widget + private PropertyKeySelectionTree treeViewer; + private Scale fuzzyScaler; + private Label lblScale; + + /*** ACTIONS ***/ + private List<Action> visibleLocaleActions; + private Action selectResourceBundle; + private Action enableFuzzyMatching; + private Action editable; + + // Parent component + Composite parent; + + // context-dependent menu actions + ResourceBundleEntry contextDependentMenu; + + /** + * The constructor. + */ + public MessagesView() { + } + + /** + * This is a callback that will allow us to create the viewer and initialize + * it. + */ + public void createPartControl(Composite parent) { + this.parent = parent; + + initLayout(parent); + initSearchBar(parent); + initMessagesTree(parent); + makeActions(); + hookContextMenu(); + contributeToActionBars(); + initListener(parent); + } + + protected void initListener(Composite parent) { + filter.addModifyListener(new ModifyListener() { + + @Override + public void modifyText(ModifyEvent e) { + treeViewer.setSearchString(filter.getText()); + } + }); + } + + protected void initLayout(Composite parent) { + GridLayout mainLayout = new GridLayout(); + mainLayout.numColumns = 1; + parent.setLayout(mainLayout); + + } + + protected void initSearchBar(Composite parent) { + // Construct a new parent container + Composite parentComp = new Composite(parent, SWT.BORDER); + parentComp.setLayout(new GridLayout(4, false)); + parentComp + .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + + Label lblSearchText = new Label(parentComp, SWT.NONE); + lblSearchText.setText("Search expression:"); + + // define the grid data for the layout + GridData gridData = new GridData(); + gridData.horizontalAlignment = SWT.FILL; + gridData.grabExcessHorizontalSpace = false; + gridData.horizontalSpan = 1; + lblSearchText.setLayoutData(gridData); + + filter = new Text(parentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); + if (viewState.getSearchString() != null) { + if (viewState.getSearchString().length() > 1 + && viewState.getSearchString().startsWith("*") + && viewState.getSearchString().endsWith("*")) + filter.setText(viewState.getSearchString().substring(1) + .substring(0, viewState.getSearchString().length() - 2)); + else + filter.setText(viewState.getSearchString()); - /** - * The ID of the view as specified by the extension. - */ - public static final String ID = "org.eclipse.babel.tapiji.tools.core.views.MessagesView"; - - // View State - private MessagesViewState viewState; - - // Search-Bar - private Text filter; - - // Property-Key widget - private PropertyKeySelectionTree treeViewer; - private Scale fuzzyScaler; - private Label lblScale; - - /*** ACTIONS ***/ - private List<Action> visibleLocaleActions; - private Action selectResourceBundle; - private Action enableFuzzyMatching; - private Action editable; - - // Parent component - Composite parent; - - // context-dependent menu actions - ResourceBundleEntry contextDependentMenu; - - /** - * The constructor. - */ - public MessagesView() { } - - /** - * This is a callback that will allow us to create the viewer and initialize - * it. - */ - public void createPartControl(Composite parent) { - this.parent = parent; - - initLayout(parent); - initSearchBar(parent); - initMessagesTree(parent); - makeActions(); - hookContextMenu(); - contributeToActionBars(); - initListener(parent); + GridData gridDatas = new GridData(); + gridDatas.horizontalAlignment = SWT.FILL; + gridDatas.grabExcessHorizontalSpace = true; + gridDatas.horizontalSpan = 3; + filter.setLayoutData(gridDatas); + + lblScale = new Label(parentComp, SWT.None); + lblScale.setText("\nPrecision:"); + GridData gdScaler = new GridData(); + gdScaler.verticalAlignment = SWT.CENTER; + gdScaler.grabExcessVerticalSpace = true; + gdScaler.horizontalSpan = 1; + // gdScaler.widthHint = 150; + lblScale.setLayoutData(gdScaler); + + // Add a scale for specification of fuzzy Matching precision + fuzzyScaler = new Scale(parentComp, SWT.None); + fuzzyScaler.setMaximum(100); + fuzzyScaler.setMinimum(0); + fuzzyScaler.setIncrement(1); + fuzzyScaler.setPageIncrement(5); + fuzzyScaler + .setSelection(Math.round((treeViewer != null ? treeViewer + .getMatchingPrecision() : viewState + .getMatchingPrecision()) * 100.f)); + fuzzyScaler.addListener(SWT.Selection, new Listener() { + public void handleEvent(Event event) { + float val = 1f - (Float.parseFloat((fuzzyScaler.getMaximum() + - fuzzyScaler.getSelection() + fuzzyScaler.getMinimum()) + + "") / 100.f); + treeViewer.setMatchingPrecision(val); + } + }); + fuzzyScaler.setSize(100, 10); + + GridData gdScalers = new GridData(); + gdScalers.verticalAlignment = SWT.BEGINNING; + gdScalers.horizontalAlignment = SWT.FILL; + gdScalers.horizontalSpan = 3; + fuzzyScaler.setLayoutData(gdScalers); + refreshSearchbarState(); + } + + protected void refreshSearchbarState() { + lblScale.setVisible(treeViewer != null ? treeViewer + .isFuzzyMatchingEnabled() : viewState.isFuzzyMatchingEnabled()); + fuzzyScaler.setVisible(treeViewer != null ? treeViewer + .isFuzzyMatchingEnabled() : viewState.isFuzzyMatchingEnabled()); + if (treeViewer != null ? treeViewer.isFuzzyMatchingEnabled() + : viewState.isFuzzyMatchingEnabled()) { + ((GridData) lblScale.getLayoutData()).heightHint = 40; + ((GridData) fuzzyScaler.getLayoutData()).heightHint = 40; + } else { + ((GridData) lblScale.getLayoutData()).heightHint = 0; + ((GridData) fuzzyScaler.getLayoutData()).heightHint = 0; } - protected void initListener(Composite parent) { - filter.addModifyListener(new ModifyListener() { - - @Override - public void modifyText(ModifyEvent e) { - treeViewer.setSearchString(filter.getText()); - } - }); + lblScale.getParent().layout(); + lblScale.getParent().getParent().layout(); + } + + protected void initMessagesTree(Composite parent) { + if (viewState.getSelectedProjectName() != null + && viewState.getSelectedProjectName().trim().length() > 0) { + try { + ResourceBundleManager.getManager( + viewState.getSelectedProjectName()) + .registerResourceBundleChangeListener( + viewState.getSelectedBundleId(), this); + + } catch (Exception e) { + } } - - protected void initLayout(Composite parent) { - GridLayout mainLayout = new GridLayout(); - mainLayout.numColumns = 1; - parent.setLayout(mainLayout); - + treeViewer = new PropertyKeySelectionTree(getViewSite(), getSite(), + parent, SWT.NONE, viewState.getSelectedProjectName(), + viewState.getSelectedBundleId(), viewState.getVisibleLocales()); + if (viewState.getSelectedProjectName() != null + && viewState.getSelectedProjectName().trim().length() > 0) { + if (viewState.getVisibleLocales() == null) + viewState.setVisibleLocales(treeViewer.getVisibleLocales()); + + if (viewState.getSortings() != null) + treeViewer.setSortInfo(viewState.getSortings()); + + treeViewer.enableFuzzyMatching(viewState.isFuzzyMatchingEnabled()); + treeViewer.setMatchingPrecision(viewState.getMatchingPrecision()); + treeViewer.setEditable(viewState.isEditable()); + + if (viewState.getSearchString() != null) + treeViewer.setSearchString(viewState.getSearchString()); } - - protected void initSearchBar(Composite parent) { - // Construct a new parent container - Composite parentComp = new Composite(parent, SWT.BORDER); - parentComp.setLayout(new GridLayout(4, false)); - parentComp - .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - - Label lblSearchText = new Label(parentComp, SWT.NONE); - lblSearchText.setText("Search expression:"); - - // define the grid data for the layout - GridData gridData = new GridData(); - gridData.horizontalAlignment = SWT.FILL; - gridData.grabExcessHorizontalSpace = false; - gridData.horizontalSpan = 1; - lblSearchText.setLayoutData(gridData); - - filter = new Text(parentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); - if (viewState.getSearchString() != null) { - if (viewState.getSearchString().length() > 1 - && viewState.getSearchString().startsWith("*") - && viewState.getSearchString().endsWith("*")) - filter.setText(viewState.getSearchString().substring(1) - .substring(0, viewState.getSearchString().length() - 2)); - else - filter.setText(viewState.getSearchString()); - - } - GridData gridDatas = new GridData(); - gridDatas.horizontalAlignment = SWT.FILL; - gridDatas.grabExcessHorizontalSpace = true; - gridDatas.horizontalSpan = 3; - filter.setLayoutData(gridDatas); - - lblScale = new Label(parentComp, SWT.None); - lblScale.setText("\nPrecision:"); - GridData gdScaler = new GridData(); - gdScaler.verticalAlignment = SWT.CENTER; - gdScaler.grabExcessVerticalSpace = true; - gdScaler.horizontalSpan = 1; - // gdScaler.widthHint = 150; - lblScale.setLayoutData(gdScaler); - - // Add a scale for specification of fuzzy Matching precision - fuzzyScaler = new Scale(parentComp, SWT.None); - fuzzyScaler.setMaximum(100); - fuzzyScaler.setMinimum(0); - fuzzyScaler.setIncrement(1); - fuzzyScaler.setPageIncrement(5); - fuzzyScaler - .setSelection(Math.round((treeViewer != null ? treeViewer - .getMatchingPrecision() : viewState - .getMatchingPrecision()) * 100.f)); - fuzzyScaler.addListener(SWT.Selection, new Listener() { - public void handleEvent(Event event) { - float val = 1f - (Float.parseFloat((fuzzyScaler.getMaximum() - - fuzzyScaler.getSelection() + fuzzyScaler.getMinimum()) - + "") / 100.f); - treeViewer.setMatchingPrecision(val); - } - }); - fuzzyScaler.setSize(100, 10); - - GridData gdScalers = new GridData(); - gdScalers.verticalAlignment = SWT.BEGINNING; - gdScalers.horizontalAlignment = SWT.FILL; - gdScalers.horizontalSpan = 3; - fuzzyScaler.setLayoutData(gdScalers); - refreshSearchbarState(); + // define the grid data for the layout + GridData gridData = new GridData(); + gridData.horizontalAlignment = SWT.FILL; + gridData.verticalAlignment = SWT.FILL; + gridData.grabExcessHorizontalSpace = true; + gridData.grabExcessVerticalSpace = true; + treeViewer.setLayoutData(gridData); + } + + /** + * Passing the focus request to the viewer's control. + */ + public void setFocus() { + treeViewer.setFocus(); + } + + protected void redrawTreeViewer() { + parent.setRedraw(false); + treeViewer.dispose(); + try { + initMessagesTree(parent); + makeActions(); + contributeToActionBars(); + hookContextMenu(); + } catch (Exception e) { + Logger.logError(e); } - - protected void refreshSearchbarState() { - lblScale.setVisible(treeViewer != null ? treeViewer - .isFuzzyMatchingEnabled() : viewState.isFuzzyMatchingEnabled()); - fuzzyScaler.setVisible(treeViewer != null ? treeViewer - .isFuzzyMatchingEnabled() : viewState.isFuzzyMatchingEnabled()); - if (treeViewer != null ? treeViewer.isFuzzyMatchingEnabled() - : viewState.isFuzzyMatchingEnabled()) { - ((GridData) lblScale.getLayoutData()).heightHint = 40; - ((GridData) fuzzyScaler.getLayoutData()).heightHint = 40; - } else { - ((GridData) lblScale.getLayoutData()).heightHint = 0; - ((GridData) fuzzyScaler.getLayoutData()).heightHint = 0; - } - - lblScale.getParent().layout(); - lblScale.getParent().getParent().layout(); + parent.setRedraw(true); + parent.layout(true); + treeViewer.layout(true); + refreshSearchbarState(); + } + + /*** ACTIONS ***/ + private void makeVisibleLocalesActions() { + if (viewState.getSelectedProjectName() == null) { + return; } - protected void initMessagesTree(Composite parent) { - if (viewState.getSelectedProjectName() != null - && viewState.getSelectedProjectName().trim().length() > 0) { - try { - ResourceBundleManager.getManager( - viewState.getSelectedProjectName()) - .registerResourceBundleChangeListener( - viewState.getSelectedBundleId(), this); - - } catch (Exception e) { + visibleLocaleActions = new ArrayList<Action>(); + Set<Locale> locales = ResourceBundleManager.getManager( + viewState.getSelectedProjectName()).getProvidedLocales( + viewState.getSelectedBundleId()); + List<Locale> visibleLocales = treeViewer.getVisibleLocales(); + for (final Locale locale : locales) { + Action langAction = new Action() { + + @Override + public void run() { + super.run(); + List<Locale> visibleL = treeViewer.getVisibleLocales(); + if (this.isChecked()) { + if (!visibleL.contains(locale)) { + visibleL.add(locale); } + } else { + visibleL.remove(locale); + } + viewState.setVisibleLocales(visibleL); + redrawTreeViewer(); } - treeViewer = new PropertyKeySelectionTree(getViewSite(), getSite(), - parent, SWT.NONE, viewState.getSelectedProjectName(), - viewState.getSelectedBundleId(), viewState.getVisibleLocales()); - if (viewState.getSelectedProjectName() != null - && viewState.getSelectedProjectName().trim().length() > 0) { - if (viewState.getVisibleLocales() == null) - viewState.setVisibleLocales(treeViewer.getVisibleLocales()); - - if (viewState.getSortings() != null) - treeViewer.setSortInfo(viewState.getSortings()); - - treeViewer.enableFuzzyMatching(viewState.isFuzzyMatchingEnabled()); - treeViewer.setMatchingPrecision(viewState.getMatchingPrecision()); - treeViewer.setEditable(viewState.isEditable()); - - if (viewState.getSearchString() != null) - treeViewer.setSearchString(viewState.getSearchString()); - } - // define the grid data for the layout - GridData gridData = new GridData(); - gridData.horizontalAlignment = SWT.FILL; - gridData.verticalAlignment = SWT.FILL; - gridData.grabExcessHorizontalSpace = true; - gridData.grabExcessVerticalSpace = true; - treeViewer.setLayoutData(gridData); - } - /** - * Passing the focus request to the viewer's control. - */ - public void setFocus() { - treeViewer.setFocus(); + }; + if (locale != null && locale.getDisplayName().trim().length() > 0) { + langAction.setText(locale.getDisplayName(Locale.US)); + } else { + langAction.setText("Default"); + } + langAction.setChecked(visibleLocales.contains(locale)); + visibleLocaleActions.add(langAction); } - - protected void redrawTreeViewer() { - parent.setRedraw(false); - treeViewer.dispose(); - try { - initMessagesTree(parent); - makeActions(); - contributeToActionBars(); - hookContextMenu(); - } catch (Exception e) { - Logger.logError(e); + } + + private void makeActions() { + makeVisibleLocalesActions(); + + selectResourceBundle = new Action() { + + @Override + public void run() { + super.run(); + ResourceBundleSelectionDialog sd = new ResourceBundleSelectionDialog( + getViewSite().getShell(), null); + if (sd.open() == InputDialog.OK) { + String resourceBundle = sd.getSelectedBundleId(); + + if (resourceBundle != null) { + int iSep = resourceBundle.indexOf("/"); + viewState.setSelectedProjectName(resourceBundle + .substring(0, iSep)); + viewState.setSelectedBundleId(resourceBundle + .substring(iSep + 1)); + viewState.setVisibleLocales(null); + redrawTreeViewer(); + setTitleToolTip(resourceBundle); + } } - parent.setRedraw(true); - parent.layout(true); - treeViewer.layout(true); + } + }; + + selectResourceBundle.setText("Resource-Bundle ..."); + selectResourceBundle + .setDescription("Allows you to select the Resource-Bundle which is used as message-source."); + selectResourceBundle.setImageDescriptor(Activator + .getImageDescriptor(ImageUtils.IMAGE_RESOURCE_BUNDLE)); + + contextDependentMenu = new ResourceBundleEntry(treeViewer, treeViewer + .getViewer().getSelection()); + + enableFuzzyMatching = new Action() { + public void run() { + super.run(); + treeViewer.enableFuzzyMatching(!treeViewer + .isFuzzyMatchingEnabled()); + viewState.setFuzzyMatchingEnabled(treeViewer + .isFuzzyMatchingEnabled()); refreshSearchbarState(); + } + }; + enableFuzzyMatching.setText("Fuzzy-Matching"); + enableFuzzyMatching + .setDescription("Enables Fuzzy matching for searching Resource-Bundle entries."); + enableFuzzyMatching.setChecked(viewState.isFuzzyMatchingEnabled()); + enableFuzzyMatching + .setToolTipText(enableFuzzyMatching.getDescription()); + + editable = new Action() { + public void run() { + super.run(); + treeViewer.setEditable(!treeViewer.isEditable()); + viewState.setEditable(treeViewer.isEditable()); + } + }; + editable.setText("Editable"); + editable.setDescription("Allows you to edit Resource-Bundle entries."); + editable.setChecked(viewState.isEditable()); + editable.setToolTipText(editable.getDescription()); + } + + private void contributeToActionBars() { + IActionBars bars = getViewSite().getActionBars(); + fillLocalPullDown(bars.getMenuManager()); + fillLocalToolBar(bars.getToolBarManager()); + } + + private void fillLocalPullDown(IMenuManager manager) { + manager.removeAll(); + manager.add(selectResourceBundle); + manager.add(enableFuzzyMatching); + manager.add(editable); + manager.add(new Separator()); + + manager.add(contextDependentMenu); + manager.add(new Separator()); + + if (visibleLocaleActions == null) + return; + + for (Action loc : visibleLocaleActions) { + manager.add(loc); } - - /*** ACTIONS ***/ - private void makeVisibleLocalesActions() { - if (viewState.getSelectedProjectName() == null) { - return; - } - - visibleLocaleActions = new ArrayList<Action>(); - Set<Locale> locales = ResourceBundleManager.getManager( - viewState.getSelectedProjectName()).getProvidedLocales( - viewState.getSelectedBundleId()); - List<Locale> visibleLocales = treeViewer.getVisibleLocales(); - for (final Locale locale : locales) { - Action langAction = new Action() { - - @Override - public void run() { - super.run(); - List<Locale> visibleL = treeViewer.getVisibleLocales(); - if (this.isChecked()) { - if (!visibleL.contains(locale)) { - visibleL.add(locale); - } - } else { - visibleL.remove(locale); - } - viewState.setVisibleLocales(visibleL); - redrawTreeViewer(); - } - - }; - if (locale != null && locale.getDisplayName().trim().length() > 0) { - langAction.setText(locale.getDisplayName(Locale.US)); - } else { - langAction.setText("Default"); + } + + /*** CONTEXT MENU ***/ + private void hookContextMenu() { + new UIJob("set PopupMenu") { + @Override + public IStatus runInUIThread(IProgressMonitor monitor) { + if (!treeViewer.isDisposed()) { + MenuManager menuMgr = new MenuManager("#PopupMenu"); + menuMgr.setRemoveAllWhenShown(true); + menuMgr.addMenuListener(new IMenuListener() { + public void menuAboutToShow(IMenuManager manager) { + fillContextMenu(manager); } - langAction.setChecked(visibleLocales.contains(locale)); - visibleLocaleActions.add(langAction); + }); + Menu menu = menuMgr.createContextMenu(treeViewer + .getViewer().getControl()); + treeViewer.getViewer().getControl().setMenu(menu); + getViewSite().registerContextMenu(menuMgr, + treeViewer.getViewer()); } + return Status.OK_STATUS; + } + }.schedule(); + } + + private void fillContextMenu(IMenuManager manager) { + manager.removeAll(); + manager.add(selectResourceBundle); + manager.add(enableFuzzyMatching); + manager.add(editable); + manager.add(new Separator()); + + manager.add(new ResourceBundleEntry(treeViewer, treeViewer.getViewer() + .getSelection())); + manager.add(new Separator()); + + for (Action loc : visibleLocaleActions) { + manager.add(loc); } - - private void makeActions() { - makeVisibleLocalesActions(); - - selectResourceBundle = new Action() { - - @Override - public void run() { - super.run(); - ResourceBundleSelectionDialog sd = new ResourceBundleSelectionDialog( - getViewSite().getShell(), null); - if (sd.open() == InputDialog.OK) { - String resourceBundle = sd.getSelectedBundleId(); - - if (resourceBundle != null) { - int iSep = resourceBundle.indexOf("/"); - viewState.setSelectedProjectName(resourceBundle - .substring(0, iSep)); - viewState.setSelectedBundleId(resourceBundle - .substring(iSep + 1)); - viewState.setVisibleLocales(null); - redrawTreeViewer(); - setTitleToolTip(resourceBundle); - } - } - } - }; - - selectResourceBundle.setText("Resource-Bundle ..."); - selectResourceBundle - .setDescription("Allows you to select the Resource-Bundle which is used as message-source."); - selectResourceBundle.setImageDescriptor(Activator - .getImageDescriptor(ImageUtils.IMAGE_RESOURCE_BUNDLE)); - - contextDependentMenu = new ResourceBundleEntry(treeViewer, treeViewer - .getViewer().getSelection()); - - enableFuzzyMatching = new Action() { - public void run() { - super.run(); - treeViewer.enableFuzzyMatching(!treeViewer - .isFuzzyMatchingEnabled()); - viewState.setFuzzyMatchingEnabled(treeViewer - .isFuzzyMatchingEnabled()); - refreshSearchbarState(); - } - }; - enableFuzzyMatching.setText("Fuzzy-Matching"); - enableFuzzyMatching - .setDescription("Enables Fuzzy matching for searching Resource-Bundle entries."); - enableFuzzyMatching.setChecked(viewState.isFuzzyMatchingEnabled()); - enableFuzzyMatching - .setToolTipText(enableFuzzyMatching.getDescription()); - - editable = new Action() { - public void run() { - super.run(); - treeViewer.setEditable(!treeViewer.isEditable()); - viewState.setEditable(treeViewer.isEditable()); - } - }; - editable.setText("Editable"); - editable.setDescription("Allows you to edit Resource-Bundle entries."); - editable.setChecked(viewState.isEditable()); - editable.setToolTipText(editable.getDescription()); - } - - private void contributeToActionBars() { - IActionBars bars = getViewSite().getActionBars(); - fillLocalPullDown(bars.getMenuManager()); - fillLocalToolBar(bars.getToolBarManager()); - } - - private void fillLocalPullDown(IMenuManager manager) { - manager.removeAll(); - manager.add(selectResourceBundle); - manager.add(enableFuzzyMatching); - manager.add(editable); - manager.add(new Separator()); - - manager.add(contextDependentMenu); - manager.add(new Separator()); - - if (visibleLocaleActions == null) - return; - - for (Action loc : visibleLocaleActions) { - manager.add(loc); - } - } - - /*** CONTEXT MENU ***/ - private void hookContextMenu() { - new UIJob("set PopupMenu") { - @Override - public IStatus runInUIThread(IProgressMonitor monitor) { - if (!treeViewer.isDisposed()) { - MenuManager menuMgr = new MenuManager("#PopupMenu"); - menuMgr.setRemoveAllWhenShown(true); - menuMgr.addMenuListener(new IMenuListener() { - public void menuAboutToShow(IMenuManager manager) { - fillContextMenu(manager); - } - }); - Menu menu = menuMgr.createContextMenu(treeViewer.getViewer() - .getControl()); - treeViewer.getViewer().getControl().setMenu(menu); - getViewSite().registerContextMenu(menuMgr, - treeViewer.getViewer()); - } - return Status.OK_STATUS; - } - }.schedule(); - } - - private void fillContextMenu(IMenuManager manager) { - manager.removeAll(); - manager.add(selectResourceBundle); - manager.add(enableFuzzyMatching); - manager.add(editable); - manager.add(new Separator()); - - manager.add(new ResourceBundleEntry(treeViewer, treeViewer.getViewer() - .getSelection())); - manager.add(new Separator()); - - for (Action loc : visibleLocaleActions) { - manager.add(loc); - } - // Other plug-ins can contribute there actions here - // manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); - } - - private void fillLocalToolBar(IToolBarManager manager) { - manager.add(selectResourceBundle); + // Other plug-ins can contribute there actions here + // manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); + } + + private void fillLocalToolBar(IToolBarManager manager) { + manager.add(selectResourceBundle); + } + + @Override + public void saveState(IMemento memento) { + super.saveState(memento); + try { + viewState.setEditable(treeViewer.isEditable()); + viewState.setSortings(treeViewer.getSortInfo()); + viewState.setSearchString(treeViewer.getSearchString()); + viewState.setFuzzyMatchingEnabled(treeViewer + .isFuzzyMatchingEnabled()); + viewState.setMatchingPrecision(treeViewer.getMatchingPrecision()); + viewState.saveState(memento); + } catch (Exception e) { } - - @Override - public void saveState(IMemento memento) { - super.saveState(memento); - try { - viewState.setEditable(treeViewer.isEditable()); - viewState.setSortings(treeViewer.getSortInfo()); - viewState.setSearchString(treeViewer.getSearchString()); - viewState.setFuzzyMatchingEnabled(treeViewer - .isFuzzyMatchingEnabled()); - viewState.setMatchingPrecision(treeViewer.getMatchingPrecision()); - viewState.saveState(memento); - } catch (Exception e) { + } + + @Override + public void init(IViewSite site, IMemento memento) throws PartInitException { + super.init(site, memento); + + // init Viewstate + viewState = new MessagesViewState(null, null, false, null); + viewState.init(memento); + } + + @Override + public void resourceBundleChanged(ResourceBundleChangedEvent event) { + try { + if (!event.getBundle().equals(treeViewer.getResourceBundle())) + return; + + switch (event.getType()) { + /* + * case ResourceBundleChangedEvent.ADDED: if ( + * viewState.getSelectedProjectName().trim().length() > 0 ) { try { + * ResourceBundleManager + * .getManager(viewState.getSelectedProjectName()) + * .unregisterResourceBundleChangeListener + * (viewState.getSelectedBundleId(), this); } catch (Exception e) {} + * } + * + * new Thread(new Runnable() { + * + * public void run() { try { Thread.sleep(500); } catch (Exception + * e) { } Display.getDefault().asyncExec(new Runnable() { public + * void run() { try { redrawTreeViewer(); } catch (Exception e) { + * e.printStackTrace(); } } }); + * + * } }).start(); break; + */ + case ResourceBundleChangedEvent.ADDED: + // update visible locales within the context menu + makeVisibleLocalesActions(); + hookContextMenu(); + break; + case ResourceBundleChangedEvent.DELETED: + case ResourceBundleChangedEvent.EXCLUDED: + if (viewState.getSelectedProjectName().trim().length() > 0) { + try { + ResourceBundleManager.getManager( + viewState.getSelectedProjectName()) + .unregisterResourceBundleChangeListener( + viewState.getSelectedBundleId(), this); + + } catch (Exception e) { + } } - } - - @Override - public void init(IViewSite site, IMemento memento) throws PartInitException { - super.init(site, memento); - - // init Viewstate viewState = new MessagesViewState(null, null, false, null); - viewState.init(memento); - } - @Override - public void resourceBundleChanged(ResourceBundleChangedEvent event) { - try { - if (!event.getBundle().equals(treeViewer.getResourceBundle())) - return; - - switch (event.getType()) { - /* - * case ResourceBundleChangedEvent.ADDED: if ( - * viewState.getSelectedProjectName().trim().length() > 0 ) { try { - * ResourceBundleManager - * .getManager(viewState.getSelectedProjectName()) - * .unregisterResourceBundleChangeListener - * (viewState.getSelectedBundleId(), this); } catch (Exception e) {} - * } - * - * new Thread(new Runnable() { - * - * public void run() { try { Thread.sleep(500); } catch (Exception - * e) { } Display.getDefault().asyncExec(new Runnable() { public - * void run() { try { redrawTreeViewer(); } catch (Exception e) { - * e.printStackTrace(); } } }); - * - * } }).start(); break; - */ - case ResourceBundleChangedEvent.ADDED: - // update visible locales within the context menu - makeVisibleLocalesActions(); - hookContextMenu(); - break; - case ResourceBundleChangedEvent.DELETED: - case ResourceBundleChangedEvent.EXCLUDED: - if (viewState.getSelectedProjectName().trim().length() > 0) { - try { - ResourceBundleManager.getManager( - viewState.getSelectedProjectName()) - .unregisterResourceBundleChangeListener( - viewState.getSelectedBundleId(), this); - - } catch (Exception e) { - } - } - viewState = new MessagesViewState(null, null, false, null); - - new Thread(new Runnable() { - - public void run() { - try { - Thread.sleep(500); - } catch (Exception e) { - } - Display.getDefault().asyncExec(new Runnable() { - public void run() { - try { - redrawTreeViewer(); - } catch (Exception e) { - Logger.logError(e); - } - } - }); - - } - }).start(); + new Thread(new Runnable() { + + public void run() { + try { + Thread.sleep(500); + } catch (Exception e) { } - } catch (Exception e) { - Logger.logError(e); - } + Display.getDefault().asyncExec(new Runnable() { + public void run() { + try { + redrawTreeViewer(); + } catch (Exception e) { + Logger.logError(e); + } + } + }); + + } + }).start(); + } + } catch (Exception e) { + Logger.logError(e); } - - @Override - public void dispose() { - try { - super.dispose(); - treeViewer.dispose(); - ResourceBundleManager - .getManager(viewState.getSelectedProjectName()) - .unregisterResourceBundleChangeListener( - viewState.getSelectedBundleId(), this); - } catch (Exception e) { - } + } + + @Override + public void dispose() { + try { + super.dispose(); + treeViewer.dispose(); + ResourceBundleManager + .getManager(viewState.getSelectedProjectName()) + .unregisterResourceBundleChangeListener( + viewState.getSelectedBundleId(), this); + } catch (Exception e) { } + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesViewState.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesViewState.java index 6fafc83e..6c7a2d4f 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesViewState.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/MessagesViewState.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -18,200 +18,200 @@ public class MessagesViewState { - private static final String TAG_VISIBLE_LOCALES = "visible_locales"; - private static final String TAG_LOCALE = "locale"; - private static final String TAG_LOCALE_LANGUAGE = "language"; - private static final String TAG_LOCALE_COUNTRY = "country"; - private static final String TAG_LOCALE_VARIANT = "variant"; - private static final String TAG_FUZZY_MATCHING = "fuzzy_matching"; - private static final String TAG_MATCHING_PRECISION = "matching_precision"; - private static final String TAG_SELECTED_PROJECT = "selected_project"; - private static final String TAG_SELECTED_BUNDLE = "selected_bundle"; - private static final String TAG_ENABLED = "enabled"; - private static final String TAG_VALUE = "value"; - private static final String TAG_SEARCH_STRING = "search_string"; - private static final String TAG_EDITABLE = "editable"; - - private List<Locale> visibleLocales; - private SortInfo sortings; - private boolean fuzzyMatchingEnabled; - private float matchingPrecision = .75f; - private String selectedProjectName; - private String selectedBundleId; - private String searchString; - private boolean editable; - - public void saveState(IMemento memento) { - try { - if (memento == null) - return; - - if (visibleLocales != null) { - IMemento memVL = memento.createChild(TAG_VISIBLE_LOCALES); - for (Locale loc : visibleLocales) { - IMemento memLoc = memVL.createChild(TAG_LOCALE); - memLoc.putString(TAG_LOCALE_LANGUAGE, loc.getLanguage()); - memLoc.putString(TAG_LOCALE_COUNTRY, loc.getCountry()); - memLoc.putString(TAG_LOCALE_VARIANT, loc.getVariant()); - } - } - - if (sortings != null) { - sortings.saveState(memento); - } - - IMemento memFuzzyMatching = memento.createChild(TAG_FUZZY_MATCHING); - memFuzzyMatching.putBoolean(TAG_ENABLED, fuzzyMatchingEnabled); - - IMemento memMatchingPrec = memento - .createChild(TAG_MATCHING_PRECISION); - memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision); - - selectedProjectName = selectedProjectName != null ? selectedProjectName - : ""; - selectedBundleId = selectedBundleId != null ? selectedBundleId : ""; - - IMemento memSP = memento.createChild(TAG_SELECTED_PROJECT); - memSP.putString(TAG_VALUE, selectedProjectName); - - IMemento memSB = memento.createChild(TAG_SELECTED_BUNDLE); - memSB.putString(TAG_VALUE, selectedBundleId); - - IMemento memSStr = memento.createChild(TAG_SEARCH_STRING); - memSStr.putString(TAG_VALUE, searchString); - - IMemento memEditable = memento.createChild(TAG_EDITABLE); - memEditable.putBoolean(TAG_ENABLED, editable); - } catch (Exception e) { - + private static final String TAG_VISIBLE_LOCALES = "visible_locales"; + private static final String TAG_LOCALE = "locale"; + private static final String TAG_LOCALE_LANGUAGE = "language"; + private static final String TAG_LOCALE_COUNTRY = "country"; + private static final String TAG_LOCALE_VARIANT = "variant"; + private static final String TAG_FUZZY_MATCHING = "fuzzy_matching"; + private static final String TAG_MATCHING_PRECISION = "matching_precision"; + private static final String TAG_SELECTED_PROJECT = "selected_project"; + private static final String TAG_SELECTED_BUNDLE = "selected_bundle"; + private static final String TAG_ENABLED = "enabled"; + private static final String TAG_VALUE = "value"; + private static final String TAG_SEARCH_STRING = "search_string"; + private static final String TAG_EDITABLE = "editable"; + + private List<Locale> visibleLocales; + private SortInfo sortings; + private boolean fuzzyMatchingEnabled; + private float matchingPrecision = .75f; + private String selectedProjectName; + private String selectedBundleId; + private String searchString; + private boolean editable; + + public void saveState(IMemento memento) { + try { + if (memento == null) + return; + + if (visibleLocales != null) { + IMemento memVL = memento.createChild(TAG_VISIBLE_LOCALES); + for (Locale loc : visibleLocales) { + IMemento memLoc = memVL.createChild(TAG_LOCALE); + memLoc.putString(TAG_LOCALE_LANGUAGE, loc.getLanguage()); + memLoc.putString(TAG_LOCALE_COUNTRY, loc.getCountry()); + memLoc.putString(TAG_LOCALE_VARIANT, loc.getVariant()); } - } - - public void init(IMemento memento) { - if (memento == null) - return; - - if (memento.getChild(TAG_VISIBLE_LOCALES) != null) { - if (visibleLocales == null) - visibleLocales = new ArrayList<Locale>(); - IMemento[] mLocales = memento.getChild(TAG_VISIBLE_LOCALES) - .getChildren(TAG_LOCALE); - for (IMemento mLocale : mLocales) { - if (mLocale.getString(TAG_LOCALE_LANGUAGE) == null - && mLocale.getString(TAG_LOCALE_COUNTRY) == null - && mLocale.getString(TAG_LOCALE_VARIANT) == null) { - continue; - } - Locale newLocale = new Locale( - mLocale.getString(TAG_LOCALE_LANGUAGE), - mLocale.getString(TAG_LOCALE_COUNTRY), - mLocale.getString(TAG_LOCALE_VARIANT)); - if (!this.visibleLocales.contains(newLocale)) { - visibleLocales.add(newLocale); - } - } - } - - if (sortings == null) - sortings = new SortInfo(); - sortings.init(memento); - - IMemento mFuzzyMatching = memento.getChild(TAG_FUZZY_MATCHING); - if (mFuzzyMatching != null) - fuzzyMatchingEnabled = mFuzzyMatching.getBoolean(TAG_ENABLED); - - IMemento mMP = memento.getChild(TAG_MATCHING_PRECISION); - if (mMP != null) - matchingPrecision = mMP.getFloat(TAG_VALUE); - - IMemento mSelProj = memento.getChild(TAG_SELECTED_PROJECT); - if (mSelProj != null) - selectedProjectName = mSelProj.getString(TAG_VALUE); - - IMemento mSelBundle = memento.getChild(TAG_SELECTED_BUNDLE); - if (mSelBundle != null) - selectedBundleId = mSelBundle.getString(TAG_VALUE); - - IMemento mSStr = memento.getChild(TAG_SEARCH_STRING); - if (mSStr != null) - searchString = mSStr.getString(TAG_VALUE); - - IMemento mEditable = memento.getChild(TAG_EDITABLE); - if (mEditable != null) - editable = mEditable.getBoolean(TAG_ENABLED); - } - - public MessagesViewState(List<Locale> visibleLocales, SortInfo sortings, - boolean fuzzyMatchingEnabled, String selectedBundleId) { - super(); - this.visibleLocales = visibleLocales; - this.sortings = sortings; - this.fuzzyMatchingEnabled = fuzzyMatchingEnabled; - this.selectedBundleId = selectedBundleId; - } - - public List<Locale> getVisibleLocales() { - return visibleLocales; - } - - public void setVisibleLocales(List<Locale> visibleLocales) { - this.visibleLocales = visibleLocales; - } + } - public SortInfo getSortings() { - return sortings; - } + if (sortings != null) { + sortings.saveState(memento); + } - public void setSortings(SortInfo sortings) { - this.sortings = sortings; - } + IMemento memFuzzyMatching = memento.createChild(TAG_FUZZY_MATCHING); + memFuzzyMatching.putBoolean(TAG_ENABLED, fuzzyMatchingEnabled); - public boolean isFuzzyMatchingEnabled() { - return fuzzyMatchingEnabled; - } + IMemento memMatchingPrec = memento + .createChild(TAG_MATCHING_PRECISION); + memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision); - public void setFuzzyMatchingEnabled(boolean fuzzyMatchingEnabled) { - this.fuzzyMatchingEnabled = fuzzyMatchingEnabled; - } + selectedProjectName = selectedProjectName != null ? selectedProjectName + : ""; + selectedBundleId = selectedBundleId != null ? selectedBundleId : ""; - public void setSelectedBundleId(String selectedBundleId) { - this.selectedBundleId = selectedBundleId; - } + IMemento memSP = memento.createChild(TAG_SELECTED_PROJECT); + memSP.putString(TAG_VALUE, selectedProjectName); - public void setSelectedProjectName(String selectedProjectName) { - this.selectedProjectName = selectedProjectName; - } + IMemento memSB = memento.createChild(TAG_SELECTED_BUNDLE); + memSB.putString(TAG_VALUE, selectedBundleId); - public void setSearchString(String searchString) { - this.searchString = searchString; - } + IMemento memSStr = memento.createChild(TAG_SEARCH_STRING); + memSStr.putString(TAG_VALUE, searchString); - public String getSelectedBundleId() { - return selectedBundleId; - } + IMemento memEditable = memento.createChild(TAG_EDITABLE); + memEditable.putBoolean(TAG_ENABLED, editable); + } catch (Exception e) { - public String getSelectedProjectName() { - return selectedProjectName; } + } - public String getSearchString() { - return searchString; - } - - public boolean isEditable() { - return editable; - } - - public void setEditable(boolean editable) { - this.editable = editable; - } + public void init(IMemento memento) { + if (memento == null) + return; - public float getMatchingPrecision() { - return matchingPrecision; + if (memento.getChild(TAG_VISIBLE_LOCALES) != null) { + if (visibleLocales == null) + visibleLocales = new ArrayList<Locale>(); + IMemento[] mLocales = memento.getChild(TAG_VISIBLE_LOCALES) + .getChildren(TAG_LOCALE); + for (IMemento mLocale : mLocales) { + if (mLocale.getString(TAG_LOCALE_LANGUAGE) == null + && mLocale.getString(TAG_LOCALE_COUNTRY) == null + && mLocale.getString(TAG_LOCALE_VARIANT) == null) { + continue; + } + Locale newLocale = new Locale( + mLocale.getString(TAG_LOCALE_LANGUAGE), + mLocale.getString(TAG_LOCALE_COUNTRY), + mLocale.getString(TAG_LOCALE_VARIANT)); + if (!this.visibleLocales.contains(newLocale)) { + visibleLocales.add(newLocale); + } + } } - public void setMatchingPrecision(float value) { - this.matchingPrecision = value; - } + if (sortings == null) + sortings = new SortInfo(); + sortings.init(memento); + + IMemento mFuzzyMatching = memento.getChild(TAG_FUZZY_MATCHING); + if (mFuzzyMatching != null) + fuzzyMatchingEnabled = mFuzzyMatching.getBoolean(TAG_ENABLED); + + IMemento mMP = memento.getChild(TAG_MATCHING_PRECISION); + if (mMP != null) + matchingPrecision = mMP.getFloat(TAG_VALUE); + + IMemento mSelProj = memento.getChild(TAG_SELECTED_PROJECT); + if (mSelProj != null) + selectedProjectName = mSelProj.getString(TAG_VALUE); + + IMemento mSelBundle = memento.getChild(TAG_SELECTED_BUNDLE); + if (mSelBundle != null) + selectedBundleId = mSelBundle.getString(TAG_VALUE); + + IMemento mSStr = memento.getChild(TAG_SEARCH_STRING); + if (mSStr != null) + searchString = mSStr.getString(TAG_VALUE); + + IMemento mEditable = memento.getChild(TAG_EDITABLE); + if (mEditable != null) + editable = mEditable.getBoolean(TAG_ENABLED); + } + + public MessagesViewState(List<Locale> visibleLocales, SortInfo sortings, + boolean fuzzyMatchingEnabled, String selectedBundleId) { + super(); + this.visibleLocales = visibleLocales; + this.sortings = sortings; + this.fuzzyMatchingEnabled = fuzzyMatchingEnabled; + this.selectedBundleId = selectedBundleId; + } + + public List<Locale> getVisibleLocales() { + return visibleLocales; + } + + public void setVisibleLocales(List<Locale> visibleLocales) { + this.visibleLocales = visibleLocales; + } + + public SortInfo getSortings() { + return sortings; + } + + public void setSortings(SortInfo sortings) { + this.sortings = sortings; + } + + public boolean isFuzzyMatchingEnabled() { + return fuzzyMatchingEnabled; + } + + public void setFuzzyMatchingEnabled(boolean fuzzyMatchingEnabled) { + this.fuzzyMatchingEnabled = fuzzyMatchingEnabled; + } + + public void setSelectedBundleId(String selectedBundleId) { + this.selectedBundleId = selectedBundleId; + } + + public void setSelectedProjectName(String selectedProjectName) { + this.selectedProjectName = selectedProjectName; + } + + public void setSearchString(String searchString) { + this.searchString = searchString; + } + + public String getSelectedBundleId() { + return selectedBundleId; + } + + public String getSelectedProjectName() { + return selectedProjectName; + } + + public String getSearchString() { + return searchString; + } + + public boolean isEditable() { + return editable; + } + + public void setEditable(boolean editable) { + this.editable = editable; + } + + public float getMatchingPrecision() { + return matchingPrecision; + } + + public void setMatchingPrecision(float value) { + this.matchingPrecision = value; + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java index 95c37640..9bc7dec9 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -24,101 +24,101 @@ import org.eclipse.ui.PlatformUI; public class ResourceBundleEntry extends ContributionItem implements - ISelectionChangedListener { + ISelectionChangedListener { + + private PropertyKeySelectionTree parentView; + private ISelection selection; + private boolean legalSelection = false; + + // Menu-Items + private MenuItem addItem; + private MenuItem editItem; + private MenuItem removeItem; + + public ResourceBundleEntry() { + } + + public ResourceBundleEntry(PropertyKeySelectionTree view, + ISelection selection) { + this.selection = selection; + this.legalSelection = !selection.isEmpty(); + this.parentView = view; + parentView.addSelectionChangedListener(this); + } + + @Override + public void fill(Menu menu, int index) { + + // MenuItem for adding a new entry + addItem = new MenuItem(menu, SWT.NONE, index); + addItem.setText("Add ..."); + addItem.setImage(PlatformUI.getWorkbench().getSharedImages() + .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage()); + addItem.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { + parentView.addNewItem(selection); + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + + } + }); + + if ((parentView == null && legalSelection) || parentView != null) { + // MenuItem for editing the currently selected entry + editItem = new MenuItem(menu, SWT.NONE, index + 1); + editItem.setText("Edit"); + editItem.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { + parentView.editSelectedItem(); + } - private PropertyKeySelectionTree parentView; - private ISelection selection; - private boolean legalSelection = false; + @Override + public void widgetDefaultSelected(SelectionEvent e) { - // Menu-Items - private MenuItem addItem; - private MenuItem editItem; - private MenuItem removeItem; + } + }); + + // MenuItem for deleting the currently selected entry + removeItem = new MenuItem(menu, SWT.NONE, index + 2); + removeItem.setText("Remove"); + removeItem.setImage(PlatformUI.getWorkbench().getSharedImages() + .getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE) + .createImage()); + removeItem.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { + parentView.deleteSelectedItems(); + } - public ResourceBundleEntry() { - } + @Override + public void widgetDefaultSelected(SelectionEvent e) { - public ResourceBundleEntry(PropertyKeySelectionTree view, - ISelection selection) { - this.selection = selection; - this.legalSelection = !selection.isEmpty(); - this.parentView = view; - parentView.addSelectionChangedListener(this); - } - - @Override - public void fill(Menu menu, int index) { - - // MenuItem for adding a new entry - addItem = new MenuItem(menu, SWT.NONE, index); - addItem.setText("Add ..."); - addItem.setImage(PlatformUI.getWorkbench().getSharedImages() - .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage()); - addItem.addSelectionListener(new SelectionListener() { - - @Override - public void widgetSelected(SelectionEvent e) { - parentView.addNewItem(selection); - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - - } - }); - - if ((parentView == null && legalSelection) || parentView != null) { - // MenuItem for editing the currently selected entry - editItem = new MenuItem(menu, SWT.NONE, index + 1); - editItem.setText("Edit"); - editItem.addSelectionListener(new SelectionListener() { - - @Override - public void widgetSelected(SelectionEvent e) { - parentView.editSelectedItem(); - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - - } - }); - - // MenuItem for deleting the currently selected entry - removeItem = new MenuItem(menu, SWT.NONE, index + 2); - removeItem.setText("Remove"); - removeItem.setImage(PlatformUI.getWorkbench().getSharedImages() - .getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE) - .createImage()); - removeItem.addSelectionListener(new SelectionListener() { - - @Override - public void widgetSelected(SelectionEvent e) { - parentView.deleteSelectedItems(); - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - - } - }); - enableMenuItems(); } + }); + enableMenuItems(); } - - protected void enableMenuItems() { - try { - editItem.setEnabled(legalSelection); - removeItem.setEnabled(legalSelection); - } catch (Exception e) { - // silent catch - } + } + + protected void enableMenuItems() { + try { + editItem.setEnabled(legalSelection); + removeItem.setEnabled(legalSelection); + } catch (Exception e) { + // silent catch } + } - @Override - public void selectionChanged(SelectionChangedEvent event) { - legalSelection = !event.getSelection().isEmpty(); - // enableMenuItems (); - } + @Override + public void selectionChanged(SelectionChangedEvent event) { + legalSelection = !event.getSelection().isEmpty(); + // enableMenuItems (); + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/SortInfo.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/SortInfo.java index b7e9ec0a..07442358 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/SortInfo.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/SortInfo.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -17,49 +17,49 @@ public class SortInfo { - public static final String TAG_SORT_INFO = "sort_info"; - public static final String TAG_COLUMN_INDEX = "col_idx"; - public static final String TAG_ORDER = "order"; + public static final String TAG_SORT_INFO = "sort_info"; + public static final String TAG_COLUMN_INDEX = "col_idx"; + public static final String TAG_ORDER = "order"; - private int colIdx; - private boolean DESC; - private List<Locale> visibleLocales; + private int colIdx; + private boolean DESC; + private List<Locale> visibleLocales; - public void setDESC(boolean dESC) { - DESC = dESC; - } + public void setDESC(boolean dESC) { + DESC = dESC; + } - public boolean isDESC() { - return DESC; - } + public boolean isDESC() { + return DESC; + } - public void setColIdx(int colIdx) { - this.colIdx = colIdx; - } + public void setColIdx(int colIdx) { + this.colIdx = colIdx; + } - public int getColIdx() { - return colIdx; - } + public int getColIdx() { + return colIdx; + } - public void setVisibleLocales(List<Locale> visibleLocales) { - this.visibleLocales = visibleLocales; - } + public void setVisibleLocales(List<Locale> visibleLocales) { + this.visibleLocales = visibleLocales; + } - public List<Locale> getVisibleLocales() { - return visibleLocales; - } + public List<Locale> getVisibleLocales() { + return visibleLocales; + } - public void saveState(IMemento memento) { - IMemento mCI = memento.createChild(TAG_SORT_INFO); - mCI.putInteger(TAG_COLUMN_INDEX, colIdx); - mCI.putBoolean(TAG_ORDER, DESC); - } + public void saveState(IMemento memento) { + IMemento mCI = memento.createChild(TAG_SORT_INFO); + mCI.putInteger(TAG_COLUMN_INDEX, colIdx); + mCI.putBoolean(TAG_ORDER, DESC); + } - public void init(IMemento memento) { - IMemento mCI = memento.getChild(TAG_SORT_INFO); - if (mCI == null) - return; - colIdx = mCI.getInteger(TAG_COLUMN_INDEX); - DESC = mCI.getBoolean(TAG_ORDER); - } + public void init(IMemento memento) { + IMemento mCI = memento.getChild(TAG_SORT_INFO); + if (mCI == null) + return; + colIdx = mCI.getInteger(TAG_COLUMN_INDEX); + DESC = mCI.getBoolean(TAG_ORDER); + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java index 1d59cad0..3033bada 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Martin Reiterer, Matthias Lettmayer, Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -33,148 +33,148 @@ import org.eclipse.swt.widgets.TreeItem; public class KeyTreeItemDropTarget extends DropTargetAdapter { - private final TreeViewer target; - - public KeyTreeItemDropTarget(TreeViewer viewer) { - super(); - this.target = viewer; + private final TreeViewer target; + + public KeyTreeItemDropTarget(TreeViewer viewer) { + super(); + this.target = viewer; + } + + public void dragEnter(DropTargetEvent event) { + // if (((DropTarget)event.getSource()).getControl() instanceof Tree) + // event.detail = DND.DROP_MOVE; + } + + private void addBundleEntries(final String keyPrefix, // new prefix + final IKeyTreeNode children, final IMessagesBundleGroup bundleGroup) { + + try { + String oldKey = children.getMessageKey(); + String key = children.getName(); + String newKey = keyPrefix + "." + key; + + IMessage[] messages = bundleGroup.getMessages(oldKey); + for (IMessage message : messages) { + IMessagesBundle messagesBundle = bundleGroup + .getMessagesBundle(message.getLocale()); + IMessage m = MessageFactory.createMessage(newKey, + message.getLocale()); + m.setText(message.getValue()); + m.setComment(message.getComment()); + messagesBundle.addMessage(m); + } + + if (messages.length == 0) { + bundleGroup.addMessages(newKey); + } + + for (IKeyTreeNode childs : children.getChildren()) { + addBundleEntries(keyPrefix + "." + key, childs, bundleGroup); + } + + } catch (Exception e) { + Logger.logError(e); } - public void dragEnter(DropTargetEvent event) { - // if (((DropTarget)event.getSource()).getControl() instanceof Tree) - // event.detail = DND.DROP_MOVE; + } + + private void remBundleEntries(IKeyTreeNode children, + IMessagesBundleGroup group) { + String key = children.getMessageKey(); + + for (IKeyTreeNode childs : children.getChildren()) { + remBundleEntries(childs, group); } - private void addBundleEntries(final String keyPrefix, // new prefix - final IKeyTreeNode children, final IMessagesBundleGroup bundleGroup) { + group.removeMessagesAddParentKey(key); + } + public void drop(final DropTargetEvent event) { + Display.getDefault().asyncExec(new Runnable() { + public void run() { try { - String oldKey = children.getMessageKey(); - String key = children.getName(); - String newKey = keyPrefix + "." + key; - - IMessage[] messages = bundleGroup.getMessages(oldKey); - for (IMessage message : messages) { - IMessagesBundle messagesBundle = bundleGroup - .getMessagesBundle(message.getLocale()); - IMessage m = MessageFactory.createMessage(newKey, - message.getLocale()); - m.setText(message.getValue()); - m.setComment(message.getComment()); - messagesBundle.addMessage(m); - } - if (messages.length == 0) { - bundleGroup.addMessages(newKey); - } + if (TextTransfer.getInstance().isSupportedType( + event.currentDataType)) { + String newKeyPrefix = ""; - for (IKeyTreeNode childs : children.getChildren()) { - addBundleEntries(keyPrefix + "." + key, childs, bundleGroup); + if (event.item instanceof TreeItem + && ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) { + IValuedKeyTreeNode targetTreeNode = (IValuedKeyTreeNode) ((TreeItem) event.item) + .getData(); + newKeyPrefix = targetTreeNode.getMessageKey(); } - } catch (Exception e) { - Logger.logError(e); - } + String message = (String) event.data; + String oldKey = message.replaceAll("\"", ""); + + String[] keyArr = (oldKey).split("\\."); + String key = keyArr[keyArr.length - 1]; + + ResKeyTreeContentProvider contentProvider = (ResKeyTreeContentProvider) target + .getContentProvider(); + IAbstractKeyTreeModel keyTree = (IAbstractKeyTreeModel) target + .getInput(); + + // key gets dropped into it's parent node + if (oldKey.equals(newKeyPrefix + "." + key)) + return; // TODO: give user feedback + + // prevent cycle loop if key gets dropped into its child + // node + if (newKeyPrefix.contains(oldKey)) + return; // TODO: give user feedback + + // source node already exists in target + IKeyTreeNode targetTreeNode = keyTree + .getChild(newKeyPrefix); + for (IKeyTreeNode targetChild : targetTreeNode + .getChildren()) { + if (targetChild.getName().equals(key)) + return; // TODO: give user feedback + } - } + IKeyTreeNode sourceTreeNode = keyTree.getChild(oldKey); - private void remBundleEntries(IKeyTreeNode children, - IMessagesBundleGroup group) { - String key = children.getMessageKey(); + IMessagesBundleGroup bundleGroup = contentProvider + .getBundle(); - for (IKeyTreeNode childs : children.getChildren()) { - remBundleEntries(childs, group); - } + DirtyHack.setFireEnabled(false); + DirtyHack.setEditorModificationEnabled(false); // editor + // won't + // get + // dirty - group.removeMessagesAddParentKey(key); - } + // add new bundle entries of source node + all children + addBundleEntries(newKeyPrefix, sourceTreeNode, + bundleGroup); - public void drop(final DropTargetEvent event) { - Display.getDefault().asyncExec(new Runnable() { - public void run() { - try { - - if (TextTransfer.getInstance().isSupportedType( - event.currentDataType)) { - String newKeyPrefix = ""; - - if (event.item instanceof TreeItem - && ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) { - IValuedKeyTreeNode targetTreeNode = (IValuedKeyTreeNode) ((TreeItem) event.item) - .getData(); - newKeyPrefix = targetTreeNode.getMessageKey(); - } - - String message = (String) event.data; - String oldKey = message.replaceAll("\"", ""); - - String[] keyArr = (oldKey).split("\\."); - String key = keyArr[keyArr.length - 1]; - - ResKeyTreeContentProvider contentProvider = (ResKeyTreeContentProvider) target - .getContentProvider(); - IAbstractKeyTreeModel keyTree = (IAbstractKeyTreeModel) target - .getInput(); - - // key gets dropped into it's parent node - if (oldKey.equals(newKeyPrefix + "." + key)) - return; // TODO: give user feedback - - // prevent cycle loop if key gets dropped into its child - // node - if (newKeyPrefix.contains(oldKey)) - return; // TODO: give user feedback - - // source node already exists in target - IKeyTreeNode targetTreeNode = keyTree - .getChild(newKeyPrefix); - for (IKeyTreeNode targetChild : targetTreeNode - .getChildren()) { - if (targetChild.getName().equals(key)) - return; // TODO: give user feedback - } - - IKeyTreeNode sourceTreeNode = keyTree.getChild(oldKey); - - IMessagesBundleGroup bundleGroup = contentProvider - .getBundle(); - - DirtyHack.setFireEnabled(false); - DirtyHack.setEditorModificationEnabled(false); // editor - // won't - // get - // dirty - - // add new bundle entries of source node + all children - addBundleEntries(newKeyPrefix, sourceTreeNode, - bundleGroup); - - // if drag & drop is move event, delete source entry + - // it's children - if (event.detail == DND.DROP_MOVE) { - remBundleEntries(sourceTreeNode, bundleGroup); - } - - // Store changes - RBManager manager = RBManager - .getInstance(((MessagesBundleGroup) bundleGroup) - .getProjectName()); - - manager.writeToFile(bundleGroup); - manager.fireEditorChanged(); // refresh the View - - target.refresh(); - } else { - event.detail = DND.DROP_NONE; - } - - } catch (Exception e) { - Logger.logError(e); - } finally { - DirtyHack.setFireEnabled(true); - DirtyHack.setEditorModificationEnabled(true); - } + // if drag & drop is move event, delete source entry + + // it's children + if (event.detail == DND.DROP_MOVE) { + remBundleEntries(sourceTreeNode, bundleGroup); } - }); - } + + // Store changes + RBManager manager = RBManager + .getInstance(((MessagesBundleGroup) bundleGroup) + .getProjectName()); + + manager.writeToFile(bundleGroup); + manager.fireEditorChanged(); // refresh the View + + target.refresh(); + } else { + event.detail = DND.DROP_NONE; + } + + } catch (Exception e) { + Logger.logError(e); + } finally { + DirtyHack.setFireEnabled(true); + DirtyHack.setEditorModificationEnabled(true); + } + } + }); + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java index cc788a4c..0739878b 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -26,91 +26,91 @@ public class KeyTreeItemTransfer extends ByteArrayTransfer { - private static final String KEY_TREE_ITEM = "keyTreeItem"; + private static final String KEY_TREE_ITEM = "keyTreeItem"; - private static final int TYPEID = registerType(KEY_TREE_ITEM); + private static final int TYPEID = registerType(KEY_TREE_ITEM); - private static KeyTreeItemTransfer transfer = new KeyTreeItemTransfer(); + private static KeyTreeItemTransfer transfer = new KeyTreeItemTransfer(); - public static KeyTreeItemTransfer getInstance() { - return transfer; - } + public static KeyTreeItemTransfer getInstance() { + return transfer; + } - public void javaToNative(Object object, TransferData transferData) { - if (!checkType(object) || !isSupportedType(transferData)) { - DND.error(DND.ERROR_INVALID_DATA); - } - IKeyTreeNode[] terms = (IKeyTreeNode[]) object; - try { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ObjectOutputStream oOut = new ObjectOutputStream(out); - for (int i = 0, length = terms.length; i < length; i++) { - oOut.writeObject(terms[i]); - } - byte[] buffer = out.toByteArray(); - oOut.close(); - - super.javaToNative(buffer, transferData); - } catch (IOException e) { - Logger.logError(e); - } + public void javaToNative(Object object, TransferData transferData) { + if (!checkType(object) || !isSupportedType(transferData)) { + DND.error(DND.ERROR_INVALID_DATA); } + IKeyTreeNode[] terms = (IKeyTreeNode[]) object; + try { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ObjectOutputStream oOut = new ObjectOutputStream(out); + for (int i = 0, length = terms.length; i < length; i++) { + oOut.writeObject(terms[i]); + } + byte[] buffer = out.toByteArray(); + oOut.close(); + + super.javaToNative(buffer, transferData); + } catch (IOException e) { + Logger.logError(e); + } + } + + public Object nativeToJava(TransferData transferData) { + if (isSupportedType(transferData)) { + + byte[] buffer; + try { + buffer = (byte[]) super.nativeToJava(transferData); + } catch (Exception e) { + Logger.logError(e); + buffer = null; + } + if (buffer == null) + return null; - public Object nativeToJava(TransferData transferData) { - if (isSupportedType(transferData)) { - - byte[] buffer; - try { - buffer = (byte[]) super.nativeToJava(transferData); - } catch (Exception e) { - Logger.logError(e); - buffer = null; - } - if (buffer == null) - return null; - - List<IKeyTreeNode> terms = new ArrayList<IKeyTreeNode>(); - try { - ByteArrayInputStream in = new ByteArrayInputStream(buffer); - ObjectInputStream readIn = new ObjectInputStream(in); - // while (readIn.available() > 0) { - IKeyTreeNode newTerm = (IKeyTreeNode) readIn.readObject(); - terms.add(newTerm); - // } - readIn.close(); - } catch (Exception ex) { - Logger.logError(ex); - return null; - } - return terms.toArray(new IKeyTreeNode[terms.size()]); - } - + List<IKeyTreeNode> terms = new ArrayList<IKeyTreeNode>(); + try { + ByteArrayInputStream in = new ByteArrayInputStream(buffer); + ObjectInputStream readIn = new ObjectInputStream(in); + // while (readIn.available() > 0) { + IKeyTreeNode newTerm = (IKeyTreeNode) readIn.readObject(); + terms.add(newTerm); + // } + readIn.close(); + } catch (Exception ex) { + Logger.logError(ex); return null; + } + return terms.toArray(new IKeyTreeNode[terms.size()]); } - protected String[] getTypeNames() { - return new String[] { KEY_TREE_ITEM }; - } + return null; + } - protected int[] getTypeIds() { - return new int[] { TYPEID }; - } + protected String[] getTypeNames() { + return new String[] { KEY_TREE_ITEM }; + } - boolean checkType(Object object) { - if (object == null || !(object instanceof IKeyTreeNode[]) - || ((IKeyTreeNode[]) object).length == 0) { - return false; - } - IKeyTreeNode[] myTypes = (IKeyTreeNode[]) object; - for (int i = 0; i < myTypes.length; i++) { - if (myTypes[i] == null) { - return false; - } - } - return true; - } + protected int[] getTypeIds() { + return new int[] { TYPEID }; + } - protected boolean validate(Object object) { - return checkType(object); + boolean checkType(Object object) { + if (object == null || !(object instanceof IKeyTreeNode[]) + || ((IKeyTreeNode[]) object).length == 0) { + return false; } + IKeyTreeNode[] myTypes = (IKeyTreeNode[]) object; + for (int i = 0; i < myTypes.length; i++) { + if (myTypes[i] == null) { + return false; + } + } + return true; + } + + protected boolean validate(Object object) { + return checkType(object); + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java index 1a770030..d6c0094e 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -18,37 +18,37 @@ public class MessagesDragSource implements DragSourceListener { - private final TreeViewer source; - private String bundleId; + private final TreeViewer source; + private String bundleId; - public MessagesDragSource(TreeViewer sourceView, String bundleId) { - source = sourceView; - this.bundleId = bundleId; - } + public MessagesDragSource(TreeViewer sourceView, String bundleId) { + source = sourceView; + this.bundleId = bundleId; + } - @Override - public void dragFinished(DragSourceEvent event) { + @Override + public void dragFinished(DragSourceEvent event) { - } + } - @Override - public void dragSetData(DragSourceEvent event) { - IKeyTreeNode selectionObject = (IKeyTreeNode) ((IStructuredSelection) source - .getSelection()).toList().get(0); + @Override + public void dragSetData(DragSourceEvent event) { + IKeyTreeNode selectionObject = (IKeyTreeNode) ((IStructuredSelection) source + .getSelection()).toList().get(0); - String key = selectionObject.getMessageKey(); + String key = selectionObject.getMessageKey(); - // TODO Solve the problem that its not possible to retrieve the editor - // position of the drop event + // TODO Solve the problem that its not possible to retrieve the editor + // position of the drop event - // event.data = "(new ResourceBundle(\"" + bundleId + - // "\")).getString(\"" + key + "\")"; - event.data = "\"" + key + "\""; - } + // event.data = "(new ResourceBundle(\"" + bundleId + + // "\")).getString(\"" + key + "\")"; + event.data = "\"" + key + "\""; + } - @Override - public void dragStart(DragSourceEvent event) { - event.doit = !source.getSelection().isEmpty(); - } + @Override + public void dragStart(DragSourceEvent event) { + event.doit = !source.getSelection().isEmpty(); + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java index 9221b9e6..8d0906ad 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -24,52 +24,52 @@ import org.eclipse.swt.widgets.TreeItem; public class MessagesDropTarget extends DropTargetAdapter { - private final String projectName; - private String bundleName; + private final String projectName; + private String bundleName; - public MessagesDropTarget(TreeViewer viewer, String projectName, - String bundleName) { - super(); - this.projectName = projectName; - this.bundleName = bundleName; - } + public MessagesDropTarget(TreeViewer viewer, String projectName, + String bundleName) { + super(); + this.projectName = projectName; + this.bundleName = bundleName; + } - public void dragEnter(DropTargetEvent event) { - } + public void dragEnter(DropTargetEvent event) { + } - public void drop(DropTargetEvent event) { - if (event.detail != DND.DROP_COPY) - return; + public void drop(DropTargetEvent event) { + if (event.detail != DND.DROP_COPY) + return; - if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) { - // event.feedback = DND.FEEDBACK_INSERT_BEFORE; - String newKeyPrefix = ""; + if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) { + // event.feedback = DND.FEEDBACK_INSERT_BEFORE; + String newKeyPrefix = ""; - if (event.item instanceof TreeItem - && ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) { - newKeyPrefix = ((IValuedKeyTreeNode) ((TreeItem) event.item) - .getData()).getMessageKey(); - } + if (event.item instanceof TreeItem + && ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) { + newKeyPrefix = ((IValuedKeyTreeNode) ((TreeItem) event.item) + .getData()).getMessageKey(); + } - String message = (String) event.data; + String message = (String) event.data; - CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( - Display.getDefault().getActiveShell()); + CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( + Display.getDefault().getActiveShell()); - DialogConfiguration config = dialog.new DialogConfiguration(); - config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix - + "." + "[Platzhalter]" - : ""); - config.setPreselectedMessage(message); - config.setPreselectedBundle(bundleName); - config.setPreselectedLocale(""); - config.setProjectName(projectName); + DialogConfiguration config = dialog.new DialogConfiguration(); + config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix + + "." + "[Platzhalter]" + : ""); + config.setPreselectedMessage(message); + config.setPreselectedBundle(bundleName); + config.setPreselectedLocale(""); + config.setProjectName(projectName); - dialog.setDialogConfiguration(config); + dialog.setDialogConfiguration(config); - if (dialog.open() != InputDialog.OK) - return; - } else - event.detail = DND.DROP_NONE; - } + if (dialog.open() != InputDialog.OK) + return; + } else + event.detail = DND.DROP_NONE; + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/MVTextTransfer.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/MVTextTransfer.java index 68d47807..17381c24 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/MVTextTransfer.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/MVTextTransfer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -12,7 +12,7 @@ public class MVTextTransfer { - private MVTextTransfer() { - } + private MVTextTransfer() { + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java index 17a89ea1..b4900a44 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Martin Reiterer, Clemente Lodi-Fe, Matthias Lettmayer, Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -9,9 +9,9 @@ * Martin Reiterer - initial API and implementation * Clemente Lodi-Fe - bug fix * Matthias Lettmayer - key traversal + updating tree improvement (fixed issue 22) - * - fixed editSelectedItem() to open an editor and select the key (fixed issue 59) + * - fixed editSelectedItem() to open an editor and select the key (fixed issue 59) * Alexej Strelzow - modified CreateResourceBundleEntryDialog instantiation - * - tree expand, Babel integration + * - tree expand, Babel integration ******************************************************************************/ package org.eclipse.babel.tapiji.tools.core.ui.widgets; @@ -90,725 +90,726 @@ import org.eclipse.ui.PlatformUI; public class PropertyKeySelectionTree extends Composite implements - IResourceBundleChangedListener { - - private final int KEY_COLUMN_WEIGHT = 1; - private final int LOCALE_COLUMN_WEIGHT = 1; - - private List<Locale> visibleLocales = new ArrayList<Locale>(); - private boolean editable; - private String resourceBundle; - - private IWorkbenchPartSite site; - private TreeColumnLayout basicLayout; - private TreeViewer treeViewer; - private TreeColumn keyColumn; - private boolean grouped = true; - private boolean fuzzyMatchingEnabled = false; - private float matchingPrecision = .75f; - private Locale uiLocale = new Locale("en"); - - private SortInfo sortInfo; - - private ResKeyTreeContentProvider contentProvider; - private ResKeyTreeLabelProvider labelProvider; - private TreeType treeType = TreeType.Tree; - - private IMessagesEditorListener editorListener; - - /*** MATCHER ***/ - ExactMatcher matcher; - - /*** SORTER ***/ - ValuedKeyTreeItemSorter sorter; - - /*** ACTIONS ***/ - private Action doubleClickAction; - - /*** LISTENERS ***/ - private ISelectionChangedListener selectionChangedListener; - private String projectName; - - public PropertyKeySelectionTree(IViewSite viewSite, - IWorkbenchPartSite site, Composite parent, int style, - String projectName, String resources, List<Locale> locales) { - super(parent, style); - this.site = site; - this.resourceBundle = resources; - this.projectName = projectName; - - if (resourceBundle != null && resourceBundle.trim().length() > 0) { - if (locales == null) - initVisibleLocales(); - else - this.visibleLocales = locales; + IResourceBundleChangedListener { + + private final int KEY_COLUMN_WEIGHT = 1; + private final int LOCALE_COLUMN_WEIGHT = 1; + + private List<Locale> visibleLocales = new ArrayList<Locale>(); + private boolean editable; + private String resourceBundle; + + private IWorkbenchPartSite site; + private TreeColumnLayout basicLayout; + private TreeViewer treeViewer; + private TreeColumn keyColumn; + private boolean grouped = true; + private boolean fuzzyMatchingEnabled = false; + private float matchingPrecision = .75f; + private Locale uiLocale = new Locale("en"); + + private SortInfo sortInfo; + + private ResKeyTreeContentProvider contentProvider; + private ResKeyTreeLabelProvider labelProvider; + private TreeType treeType = TreeType.Tree; + + private IMessagesEditorListener editorListener; + + /*** MATCHER ***/ + ExactMatcher matcher; + + /*** SORTER ***/ + ValuedKeyTreeItemSorter sorter; + + /*** ACTIONS ***/ + private Action doubleClickAction; + + /*** LISTENERS ***/ + private ISelectionChangedListener selectionChangedListener; + private String projectName; + + public PropertyKeySelectionTree(IViewSite viewSite, + IWorkbenchPartSite site, Composite parent, int style, + String projectName, String resources, List<Locale> locales) { + super(parent, style); + this.site = site; + this.resourceBundle = resources; + this.projectName = projectName; + + if (resourceBundle != null && resourceBundle.trim().length() > 0) { + if (locales == null) + initVisibleLocales(); + else + this.visibleLocales = locales; + } + + constructWidget(); + + if (resourceBundle != null && resourceBundle.trim().length() > 0) { + initTreeViewer(); + initMatchers(); + initSorters(); + treeViewer.expandAll(); + } + + hookDragAndDrop(); + registerListeners(); + } + + @Override + public void dispose() { + super.dispose(); + unregisterListeners(); + } + + protected void initSorters() { + sorter = new ValuedKeyTreeItemSorter(treeViewer, sortInfo); + treeViewer.setSorter(sorter); + } + + public void enableFuzzyMatching(boolean enable) { + String pattern = ""; + if (matcher != null) { + pattern = matcher.getPattern(); + + if (!fuzzyMatchingEnabled && enable) { + if (matcher.getPattern().trim().length() > 1 + && matcher.getPattern().startsWith("*") + && matcher.getPattern().endsWith("*")) + pattern = pattern.substring(1).substring(0, + pattern.length() - 2); + matcher.setPattern(null); + } + } + fuzzyMatchingEnabled = enable; + initMatchers(); + + matcher.setPattern(pattern); + treeViewer.refresh(); + } + + public boolean isFuzzyMatchingEnabled() { + return fuzzyMatchingEnabled; + } + + protected void initMatchers() { + treeViewer.resetFilters(); + + if (fuzzyMatchingEnabled) { + matcher = new FuzzyMatcher(treeViewer); + ((FuzzyMatcher) matcher).setMinimumSimilarity(matchingPrecision); + } else + matcher = new ExactMatcher(treeViewer); + + } + + protected void initTreeViewer() { + this.setRedraw(false); + // init content provider + contentProvider = new ResKeyTreeContentProvider(visibleLocales, + projectName, resourceBundle, treeType); + treeViewer.setContentProvider(contentProvider); + + // init label provider + labelProvider = new ResKeyTreeLabelProvider(visibleLocales); + treeViewer.setLabelProvider(labelProvider); + + // we need this to keep the tree expanded + treeViewer.setComparer(new IElementComparer() { + + @Override + public int hashCode(Object element) { + final int prime = 31; + int result = 1; + result = prime * result + + ((toString() == null) ? 0 : toString().hashCode()); + return result; + } + + @Override + public boolean equals(Object a, Object b) { + if (a == b) { + return true; } - - constructWidget(); - - if (resourceBundle != null && resourceBundle.trim().length() > 0) { - initTreeViewer(); - initMatchers(); - initSorters(); - treeViewer.expandAll(); + if (a instanceof IKeyTreeNode && b instanceof IKeyTreeNode) { + IKeyTreeNode nodeA = (IKeyTreeNode) a; + IKeyTreeNode nodeB = (IKeyTreeNode) b; + return nodeA.equals(nodeB); } - - hookDragAndDrop(); - registerListeners(); - } - - @Override - public void dispose() { - super.dispose(); - unregisterListeners(); - } - - protected void initSorters() { - sorter = new ValuedKeyTreeItemSorter(treeViewer, sortInfo); - treeViewer.setSorter(sorter); - } - - public void enableFuzzyMatching(boolean enable) { - String pattern = ""; - if (matcher != null) { - pattern = matcher.getPattern(); - - if (!fuzzyMatchingEnabled && enable) { - if (matcher.getPattern().trim().length() > 1 - && matcher.getPattern().startsWith("*") - && matcher.getPattern().endsWith("*")) - pattern = pattern.substring(1).substring(0, - pattern.length() - 2); - matcher.setPattern(null); - } - } - fuzzyMatchingEnabled = enable; - initMatchers(); - - matcher.setPattern(pattern); - treeViewer.refresh(); - } - - public boolean isFuzzyMatchingEnabled() { - return fuzzyMatchingEnabled; - } - - protected void initMatchers() { - treeViewer.resetFilters(); - - if (fuzzyMatchingEnabled) { - matcher = new FuzzyMatcher(treeViewer); - ((FuzzyMatcher) matcher).setMinimumSimilarity(matchingPrecision); - } else - matcher = new ExactMatcher(treeViewer); - - } - - protected void initTreeViewer() { - this.setRedraw(false); - // init content provider - contentProvider = new ResKeyTreeContentProvider(visibleLocales, - projectName, resourceBundle, treeType); - treeViewer.setContentProvider(contentProvider); - - // init label provider - labelProvider = new ResKeyTreeLabelProvider(visibleLocales); - treeViewer.setLabelProvider(labelProvider); - - // we need this to keep the tree expanded - treeViewer.setComparer(new IElementComparer() { - - @Override - public int hashCode(Object element) { - final int prime = 31; - int result = 1; - result = prime * result - + ((toString() == null) ? 0 : toString().hashCode()); - return result; - } - - @Override - public boolean equals(Object a, Object b) { - if (a == b) { - return true; - } - if (a instanceof IKeyTreeNode && b instanceof IKeyTreeNode) { - IKeyTreeNode nodeA = (IKeyTreeNode) a; - IKeyTreeNode nodeB = (IKeyTreeNode) b; - return nodeA.equals(nodeB); - } - return false; - } - }); - - setTreeStructure(); - this.setRedraw(true); - } - - public void setTreeStructure() { - IAbstractKeyTreeModel model = KeyTreeFactory - .createModel(ResourceBundleManager.getManager(projectName) - .getResourceBundle(resourceBundle)); - if (treeViewer.getInput() == null) { - treeViewer.setUseHashlookup(true); - } - org.eclipse.jface.viewers.TreePath[] expandedTreePaths = treeViewer - .getExpandedTreePaths(); - treeViewer.setInput(model); - treeViewer.refresh(); - treeViewer.setExpandedTreePaths(expandedTreePaths); - } - - protected void refreshContent(ResourceBundleChangedEvent event) { - if (visibleLocales == null) { - initVisibleLocales(); - } - ResourceBundleManager manager = ResourceBundleManager - .getManager(projectName); - - // update content provider - contentProvider.setLocales(visibleLocales); - contentProvider.setProjectName(manager.getProject().getName()); - contentProvider.setBundleId(resourceBundle); - - // init label provider - IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle); - labelProvider.setLocales(visibleLocales); - if (treeViewer.getLabelProvider() != labelProvider) - treeViewer.setLabelProvider(labelProvider); - - // define input of treeviewer - setTreeStructure(); - } - - protected void initVisibleLocales() { - SortedMap<String, Locale> locSorted = new TreeMap<String, Locale>(); - ResourceBundleManager manager = ResourceBundleManager - .getManager(projectName); - sortInfo = new SortInfo(); - visibleLocales.clear(); - if (resourceBundle != null) { - for (Locale l : manager.getProvidedLocales(resourceBundle)) { - if (l == null) { - locSorted.put("Default", null); - } else { - locSorted.put(l.getDisplayName(uiLocale), l); - } - } - } - - for (String lString : locSorted.keySet()) { - visibleLocales.add(locSorted.get(lString)); - } - sortInfo.setVisibleLocales(visibleLocales); - } - - protected void constructWidget() { - basicLayout = new TreeColumnLayout(); - this.setLayout(basicLayout); - - treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE - | SWT.BORDER); - Tree tree = treeViewer.getTree(); - - if (resourceBundle != null) { - tree.setHeaderVisible(true); - tree.setLinesVisible(true); - - // create tree-columns - constructTreeColumns(tree); + return false; + } + }); + + setTreeStructure(); + this.setRedraw(true); + } + + public void setTreeStructure() { + IAbstractKeyTreeModel model = KeyTreeFactory + .createModel(ResourceBundleManager.getManager(projectName) + .getResourceBundle(resourceBundle)); + if (treeViewer.getInput() == null) { + treeViewer.setUseHashlookup(true); + } + org.eclipse.jface.viewers.TreePath[] expandedTreePaths = treeViewer + .getExpandedTreePaths(); + treeViewer.setInput(model); + treeViewer.refresh(); + treeViewer.setExpandedTreePaths(expandedTreePaths); + } + + protected void refreshContent(ResourceBundleChangedEvent event) { + if (visibleLocales == null) { + initVisibleLocales(); + } + ResourceBundleManager manager = ResourceBundleManager + .getManager(projectName); + + // update content provider + contentProvider.setLocales(visibleLocales); + contentProvider.setProjectName(manager.getProject().getName()); + contentProvider.setBundleId(resourceBundle); + + // init label provider + IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle); + labelProvider.setLocales(visibleLocales); + if (treeViewer.getLabelProvider() != labelProvider) + treeViewer.setLabelProvider(labelProvider); + + // define input of treeviewer + setTreeStructure(); + } + + protected void initVisibleLocales() { + SortedMap<String, Locale> locSorted = new TreeMap<String, Locale>(); + ResourceBundleManager manager = ResourceBundleManager + .getManager(projectName); + sortInfo = new SortInfo(); + visibleLocales.clear(); + if (resourceBundle != null) { + for (Locale l : manager.getProvidedLocales(resourceBundle)) { + if (l == null) { + locSorted.put("Default", null); } else { - tree.setHeaderVisible(false); - tree.setLinesVisible(false); + locSorted.put(l.getDisplayName(uiLocale), l); } - - makeActions(); - hookDoubleClickAction(); - - // register messages table as selection provider - site.setSelectionProvider(treeViewer); - } - - protected void constructTreeColumns(Tree tree) { - tree.removeAll(); - // tree.getColumns().length; - - // construct key-column - keyColumn = new TreeColumn(tree, SWT.NONE); - keyColumn.setText("Key"); - keyColumn.addSelectionListener(new SelectionListener() { - - @Override - public void widgetSelected(SelectionEvent e) { - updateSorter(0); - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - updateSorter(0); + } + } + + for (String lString : locSorted.keySet()) { + visibleLocales.add(locSorted.get(lString)); + } + sortInfo.setVisibleLocales(visibleLocales); + } + + protected void constructWidget() { + basicLayout = new TreeColumnLayout(); + this.setLayout(basicLayout); + + treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE + | SWT.BORDER); + Tree tree = treeViewer.getTree(); + + if (resourceBundle != null) { + tree.setHeaderVisible(true); + tree.setLinesVisible(true); + + // create tree-columns + constructTreeColumns(tree); + } else { + tree.setHeaderVisible(false); + tree.setLinesVisible(false); + } + + makeActions(); + hookDoubleClickAction(); + + // register messages table as selection provider + site.setSelectionProvider(treeViewer); + } + + protected void constructTreeColumns(Tree tree) { + tree.removeAll(); + // tree.getColumns().length; + + // construct key-column + keyColumn = new TreeColumn(tree, SWT.NONE); + keyColumn.setText("Key"); + keyColumn.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { + updateSorter(0); + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + updateSorter(0); + } + }); + basicLayout.setColumnData(keyColumn, new ColumnWeightData( + KEY_COLUMN_WEIGHT)); + + if (visibleLocales != null) { + final ResourceBundleManager manager = ResourceBundleManager + .getManager(projectName); + for (final Locale l : visibleLocales) { + TreeColumn col = new TreeColumn(tree, SWT.NONE); + + // Add editing support to this table column + TreeViewerColumn tCol = new TreeViewerColumn(treeViewer, col); + tCol.setEditingSupport(new EditingSupport(treeViewer) { + + TextCellEditor editor = null; + + @Override + protected void setValue(Object element, Object value) { + + if (element instanceof IValuedKeyTreeNode) { + IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element; + String activeKey = vkti.getMessageKey(); + + if (activeKey != null) { + IMessagesBundleGroup bundleGroup = manager + .getResourceBundle(resourceBundle); + IMessage entry = bundleGroup.getMessage( + activeKey, l); + + if (entry == null + || !value.equals(entry.getValue())) { + String comment = null; + if (entry != null) { + comment = entry.getComment(); + } + + IMessagesBundle messagesBundle = bundleGroup + .getMessagesBundle(l); + + DirtyHack.setFireEnabled(false); + + IMessage message = messagesBundle + .getMessage(activeKey); + if (message == null) { + IMessage newMessage = MessageFactory + .createMessage(activeKey, l); + newMessage.setText(String + .valueOf(value)); + newMessage.setComment(comment); + messagesBundle.addMessage(newMessage); + } else { + message.setText(String.valueOf(value)); + message.setComment(comment); + } + + FileUtils.writeToFile(messagesBundle); + RBManager + .getInstance(manager.getProject()) + .fireResourceChanged(messagesBundle); + + // update TreeViewer + vkti.setValue(l, String.valueOf(value)); + treeViewer.refresh(); + + DirtyHack.setFireEnabled(true); + } + } } - }); - basicLayout.setColumnData(keyColumn, new ColumnWeightData( - KEY_COLUMN_WEIGHT)); - - if (visibleLocales != null) { - final ResourceBundleManager manager = ResourceBundleManager - .getManager(projectName); - for (final Locale l : visibleLocales) { - TreeColumn col = new TreeColumn(tree, SWT.NONE); - - // Add editing support to this table column - TreeViewerColumn tCol = new TreeViewerColumn(treeViewer, col); - tCol.setEditingSupport(new EditingSupport(treeViewer) { - - TextCellEditor editor = null; - - @Override - protected void setValue(Object element, Object value) { - - if (element instanceof IValuedKeyTreeNode) { - IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element; - String activeKey = vkti.getMessageKey(); - - if (activeKey != null) { - IMessagesBundleGroup bundleGroup = manager - .getResourceBundle(resourceBundle); - IMessage entry = bundleGroup.getMessage( - activeKey, l); - - if (entry == null - || !value.equals(entry.getValue())) { - String comment = null; - if (entry != null) { - comment = entry.getComment(); - } - - IMessagesBundle messagesBundle = bundleGroup - .getMessagesBundle(l); - - DirtyHack.setFireEnabled(false); - - IMessage message = messagesBundle - .getMessage(activeKey); - if (message == null) { - IMessage newMessage = MessageFactory - .createMessage(activeKey, l); - newMessage.setText(String - .valueOf(value)); - newMessage.setComment(comment); - messagesBundle.addMessage(newMessage); - } else { - message.setText(String.valueOf(value)); - message.setComment(comment); - } - - FileUtils.writeToFile(messagesBundle); - RBManager.getInstance(manager.getProject()).fireResourceChanged(messagesBundle); - - // update TreeViewer - vkti.setValue(l, String.valueOf(value)); - treeViewer.refresh(); - - DirtyHack.setFireEnabled(true); - } - } - } - } - - @Override - protected Object getValue(Object element) { - return labelProvider.getColumnText(element, - visibleLocales.indexOf(l) + 1); - } + } + + @Override + protected Object getValue(Object element) { + return labelProvider.getColumnText(element, + visibleLocales.indexOf(l) + 1); + } + + @Override + protected CellEditor getCellEditor(Object element) { + if (editor == null) { + Composite tree = (Composite) treeViewer + .getControl(); + editor = new TextCellEditor(tree); + editor.getControl().addTraverseListener( + new TraverseListener() { @Override - protected CellEditor getCellEditor(Object element) { - if (editor == null) { - Composite tree = (Composite) treeViewer - .getControl(); - editor = new TextCellEditor(tree); - editor.getControl().addTraverseListener( - new TraverseListener() { - - @Override - public void keyTraversed(TraverseEvent e) { - Logger.logInfo("CELL_EDITOR: " - + e.toString()); - if (e.detail == SWT.TRAVERSE_TAB_NEXT - || e.detail == SWT.TRAVERSE_TAB_PREVIOUS) { - - e.doit = false; - int colIndex = visibleLocales - .indexOf(l) + 1; - Object sel = ((IStructuredSelection) treeViewer - .getSelection()) - .getFirstElement(); - int noOfCols = treeViewer - .getTree() - .getColumnCount(); - - // go to next cell - if (e.detail == SWT.TRAVERSE_TAB_NEXT) { - int nextColIndex = colIndex + 1; - if (nextColIndex < noOfCols) - treeViewer.editElement( - sel, - nextColIndex); - // go to previous cell - } else if (e.detail == SWT.TRAVERSE_TAB_PREVIOUS) { - int prevColIndex = colIndex - 1; - if (prevColIndex > 0) - treeViewer.editElement( - sel, - colIndex - 1); - } - } - } - }); + public void keyTraversed(TraverseEvent e) { + Logger.logInfo("CELL_EDITOR: " + + e.toString()); + if (e.detail == SWT.TRAVERSE_TAB_NEXT + || e.detail == SWT.TRAVERSE_TAB_PREVIOUS) { + + e.doit = false; + int colIndex = visibleLocales + .indexOf(l) + 1; + Object sel = ((IStructuredSelection) treeViewer + .getSelection()) + .getFirstElement(); + int noOfCols = treeViewer + .getTree() + .getColumnCount(); + + // go to next cell + if (e.detail == SWT.TRAVERSE_TAB_NEXT) { + int nextColIndex = colIndex + 1; + if (nextColIndex < noOfCols) + treeViewer.editElement( + sel, + nextColIndex); + // go to previous cell + } else if (e.detail == SWT.TRAVERSE_TAB_PREVIOUS) { + int prevColIndex = colIndex - 1; + if (prevColIndex > 0) + treeViewer.editElement( + sel, + colIndex - 1); } - return editor; - } - - @Override - protected boolean canEdit(Object element) { - return editable; - } - }); - - String displayName = l == null ? ResourceBundleManager.defaultLocaleTag - : l.getDisplayName(uiLocale); - - col.setText(displayName); - col.addSelectionListener(new SelectionListener() { - - @Override - public void widgetSelected(SelectionEvent e) { - updateSorter(visibleLocales.indexOf(l) + 1); - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - updateSorter(visibleLocales.indexOf(l) + 1); + } } - }); - basicLayout.setColumnData(col, new ColumnWeightData( - LOCALE_COLUMN_WEIGHT)); + }); } - } - } + return editor; + } - protected void updateSorter(int idx) { - SortInfo sortInfo = sorter.getSortInfo(); - if (idx == sortInfo.getColIdx()) - sortInfo.setDESC(!sortInfo.isDESC()); - else { - sortInfo.setColIdx(idx); - sortInfo.setDESC(false); - } - sortInfo.setVisibleLocales(visibleLocales); - sorter.setSortInfo(sortInfo); - treeType = idx == 0 ? TreeType.Tree : TreeType.Flat; - setTreeStructure(); - treeViewer.refresh(); - } - - @Override - public boolean setFocus() { - return treeViewer.getControl().setFocus(); - } - - /*** DRAG AND DROP ***/ - protected void hookDragAndDrop() { - // KeyTreeItemDragSource ktiSource = new KeyTreeItemDragSource - // (treeViewer); - KeyTreeItemDropTarget ktiTarget = new KeyTreeItemDropTarget(treeViewer); - MessagesDragSource source = new MessagesDragSource(treeViewer, - this.resourceBundle); - MessagesDropTarget target = new MessagesDropTarget(treeViewer, - projectName, resourceBundle); - - // Initialize drag source for copy event - DragSource dragSource = new DragSource(treeViewer.getControl(), - DND.DROP_COPY | DND.DROP_MOVE); - dragSource.setTransfer(new Transfer[] { TextTransfer.getInstance() }); - // dragSource.addDragListener(ktiSource); - dragSource.addDragListener(source); - - // Initialize drop target for copy event - DropTarget dropTarget = new DropTarget(treeViewer.getControl(), - DND.DROP_MOVE | DND.DROP_COPY); - dropTarget.setTransfer(new Transfer[] { TextTransfer.getInstance(), - JavaUI.getJavaElementClipboardTransfer() }); - dropTarget.addDropListener(ktiTarget); - dropTarget.addDropListener(target); - } - - /*** ACTIONS ***/ - - private void makeActions() { - doubleClickAction = new Action() { - - @Override - public void run() { - editSelectedItem(); - } - - }; - } - - private void hookDoubleClickAction() { - treeViewer.addDoubleClickListener(new IDoubleClickListener() { - - public void doubleClick(DoubleClickEvent event) { - doubleClickAction.run(); - } + @Override + protected boolean canEdit(Object element) { + return editable; + } }); - } - /*** SELECTION LISTENER ***/ + String displayName = l == null ? ResourceBundleManager.defaultLocaleTag + : l.getDisplayName(uiLocale); - protected void registerListeners() { + col.setText(displayName); + col.addSelectionListener(new SelectionListener() { - this.editorListener = new MessagesEditorListener(); - ResourceBundleManager manager = ResourceBundleManager - .getManager(projectName); - if (manager != null) { - RBManager.getInstance(manager.getProject()) - .addMessagesEditorListener(editorListener); - } - - treeViewer.getControl().addKeyListener(new KeyAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + updateSorter(visibleLocales.indexOf(l) + 1); + } - public void keyPressed(KeyEvent event) { - if (event.character == SWT.DEL && event.stateMask == 0) { - deleteSelectedItems(); - } - } + @Override + public void widgetDefaultSelected(SelectionEvent e) { + updateSorter(visibleLocales.indexOf(l) + 1); + } }); - } - - protected void unregisterListeners() { - ResourceBundleManager manager = ResourceBundleManager - .getManager(projectName); - if (manager != null) { - RBManager.getInstance(manager.getProject()) - .removeMessagesEditorListener(editorListener); - } - treeViewer.removeSelectionChangedListener(selectionChangedListener); - } - - public void addSelectionChangedListener(ISelectionChangedListener listener) { - treeViewer.addSelectionChangedListener(listener); - selectionChangedListener = listener; - } - - @Override - public void resourceBundleChanged(final ResourceBundleChangedEvent event) { - if (event.getType() != ResourceBundleChangedEvent.MODIFIED - || !event.getBundle().equals(this.getResourceBundle())) - return; - - if (Display.getCurrent() != null) { - refreshViewer(event, true); - return; + basicLayout.setColumnData(col, new ColumnWeightData( + LOCALE_COLUMN_WEIGHT)); + } + } + } + + protected void updateSorter(int idx) { + SortInfo sortInfo = sorter.getSortInfo(); + if (idx == sortInfo.getColIdx()) + sortInfo.setDESC(!sortInfo.isDESC()); + else { + sortInfo.setColIdx(idx); + sortInfo.setDESC(false); + } + sortInfo.setVisibleLocales(visibleLocales); + sorter.setSortInfo(sortInfo); + treeType = idx == 0 ? TreeType.Tree : TreeType.Flat; + setTreeStructure(); + treeViewer.refresh(); + } + + @Override + public boolean setFocus() { + return treeViewer.getControl().setFocus(); + } + + /*** DRAG AND DROP ***/ + protected void hookDragAndDrop() { + // KeyTreeItemDragSource ktiSource = new KeyTreeItemDragSource + // (treeViewer); + KeyTreeItemDropTarget ktiTarget = new KeyTreeItemDropTarget(treeViewer); + MessagesDragSource source = new MessagesDragSource(treeViewer, + this.resourceBundle); + MessagesDropTarget target = new MessagesDropTarget(treeViewer, + projectName, resourceBundle); + + // Initialize drag source for copy event + DragSource dragSource = new DragSource(treeViewer.getControl(), + DND.DROP_COPY | DND.DROP_MOVE); + dragSource.setTransfer(new Transfer[] { TextTransfer.getInstance() }); + // dragSource.addDragListener(ktiSource); + dragSource.addDragListener(source); + + // Initialize drop target for copy event + DropTarget dropTarget = new DropTarget(treeViewer.getControl(), + DND.DROP_MOVE | DND.DROP_COPY); + dropTarget.setTransfer(new Transfer[] { TextTransfer.getInstance(), + JavaUI.getJavaElementClipboardTransfer() }); + dropTarget.addDropListener(ktiTarget); + dropTarget.addDropListener(target); + } + + /*** ACTIONS ***/ + + private void makeActions() { + doubleClickAction = new Action() { + + @Override + public void run() { + editSelectedItem(); + } + + }; + } + + private void hookDoubleClickAction() { + treeViewer.addDoubleClickListener(new IDoubleClickListener() { + + public void doubleClick(DoubleClickEvent event) { + doubleClickAction.run(); + } + }); + } + + /*** SELECTION LISTENER ***/ + + protected void registerListeners() { + + this.editorListener = new MessagesEditorListener(); + ResourceBundleManager manager = ResourceBundleManager + .getManager(projectName); + if (manager != null) { + RBManager.getInstance(manager.getProject()) + .addMessagesEditorListener(editorListener); + } + + treeViewer.getControl().addKeyListener(new KeyAdapter() { + + public void keyPressed(KeyEvent event) { + if (event.character == SWT.DEL && event.stateMask == 0) { + deleteSelectedItems(); } - - Display.getDefault().asyncExec(new Runnable() { - - public void run() { - refreshViewer(event, true); - } - }); - } - - private void refreshViewer(ResourceBundleChangedEvent event, - boolean computeVisibleLocales) { - // manager.loadResourceBundle(resourceBundle); - if (computeVisibleLocales) { - refreshContent(event); + } + }); + } + + protected void unregisterListeners() { + ResourceBundleManager manager = ResourceBundleManager + .getManager(projectName); + if (manager != null) { + RBManager.getInstance(manager.getProject()) + .removeMessagesEditorListener(editorListener); + } + treeViewer.removeSelectionChangedListener(selectionChangedListener); + } + + public void addSelectionChangedListener(ISelectionChangedListener listener) { + treeViewer.addSelectionChangedListener(listener); + selectionChangedListener = listener; + } + + @Override + public void resourceBundleChanged(final ResourceBundleChangedEvent event) { + if (event.getType() != ResourceBundleChangedEvent.MODIFIED + || !event.getBundle().equals(this.getResourceBundle())) + return; + + if (Display.getCurrent() != null) { + refreshViewer(event, true); + return; + } + + Display.getDefault().asyncExec(new Runnable() { + + public void run() { + refreshViewer(event, true); + } + }); + } + + private void refreshViewer(ResourceBundleChangedEvent event, + boolean computeVisibleLocales) { + // manager.loadResourceBundle(resourceBundle); + if (computeVisibleLocales) { + refreshContent(event); + } + + // Display.getDefault().asyncExec(new Runnable() { + // public void run() { + treeViewer.refresh(); + // } + // }); + } + + public StructuredViewer getViewer() { + return this.treeViewer; + } + + public void setSearchString(String pattern) { + matcher.setPattern(pattern); + treeType = matcher.getPattern().trim().length() > 0 ? TreeType.Flat + : TreeType.Tree; + labelProvider.setSearchEnabled(treeType.equals(TreeType.Flat)); + // WTF? + treeType = treeType.equals(TreeType.Tree) + && sorter.getSortInfo().getColIdx() == 0 ? TreeType.Tree + : TreeType.Flat; + treeViewer.refresh(); + + this.refreshContent(null); + + // highlight the search results + labelProvider.updateTreeViewer(treeViewer); + } + + public SortInfo getSortInfo() { + if (this.sorter != null) + return this.sorter.getSortInfo(); + else + return null; + } + + public void setSortInfo(SortInfo sortInfo) { + sortInfo.setVisibleLocales(visibleLocales); + if (sorter != null) { + sorter.setSortInfo(sortInfo); + treeType = sortInfo.getColIdx() == 0 ? TreeType.Tree + : TreeType.Flat; + treeViewer.refresh(); + } + } + + public String getSearchString() { + return matcher.getPattern(); + } + + public boolean isEditable() { + return editable; + } + + public void setEditable(boolean editable) { + this.editable = editable; + } + + public List<Locale> getVisibleLocales() { + return visibleLocales; + } + + public String getResourceBundle() { + return resourceBundle; + } + + public void editSelectedItem() { + String key = ""; + ISelection selection = treeViewer.getSelection(); + if (selection instanceof IStructuredSelection) { + IStructuredSelection structSel = (IStructuredSelection) selection; + if (structSel.getFirstElement() instanceof IKeyTreeNode) { + IKeyTreeNode keyTreeNode = (IKeyTreeNode) structSel + .getFirstElement(); + key = keyTreeNode.getMessageKey(); + } + } + + ResourceBundleManager manager = ResourceBundleManager + .getManager(projectName); + EditorUtils.openEditor(site.getPage(), + manager.getRandomFile(resourceBundle), + EditorUtils.RESOURCE_BUNDLE_EDITOR, key); + } + + public void deleteSelectedItems() { + List<String> keys = new ArrayList<String>(); + + IWorkbenchWindow window = PlatformUI.getWorkbench() + .getActiveWorkbenchWindow(); + ISelection selection = window.getActivePage().getSelection(); + if (selection instanceof IStructuredSelection) { + for (Iterator<?> iter = ((IStructuredSelection) selection) + .iterator(); iter.hasNext();) { + Object elem = iter.next(); + if (elem instanceof IKeyTreeNode) { + addKeysToRemove((IKeyTreeNode) elem, keys); } - - // Display.getDefault().asyncExec(new Runnable() { - // public void run() { - treeViewer.refresh(); - // } - // }); + } } - public StructuredViewer getViewer() { - return this.treeViewer; + try { + ResourceBundleManager manager = ResourceBundleManager + .getManager(projectName); + manager.removeResourceBundleEntry(getResourceBundle(), keys); + } catch (Exception ex) { + Logger.logError(ex); } + } - public void setSearchString(String pattern) { - matcher.setPattern(pattern); - treeType = matcher.getPattern().trim().length() > 0 ? TreeType.Flat - : TreeType.Tree; - labelProvider.setSearchEnabled(treeType.equals(TreeType.Flat)); - // WTF? - treeType = treeType.equals(TreeType.Tree) - && sorter.getSortInfo().getColIdx() == 0 ? TreeType.Tree - : TreeType.Flat; - treeViewer.refresh(); - - - this.refreshContent(null); - - // highlight the search results - labelProvider.updateTreeViewer(treeViewer); + private void addKeysToRemove(IKeyTreeNode node, List<String> keys) { + keys.add(node.getMessageKey()); + for (IKeyTreeNode ktn : node.getChildren()) { + addKeysToRemove(ktn, keys); } + } - public SortInfo getSortInfo() { - if (this.sorter != null) - return this.sorter.getSortInfo(); - else - return null; - } + public void addNewItem(ISelection selection) { + // event.feedback = DND.FEEDBACK_INSERT_BEFORE; + String newKeyPrefix = ""; - public void setSortInfo(SortInfo sortInfo) { - sortInfo.setVisibleLocales(visibleLocales); - if (sorter != null) { - sorter.setSortInfo(sortInfo); - treeType = sortInfo.getColIdx() == 0 ? TreeType.Tree - : TreeType.Flat; - treeViewer.refresh(); + if (selection instanceof IStructuredSelection) { + for (Iterator<?> iter = ((IStructuredSelection) selection) + .iterator(); iter.hasNext();) { + Object elem = iter.next(); + if (elem instanceof IKeyTreeNode) { + newKeyPrefix = ((IKeyTreeNode) elem).getMessageKey(); + break; } + } } - public String getSearchString() { - return matcher.getPattern(); - } - - public boolean isEditable() { - return editable; - } - - public void setEditable(boolean editable) { - this.editable = editable; - } - - public List<Locale> getVisibleLocales() { - return visibleLocales; - } - - public String getResourceBundle() { - return resourceBundle; - } - - public void editSelectedItem() { - String key = ""; - ISelection selection = treeViewer.getSelection(); - if (selection instanceof IStructuredSelection) { - IStructuredSelection structSel = (IStructuredSelection) selection; - if (structSel.getFirstElement() instanceof IKeyTreeNode) { - IKeyTreeNode keyTreeNode = (IKeyTreeNode) structSel - .getFirstElement(); - key = keyTreeNode.getMessageKey(); - } - } + CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( + Display.getDefault().getActiveShell()); - ResourceBundleManager manager = ResourceBundleManager - .getManager(projectName); - EditorUtils.openEditor(site.getPage(), - manager.getRandomFile(resourceBundle), - EditorUtils.RESOURCE_BUNDLE_EDITOR, key); - } + DialogConfiguration config = dialog.new DialogConfiguration(); + config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix + + "." + "[Platzhalter]" + : ""); + config.setPreselectedMessage(""); + config.setPreselectedBundle(getResourceBundle()); + config.setPreselectedLocale(""); + config.setProjectName(projectName); - public void deleteSelectedItems() { - List<String> keys = new ArrayList<String>(); - - IWorkbenchWindow window = PlatformUI.getWorkbench() - .getActiveWorkbenchWindow(); - ISelection selection = window.getActivePage().getSelection(); - if (selection instanceof IStructuredSelection) { - for (Iterator<?> iter = ((IStructuredSelection) selection) - .iterator(); iter.hasNext();) { - Object elem = iter.next(); - if (elem instanceof IKeyTreeNode) { - addKeysToRemove((IKeyTreeNode) elem, keys); - } - } - } + dialog.setDialogConfiguration(config); - try { - ResourceBundleManager manager = ResourceBundleManager - .getManager(projectName); - manager.removeResourceBundleEntry(getResourceBundle(), keys); - } catch (Exception ex) { - Logger.logError(ex); - } - } + if (dialog.open() != InputDialog.OK) + return; + } - private void addKeysToRemove(IKeyTreeNode node, List<String> keys) { - keys.add(node.getMessageKey()); - for (IKeyTreeNode ktn : node.getChildren()) { - addKeysToRemove(ktn, keys); - } + public void setMatchingPrecision(float value) { + matchingPrecision = value; + if (matcher instanceof FuzzyMatcher) { + ((FuzzyMatcher) matcher).setMinimumSimilarity(value); + treeViewer.refresh(); } + } - public void addNewItem(ISelection selection) { - // event.feedback = DND.FEEDBACK_INSERT_BEFORE; - String newKeyPrefix = ""; - - if (selection instanceof IStructuredSelection) { - for (Iterator<?> iter = ((IStructuredSelection) selection) - .iterator(); iter.hasNext();) { - Object elem = iter.next(); - if (elem instanceof IKeyTreeNode) { - newKeyPrefix = ((IKeyTreeNode) elem).getMessageKey(); - break; - } - } - } - - CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( - Display.getDefault().getActiveShell()); - - DialogConfiguration config = dialog.new DialogConfiguration(); - config.setPreselectedKey(newKeyPrefix.trim().length() > 0 ? newKeyPrefix - + "." + "[Platzhalter]" - : ""); - config.setPreselectedMessage(""); - config.setPreselectedBundle(getResourceBundle()); - config.setPreselectedLocale(""); - config.setProjectName(projectName); - - dialog.setDialogConfiguration(config); + public float getMatchingPrecision() { + return matchingPrecision; + } - if (dialog.open() != InputDialog.OK) - return; - } - - public void setMatchingPrecision(float value) { - matchingPrecision = value; - if (matcher instanceof FuzzyMatcher) { - ((FuzzyMatcher) matcher).setMinimumSimilarity(value); - treeViewer.refresh(); - } + private class MessagesEditorListener implements IMessagesEditorListener { + @Override + public void onSave() { + if (resourceBundle != null) { + setTreeStructure(); + } } - public float getMatchingPrecision() { - return matchingPrecision; + @Override + public void onModify() { + if (resourceBundle != null) { + setTreeStructure(); + } } - private class MessagesEditorListener implements IMessagesEditorListener { - @Override - public void onSave() { - if (resourceBundle != null) { - setTreeStructure(); - } - } - - @Override - public void onModify() { - if (resourceBundle != null) { - setTreeStructure(); - } - } - - @Override - public void onResourceChanged(IMessagesBundle bundle) { - // TODO Auto-generated method stub + @Override + public void onResourceChanged(IMessagesBundle bundle) { + // TODO Auto-generated method stub - } } + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/ResourceSelector.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/ResourceSelector.java index dba51f8a..d14feb66 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/ResourceSelector.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/ResourceSelector.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -42,229 +42,229 @@ public class ResourceSelector extends Composite { - public static final int DISPLAY_KEYS = 0; - public static final int DISPLAY_TEXT = 1; + public static final int DISPLAY_KEYS = 0; + public static final int DISPLAY_TEXT = 1; - private Locale displayLocale = null; // default - private int displayMode; - private String resourceBundle; - private String projectName; - private boolean showTree = true; + private Locale displayLocale = null; // default + private int displayMode; + private String resourceBundle; + private String projectName; + private boolean showTree = true; - private TreeViewer viewer; - private TreeColumnLayout basicLayout; - private TreeColumn entries; - private Set<IResourceSelectionListener> listeners = new HashSet<IResourceSelectionListener>(); + private TreeViewer viewer; + private TreeColumnLayout basicLayout; + private TreeColumn entries; + private Set<IResourceSelectionListener> listeners = new HashSet<IResourceSelectionListener>(); - // Viewer model - private TreeType treeType = TreeType.Tree; - private StyledCellLabelProvider labelProvider; + // Viewer model + private TreeType treeType = TreeType.Tree; + private StyledCellLabelProvider labelProvider; - public ResourceSelector(Composite parent, int style) { - super(parent, style); + public ResourceSelector(Composite parent, int style) { + super(parent, style); - initLayout(this); - initViewer(this); - } - - protected void updateContentProvider(IMessagesBundleGroup group) { - // define input of treeviewer - if (!showTree || displayMode == DISPLAY_TEXT) { - treeType = TreeType.Flat; - } + initLayout(this); + initViewer(this); + } - ResourceBundleManager manager = ResourceBundleManager - .getManager(projectName); - - IAbstractKeyTreeModel model = KeyTreeFactory.createModel(manager - .getResourceBundle(resourceBundle)); - ResKeyTreeContentProvider contentProvider = (ResKeyTreeContentProvider) viewer - .getContentProvider(); - contentProvider.setProjectName(manager.getProject().getName()); - contentProvider.setBundleId(resourceBundle); - contentProvider.setTreeType(treeType); - if (viewer.getInput() == null) { - viewer.setUseHashlookup(true); - } - - // viewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS); - org.eclipse.jface.viewers.TreePath[] expandedTreePaths = viewer - .getExpandedTreePaths(); - viewer.setInput(model); - viewer.refresh(); - viewer.setExpandedTreePaths(expandedTreePaths); + protected void updateContentProvider(IMessagesBundleGroup group) { + // define input of treeviewer + if (!showTree || displayMode == DISPLAY_TEXT) { + treeType = TreeType.Flat; } - protected void updateViewer(boolean updateContent) { - IMessagesBundleGroup group = ResourceBundleManager.getManager( - projectName).getResourceBundle(resourceBundle); - - if (group == null) - return; - - if (displayMode == DISPLAY_TEXT) { - labelProvider = new ValueKeyTreeLabelProvider( - group.getMessagesBundle(displayLocale)); - treeType = TreeType.Flat; - ((ResKeyTreeContentProvider) viewer.getContentProvider()) - .setTreeType(treeType); - } else { - labelProvider = new ResKeyTreeLabelProvider(null); - treeType = TreeType.Tree; - ((ResKeyTreeContentProvider) viewer.getContentProvider()) - .setTreeType(treeType); - } - - viewer.setLabelProvider(labelProvider); - if (updateContent) - updateContentProvider(group); + ResourceBundleManager manager = ResourceBundleManager + .getManager(projectName); + + IAbstractKeyTreeModel model = KeyTreeFactory.createModel(manager + .getResourceBundle(resourceBundle)); + ResKeyTreeContentProvider contentProvider = (ResKeyTreeContentProvider) viewer + .getContentProvider(); + contentProvider.setProjectName(manager.getProject().getName()); + contentProvider.setBundleId(resourceBundle); + contentProvider.setTreeType(treeType); + if (viewer.getInput() == null) { + viewer.setUseHashlookup(true); } - protected void initLayout(Composite parent) { - basicLayout = new TreeColumnLayout(); - parent.setLayout(basicLayout); + // viewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS); + org.eclipse.jface.viewers.TreePath[] expandedTreePaths = viewer + .getExpandedTreePaths(); + viewer.setInput(model); + viewer.refresh(); + viewer.setExpandedTreePaths(expandedTreePaths); + } + + protected void updateViewer(boolean updateContent) { + IMessagesBundleGroup group = ResourceBundleManager.getManager( + projectName).getResourceBundle(resourceBundle); + + if (group == null) + return; + + if (displayMode == DISPLAY_TEXT) { + labelProvider = new ValueKeyTreeLabelProvider( + group.getMessagesBundle(displayLocale)); + treeType = TreeType.Flat; + ((ResKeyTreeContentProvider) viewer.getContentProvider()) + .setTreeType(treeType); + } else { + labelProvider = new ResKeyTreeLabelProvider(null); + treeType = TreeType.Tree; + ((ResKeyTreeContentProvider) viewer.getContentProvider()) + .setTreeType(treeType); } - protected void initViewer(Composite parent) { - viewer = new TreeViewer(parent, SWT.BORDER | SWT.SINGLE - | SWT.FULL_SELECTION); - Tree table = viewer.getTree(); - - // Init table-columns - entries = new TreeColumn(table, SWT.NONE); - basicLayout.setColumnData(entries, new ColumnWeightData(1)); - - viewer.setContentProvider(new ResKeyTreeContentProvider()); - viewer.addSelectionChangedListener(new ISelectionChangedListener() { - - @Override - public void selectionChanged(SelectionChangedEvent event) { - ISelection selection = event.getSelection(); - String selectionSummary = ""; - String selectedKey = ""; - ResourceBundleManager manager = ResourceBundleManager - .getManager(projectName); - - if (selection instanceof IStructuredSelection) { - Iterator<IKeyTreeNode> itSel = ((IStructuredSelection) selection) - .iterator(); - if (itSel.hasNext()) { - IKeyTreeNode selItem = itSel.next(); - IMessagesBundleGroup group = manager - .getResourceBundle(resourceBundle); - selectedKey = selItem.getMessageKey(); - - if (group == null) - return; - Iterator<Locale> itLocales = manager - .getProvidedLocales(resourceBundle).iterator(); - while (itLocales.hasNext()) { - Locale l = itLocales.next(); - try { - selectionSummary += (l == null ? ResourceBundleManager.defaultLocaleTag - : l.getDisplayLanguage()) - + ":\n"; - selectionSummary += "\t" - + group.getMessagesBundle(l) - .getMessage( - selItem.getMessageKey()) - .getValue() + "\n"; - } catch (Exception e) { - } - } - } - } - - // construct ResourceSelectionEvent - ResourceSelectionEvent e = new ResourceSelectionEvent( - selectedKey, selectionSummary); - fireSelectionChanged(e); - } - }); - - // we need this to keep the tree expanded - viewer.setComparer(new IElementComparer() { - - @Override - public int hashCode(Object element) { - final int prime = 31; - int result = 1; - result = prime * result - + ((toString() == null) ? 0 : toString().hashCode()); - return result; - } - - @Override - public boolean equals(Object a, Object b) { - if (a == b) { - return true; - } - if (a instanceof IKeyTreeNode && b instanceof IKeyTreeNode) { - IKeyTreeNode nodeA = (IKeyTreeNode) a; - IKeyTreeNode nodeB = (IKeyTreeNode) b; - return nodeA.equals(nodeB); - } - return false; + viewer.setLabelProvider(labelProvider); + if (updateContent) + updateContentProvider(group); + } + + protected void initLayout(Composite parent) { + basicLayout = new TreeColumnLayout(); + parent.setLayout(basicLayout); + } + + protected void initViewer(Composite parent) { + viewer = new TreeViewer(parent, SWT.BORDER | SWT.SINGLE + | SWT.FULL_SELECTION); + Tree table = viewer.getTree(); + + // Init table-columns + entries = new TreeColumn(table, SWT.NONE); + basicLayout.setColumnData(entries, new ColumnWeightData(1)); + + viewer.setContentProvider(new ResKeyTreeContentProvider()); + viewer.addSelectionChangedListener(new ISelectionChangedListener() { + + @Override + public void selectionChanged(SelectionChangedEvent event) { + ISelection selection = event.getSelection(); + String selectionSummary = ""; + String selectedKey = ""; + ResourceBundleManager manager = ResourceBundleManager + .getManager(projectName); + + if (selection instanceof IStructuredSelection) { + Iterator<IKeyTreeNode> itSel = ((IStructuredSelection) selection) + .iterator(); + if (itSel.hasNext()) { + IKeyTreeNode selItem = itSel.next(); + IMessagesBundleGroup group = manager + .getResourceBundle(resourceBundle); + selectedKey = selItem.getMessageKey(); + + if (group == null) + return; + Iterator<Locale> itLocales = manager + .getProvidedLocales(resourceBundle).iterator(); + while (itLocales.hasNext()) { + Locale l = itLocales.next(); + try { + selectionSummary += (l == null ? ResourceBundleManager.defaultLocaleTag + : l.getDisplayLanguage()) + + ":\n"; + selectionSummary += "\t" + + group.getMessagesBundle(l) + .getMessage( + selItem.getMessageKey()) + .getValue() + "\n"; + } catch (Exception e) { + } } - }); - } - - public Locale getDisplayLocale() { - return displayLocale; - } - - public void setDisplayLocale(Locale displayLocale) { - this.displayLocale = displayLocale; - updateViewer(false); - } - - public int getDisplayMode() { - return displayMode; - } - - public void setDisplayMode(int displayMode) { - this.displayMode = displayMode; - updateViewer(true); - } - - public void setResourceBundle(String resourceBundle) { - this.resourceBundle = resourceBundle; - updateViewer(true); - } - - public String getResourceBundle() { - return resourceBundle; - } - - public void addSelectionChangedListener(IResourceSelectionListener l) { - listeners.add(l); - } - - public void removeSelectionChangedListener(IResourceSelectionListener l) { - listeners.remove(l); - } + } + } - private void fireSelectionChanged(ResourceSelectionEvent event) { - Iterator<IResourceSelectionListener> itResList = listeners.iterator(); - while (itResList.hasNext()) { - itResList.next().selectionChanged(event); + // construct ResourceSelectionEvent + ResourceSelectionEvent e = new ResourceSelectionEvent( + selectedKey, selectionSummary); + fireSelectionChanged(e); + } + }); + + // we need this to keep the tree expanded + viewer.setComparer(new IElementComparer() { + + @Override + public int hashCode(Object element) { + final int prime = 31; + int result = 1; + result = prime * result + + ((toString() == null) ? 0 : toString().hashCode()); + return result; + } + + @Override + public boolean equals(Object a, Object b) { + if (a == b) { + return true; } + if (a instanceof IKeyTreeNode && b instanceof IKeyTreeNode) { + IKeyTreeNode nodeA = (IKeyTreeNode) a; + IKeyTreeNode nodeB = (IKeyTreeNode) b; + return nodeA.equals(nodeB); + } + return false; + } + }); + } + + public Locale getDisplayLocale() { + return displayLocale; + } + + public void setDisplayLocale(Locale displayLocale) { + this.displayLocale = displayLocale; + updateViewer(false); + } + + public int getDisplayMode() { + return displayMode; + } + + public void setDisplayMode(int displayMode) { + this.displayMode = displayMode; + updateViewer(true); + } + + public void setResourceBundle(String resourceBundle) { + this.resourceBundle = resourceBundle; + updateViewer(true); + } + + public String getResourceBundle() { + return resourceBundle; + } + + public void addSelectionChangedListener(IResourceSelectionListener l) { + listeners.add(l); + } + + public void removeSelectionChangedListener(IResourceSelectionListener l) { + listeners.remove(l); + } + + private void fireSelectionChanged(ResourceSelectionEvent event) { + Iterator<IResourceSelectionListener> itResList = listeners.iterator(); + while (itResList.hasNext()) { + itResList.next().selectionChanged(event); } + } - public void setProjectName(String projectName) { - this.projectName = projectName; - } + public void setProjectName(String projectName) { + this.projectName = projectName; + } - public boolean isShowTree() { - return showTree; - } + public boolean isShowTree() { + return showTree; + } - public void setShowTree(boolean showTree) { - if (this.showTree != showTree) { - this.showTree = showTree; - this.treeType = showTree ? TreeType.Tree : TreeType.Flat; - updateViewer(false); - } + public void setShowTree(boolean showTree) { + if (this.showTree != showTree) { + this.showTree = showTree; + this.treeType = showTree ? TreeType.Tree : TreeType.Flat; + updateViewer(false); } + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java index 3b58fc8a..586ce13f 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -12,28 +12,28 @@ public class ResourceSelectionEvent { - private String selectionSummary; - private String selectedKey; + private String selectionSummary; + private String selectedKey; - public ResourceSelectionEvent(String selectedKey, String selectionSummary) { - this.setSelectionSummary(selectionSummary); - this.setSelectedKey(selectedKey); - } + public ResourceSelectionEvent(String selectedKey, String selectionSummary) { + this.setSelectionSummary(selectionSummary); + this.setSelectedKey(selectedKey); + } - public void setSelectedKey(String key) { - selectedKey = key; - } + public void setSelectedKey(String key) { + selectedKey = key; + } - public void setSelectionSummary(String selectionSummary) { - this.selectionSummary = selectionSummary; - } + public void setSelectionSummary(String selectionSummary) { + this.selectionSummary = selectionSummary; + } - public String getSelectionSummary() { - return selectionSummary; - } + public String getSelectionSummary() { + return selectionSummary; + } - public String getSelectedKey() { - return selectedKey; - } + public String getSelectedKey() { + return selectedKey; + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java index 419bc725..da604562 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -19,71 +19,71 @@ public class ExactMatcher extends ViewerFilter { - protected final StructuredViewer viewer; - protected String pattern = ""; - protected StringMatcher matcher; + protected final StructuredViewer viewer; + protected String pattern = ""; + protected StringMatcher matcher; - public ExactMatcher(StructuredViewer viewer) { - this.viewer = viewer; - } + public ExactMatcher(StructuredViewer viewer) { + this.viewer = viewer; + } - public String getPattern() { - return pattern; - } + public String getPattern() { + return pattern; + } - public void setPattern(String p) { - boolean filtering = matcher != null; - if (p != null && p.trim().length() > 0) { - pattern = p; - matcher = new StringMatcher("*" + pattern + "*", true, false); - if (!filtering) - viewer.addFilter(this); - else - viewer.refresh(); - } else { - pattern = ""; - matcher = null; - if (filtering) { - viewer.removeFilter(this); - } - } + public void setPattern(String p) { + boolean filtering = matcher != null; + if (p != null && p.trim().length() > 0) { + pattern = p; + matcher = new StringMatcher("*" + pattern + "*", true, false); + if (!filtering) + viewer.addFilter(this); + else + viewer.refresh(); + } else { + pattern = ""; + matcher = null; + if (filtering) { + viewer.removeFilter(this); + } } + } - @Override - public boolean select(Viewer viewer, Object parentElement, Object element) { - IValuedKeyTreeNode vEle = (IValuedKeyTreeNode) element; - FilterInfo filterInfo = new FilterInfo(); - boolean selected = matcher.match(vEle.getMessageKey()); + @Override + public boolean select(Viewer viewer, Object parentElement, Object element) { + IValuedKeyTreeNode vEle = (IValuedKeyTreeNode) element; + FilterInfo filterInfo = new FilterInfo(); + boolean selected = matcher.match(vEle.getMessageKey()); - if (selected) { - int start = -1; - while ((start = vEle.getMessageKey().toLowerCase() - .indexOf(pattern.toLowerCase(), start + 1)) >= 0) { - filterInfo.addKeyOccurrence(start, pattern.length()); - } - filterInfo.setFoundInKey(selected); - filterInfo.setFoundInKey(true); - } else - filterInfo.setFoundInKey(false); + if (selected) { + int start = -1; + while ((start = vEle.getMessageKey().toLowerCase() + .indexOf(pattern.toLowerCase(), start + 1)) >= 0) { + filterInfo.addKeyOccurrence(start, pattern.length()); + } + filterInfo.setFoundInKey(selected); + filterInfo.setFoundInKey(true); + } else + filterInfo.setFoundInKey(false); - // Iterate translations - for (Locale l : vEle.getLocales()) { - String value = vEle.getValue(l); - if (matcher.match(value)) { - filterInfo.addFoundInLocale(l); - filterInfo.addSimilarity(l, 1d); - int start = -1; - while ((start = value.toLowerCase().indexOf( - pattern.toLowerCase(), start + 1)) >= 0) { - filterInfo - .addFoundInLocaleRange(l, start, pattern.length()); - } - selected = true; - } + // Iterate translations + for (Locale l : vEle.getLocales()) { + String value = vEle.getValue(l); + if (matcher.match(value)) { + filterInfo.addFoundInLocale(l); + filterInfo.addSimilarity(l, 1d); + int start = -1; + while ((start = value.toLowerCase().indexOf( + pattern.toLowerCase(), start + 1)) >= 0) { + filterInfo + .addFoundInLocaleRange(l, start, pattern.length()); } - - vEle.setInfo(filterInfo); - return selected; + selected = true; + } } + vEle.setInfo(filterInfo); + return selected; + } + } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FilterInfo.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FilterInfo.java index ee6725be..e53959a3 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FilterInfo.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FilterInfo.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -20,75 +20,75 @@ public class FilterInfo { - private boolean foundInKey; - private List<Locale> foundInLocales = new ArrayList<Locale>(); - private List<Region> keyOccurrences = new ArrayList<Region>(); - private Double keySimilarity; - private Map<Locale, List<Region>> occurrences = new HashMap<Locale, List<Region>>(); - private Map<Locale, Double> localeSimilarity = new HashMap<Locale, Double>(); - - public FilterInfo() { - - } - - public void setKeySimilarity(Double similarity) { - keySimilarity = similarity; - } - - public Double getKeySimilarity() { - return keySimilarity; - } - - public void addSimilarity(Locale l, Double similarity) { - localeSimilarity.put(l, similarity); - } - - public Double getSimilarityLevel(Locale l) { - return localeSimilarity.get(l); - } - - public void setFoundInKey(boolean foundInKey) { - this.foundInKey = foundInKey; - } - - public boolean isFoundInKey() { - return foundInKey; - } - - public void addFoundInLocale(Locale loc) { - foundInLocales.add(loc); - } - - public void removeFoundInLocale(Locale loc) { - foundInLocales.remove(loc); - } - - public void clearFoundInLocale() { - foundInLocales.clear(); - } - - public boolean hasFoundInLocale(Locale l) { - return foundInLocales.contains(l); - } - - public List<Region> getFoundInLocaleRanges(Locale locale) { - List<Region> reg = occurrences.get(locale); - return (reg == null ? new ArrayList<Region>() : reg); - } - - public void addFoundInLocaleRange(Locale locale, int start, int length) { - List<Region> regions = occurrences.get(locale); - if (regions == null) - regions = new ArrayList<Region>(); - regions.add(new Region(start, length)); - occurrences.put(locale, regions); - } - - public List<Region> getKeyOccurrences() { - return keyOccurrences; - } - - public void addKeyOccurrence(int start, int length) { - keyOccurrences.add(new Region(start, length)); - } + private boolean foundInKey; + private List<Locale> foundInLocales = new ArrayList<Locale>(); + private List<Region> keyOccurrences = new ArrayList<Region>(); + private Double keySimilarity; + private Map<Locale, List<Region>> occurrences = new HashMap<Locale, List<Region>>(); + private Map<Locale, Double> localeSimilarity = new HashMap<Locale, Double>(); + + public FilterInfo() { + + } + + public void setKeySimilarity(Double similarity) { + keySimilarity = similarity; + } + + public Double getKeySimilarity() { + return keySimilarity; + } + + public void addSimilarity(Locale l, Double similarity) { + localeSimilarity.put(l, similarity); + } + + public Double getSimilarityLevel(Locale l) { + return localeSimilarity.get(l); + } + + public void setFoundInKey(boolean foundInKey) { + this.foundInKey = foundInKey; + } + + public boolean isFoundInKey() { + return foundInKey; + } + + public void addFoundInLocale(Locale loc) { + foundInLocales.add(loc); + } + + public void removeFoundInLocale(Locale loc) { + foundInLocales.remove(loc); + } + + public void clearFoundInLocale() { + foundInLocales.clear(); + } + + public boolean hasFoundInLocale(Locale l) { + return foundInLocales.contains(l); + } + + public List<Region> getFoundInLocaleRanges(Locale locale) { + List<Region> reg = occurrences.get(locale); + return (reg == null ? new ArrayList<Region>() : reg); + } + + public void addFoundInLocaleRange(Locale locale, int start, int length) { + List<Region> regions = occurrences.get(locale); + if (regions == null) + regions = new ArrayList<Region>(); + regions.add(new Region(start, length)); + occurrences.put(locale, regions); + } + + public List<Region> getKeyOccurrences() { + return keyOccurrences; + } + + public void addKeyOccurrence(int start, int length) { + keyOccurrences.add(new Region(start, length)); + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java index c5302f50..41af9dce 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -20,46 +20,46 @@ public class FuzzyMatcher extends ExactMatcher { - protected ILevenshteinDistanceAnalyzer lvda; - protected float minimumSimilarity = 0.75f; + protected ILevenshteinDistanceAnalyzer lvda; + protected float minimumSimilarity = 0.75f; - public FuzzyMatcher(StructuredViewer viewer) { - super(viewer); - lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer(); - ; - } + public FuzzyMatcher(StructuredViewer viewer) { + super(viewer); + lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer(); + ; + } - public double getMinimumSimilarity() { - return minimumSimilarity; - } + public double getMinimumSimilarity() { + return minimumSimilarity; + } - public void setMinimumSimilarity(float similarity) { - this.minimumSimilarity = similarity; - } + public void setMinimumSimilarity(float similarity) { + this.minimumSimilarity = similarity; + } - @Override - public boolean select(Viewer viewer, Object parentElement, Object element) { - boolean exactMatch = super.select(viewer, parentElement, element); - boolean match = exactMatch; + @Override + public boolean select(Viewer viewer, Object parentElement, Object element) { + boolean exactMatch = super.select(viewer, parentElement, element); + boolean match = exactMatch; - IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element; - FilterInfo filterInfo = (FilterInfo) vkti.getInfo(); + IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element; + FilterInfo filterInfo = (FilterInfo) vkti.getInfo(); - for (Locale l : vkti.getLocales()) { - String value = vkti.getValue(l); - if (filterInfo.hasFoundInLocale(l)) - continue; - double dist = lvda.analyse(value, getPattern()); - if (dist >= minimumSimilarity) { - filterInfo.addFoundInLocale(l); - filterInfo.addSimilarity(l, dist); - match = true; - filterInfo.addFoundInLocaleRange(l, 0, value.length()); - } - } - - vkti.setInfo(filterInfo); - return match; + for (Locale l : vkti.getLocales()) { + String value = vkti.getValue(l); + if (filterInfo.hasFoundInLocale(l)) + continue; + double dist = lvda.analyse(value, getPattern()); + if (dist >= minimumSimilarity) { + filterInfo.addFoundInLocale(l); + filterInfo.addSimilarity(l, dist); + match = true; + filterInfo.addFoundInLocaleRange(l, 0, value.length()); + } } + vkti.setInfo(filterInfo); + return match; + } + } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/StringMatcher.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/StringMatcher.java index 52238ec9..841f0d9d 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/StringMatcher.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/filter/StringMatcher.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -16,481 +16,481 @@ * A string pattern matcher, suppporting "*" and "?" wildcards. */ public class StringMatcher { - protected String fPattern; + protected String fPattern; - protected int fLength; // pattern length + protected int fLength; // pattern length - protected boolean fIgnoreWildCards; + protected boolean fIgnoreWildCards; - protected boolean fIgnoreCase; + protected boolean fIgnoreCase; - protected boolean fHasLeadingStar; + protected boolean fHasLeadingStar; - protected boolean fHasTrailingStar; + protected boolean fHasTrailingStar; - protected String fSegments[]; // the given pattern is split into * separated - // segments + protected String fSegments[]; // the given pattern is split into * separated + // segments - /* boundary value beyond which we don't need to search in the text */ - protected int fBound = 0; + /* boundary value beyond which we don't need to search in the text */ + protected int fBound = 0; - protected static final char fSingleWildCard = '\u0000'; + protected static final char fSingleWildCard = '\u0000'; - public static class Position { - int start; // inclusive + public static class Position { + int start; // inclusive - int end; // exclusive + int end; // exclusive - public Position(int start, int end) { - this.start = start; - this.end = end; - } - - public int getStart() { - return start; - } - - public int getEnd() { - return end; - } + public Position(int start, int end) { + this.start = start; + this.end = end; } - /** - * StringMatcher constructor takes in a String object that is a simple - * pattern which may contain '*' for 0 and many characters and '?' for - * exactly one character. - * - * Literal '*' and '?' characters must be escaped in the pattern e.g., - * "\*" means literal "*", etc. - * - * Escaping any other character (including the escape character itself), - * just results in that character in the pattern. e.g., "\a" means "a" and - * "\\" means "\" - * - * If invoking the StringMatcher with string literals in Java, don't forget - * escape characters are represented by "\\". - * - * @param pattern - * the pattern to match text against - * @param ignoreCase - * if true, case is ignored - * @param ignoreWildCards - * if true, wild cards and their escape sequences are ignored - * (everything is taken literally). - */ - public StringMatcher(String pattern, boolean ignoreCase, - boolean ignoreWildCards) { - if (pattern == null) { - throw new IllegalArgumentException(); - } - fIgnoreCase = ignoreCase; - fIgnoreWildCards = ignoreWildCards; - fPattern = pattern; - fLength = pattern.length(); - - if (fIgnoreWildCards) { - parseNoWildCards(); - } else { - parseWildCards(); - } + public int getStart() { + return start; } - /** - * Find the first occurrence of the pattern between <code>start</code - * )(inclusive) and <code>end</code>(exclusive). - * - * @param text - * the String object to search in - * @param start - * the starting index of the search range, inclusive - * @param end - * the ending index of the search range, exclusive - * @return an <code>StringMatcher.Position</code> object that keeps the - * starting (inclusive) and ending positions (exclusive) of the - * first occurrence of the pattern in the specified range of the - * text; return null if not found or subtext is empty (start==end). - * A pair of zeros is returned if pattern is empty string Note that - * for pattern like "*abc*" with leading and trailing stars, - * position of "abc" is returned. For a pattern like"*??*" in text - * "abcdf", (1,3) is returned - */ - public StringMatcher.Position find(String text, int start, int end) { - if (text == null) { - throw new IllegalArgumentException(); - } + public int getEnd() { + return end; + } + } + + /** + * StringMatcher constructor takes in a String object that is a simple + * pattern which may contain '*' for 0 and many characters and '?' for + * exactly one character. + * + * Literal '*' and '?' characters must be escaped in the pattern e.g., + * "\*" means literal "*", etc. + * + * Escaping any other character (including the escape character itself), + * just results in that character in the pattern. e.g., "\a" means "a" and + * "\\" means "\" + * + * If invoking the StringMatcher with string literals in Java, don't forget + * escape characters are represented by "\\". + * + * @param pattern + * the pattern to match text against + * @param ignoreCase + * if true, case is ignored + * @param ignoreWildCards + * if true, wild cards and their escape sequences are ignored + * (everything is taken literally). + */ + public StringMatcher(String pattern, boolean ignoreCase, + boolean ignoreWildCards) { + if (pattern == null) { + throw new IllegalArgumentException(); + } + fIgnoreCase = ignoreCase; + fIgnoreWildCards = ignoreWildCards; + fPattern = pattern; + fLength = pattern.length(); + + if (fIgnoreWildCards) { + parseNoWildCards(); + } else { + parseWildCards(); + } + } + + /** + * Find the first occurrence of the pattern between <code>start</code + * )(inclusive) and <code>end</code>(exclusive). + * + * @param text + * the String object to search in + * @param start + * the starting index of the search range, inclusive + * @param end + * the ending index of the search range, exclusive + * @return an <code>StringMatcher.Position</code> object that keeps the + * starting (inclusive) and ending positions (exclusive) of the + * first occurrence of the pattern in the specified range of the + * text; return null if not found or subtext is empty (start==end). + * A pair of zeros is returned if pattern is empty string Note that + * for pattern like "*abc*" with leading and trailing stars, + * position of "abc" is returned. For a pattern like"*??*" in text + * "abcdf", (1,3) is returned + */ + public StringMatcher.Position find(String text, int start, int end) { + if (text == null) { + throw new IllegalArgumentException(); + } - int tlen = text.length(); - if (start < 0) { - start = 0; - } - if (end > tlen) { - end = tlen; - } - if (end < 0 || start >= end) { - return null; - } - if (fLength == 0) { - return new Position(start, start); - } - if (fIgnoreWildCards) { - int x = posIn(text, start, end); - if (x < 0) { - return null; - } - return new Position(x, x + fLength); - } + int tlen = text.length(); + if (start < 0) { + start = 0; + } + if (end > tlen) { + end = tlen; + } + if (end < 0 || start >= end) { + return null; + } + if (fLength == 0) { + return new Position(start, start); + } + if (fIgnoreWildCards) { + int x = posIn(text, start, end); + if (x < 0) { + return null; + } + return new Position(x, x + fLength); + } - int segCount = fSegments.length; - if (segCount == 0) { - return new Position(start, end); - } + int segCount = fSegments.length; + if (segCount == 0) { + return new Position(start, end); + } - int curPos = start; - int matchStart = -1; - int i; - for (i = 0; i < segCount && curPos < end; ++i) { - String current = fSegments[i]; - int nextMatch = regExpPosIn(text, curPos, end, current); - if (nextMatch < 0) { - return null; - } - if (i == 0) { - matchStart = nextMatch; - } - curPos = nextMatch + current.length(); - } - if (i < segCount) { - return null; - } - return new Position(matchStart, curPos); - } - - /** - * match the given <code>text</code> with the pattern - * - * @return true if matched otherwise false - * @param text - * a String object - */ - public boolean match(String text) { - if (text == null) { - return false; - } - return match(text, 0, text.length()); - } - - /** - * Given the starting (inclusive) and the ending (exclusive) positions in - * the <code>text</code>, determine if the given substring matches with - * aPattern - * - * @return true if the specified portion of the text matches the pattern - * @param text - * a String object that contains the substring to match - * @param start - * marks the starting position (inclusive) of the substring - * @param end - * marks the ending index (exclusive) of the substring - */ - public boolean match(String text, int start, int end) { - if (null == text) { - throw new IllegalArgumentException(); - } + int curPos = start; + int matchStart = -1; + int i; + for (i = 0; i < segCount && curPos < end; ++i) { + String current = fSegments[i]; + int nextMatch = regExpPosIn(text, curPos, end, current); + if (nextMatch < 0) { + return null; + } + if (i == 0) { + matchStart = nextMatch; + } + curPos = nextMatch + current.length(); + } + if (i < segCount) { + return null; + } + return new Position(matchStart, curPos); + } + + /** + * match the given <code>text</code> with the pattern + * + * @return true if matched otherwise false + * @param text + * a String object + */ + public boolean match(String text) { + if (text == null) { + return false; + } + return match(text, 0, text.length()); + } + + /** + * Given the starting (inclusive) and the ending (exclusive) positions in + * the <code>text</code>, determine if the given substring matches with + * aPattern + * + * @return true if the specified portion of the text matches the pattern + * @param text + * a String object that contains the substring to match + * @param start + * marks the starting position (inclusive) of the substring + * @param end + * marks the ending index (exclusive) of the substring + */ + public boolean match(String text, int start, int end) { + if (null == text) { + throw new IllegalArgumentException(); + } - if (start > end) { - return false; - } + if (start > end) { + return false; + } - if (fIgnoreWildCards) { - return (end - start == fLength) - && fPattern.regionMatches(fIgnoreCase, 0, text, start, - fLength); - } - int segCount = fSegments.length; - if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) { - return true; - } - if (start == end) { - return fLength == 0; - } - if (fLength == 0) { - return start == end; - } + if (fIgnoreWildCards) { + return (end - start == fLength) + && fPattern.regionMatches(fIgnoreCase, 0, text, start, + fLength); + } + int segCount = fSegments.length; + if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) { + return true; + } + if (start == end) { + return fLength == 0; + } + if (fLength == 0) { + return start == end; + } - int tlen = text.length(); - if (start < 0) { - start = 0; - } - if (end > tlen) { - end = tlen; - } + int tlen = text.length(); + if (start < 0) { + start = 0; + } + if (end > tlen) { + end = tlen; + } - int tCurPos = start; - int bound = end - fBound; - if (bound < 0) { - return false; - } - int i = 0; - String current = fSegments[i]; - int segLength = current.length(); - - /* process first segment */ - if (!fHasLeadingStar) { - if (!regExpRegionMatches(text, start, current, 0, segLength)) { - return false; - } else { - ++i; - tCurPos = tCurPos + segLength; - } - } - if ((fSegments.length == 1) && (!fHasLeadingStar) - && (!fHasTrailingStar)) { - // only one segment to match, no wildcards specified - return tCurPos == end; - } - /* process middle segments */ - while (i < segCount) { - current = fSegments[i]; - int currentMatch; - int k = current.indexOf(fSingleWildCard); - if (k < 0) { - currentMatch = textPosIn(text, tCurPos, end, current); - if (currentMatch < 0) { - return false; - } - } else { - currentMatch = regExpPosIn(text, tCurPos, end, current); - if (currentMatch < 0) { - return false; - } - } - tCurPos = currentMatch + current.length(); - i++; - } + int tCurPos = start; + int bound = end - fBound; + if (bound < 0) { + return false; + } + int i = 0; + String current = fSegments[i]; + int segLength = current.length(); + + /* process first segment */ + if (!fHasLeadingStar) { + if (!regExpRegionMatches(text, start, current, 0, segLength)) { + return false; + } else { + ++i; + tCurPos = tCurPos + segLength; + } + } + if ((fSegments.length == 1) && (!fHasLeadingStar) + && (!fHasTrailingStar)) { + // only one segment to match, no wildcards specified + return tCurPos == end; + } + /* process middle segments */ + while (i < segCount) { + current = fSegments[i]; + int currentMatch; + int k = current.indexOf(fSingleWildCard); + if (k < 0) { + currentMatch = textPosIn(text, tCurPos, end, current); + if (currentMatch < 0) { + return false; + } + } else { + currentMatch = regExpPosIn(text, tCurPos, end, current); + if (currentMatch < 0) { + return false; + } + } + tCurPos = currentMatch + current.length(); + i++; + } - /* process final segment */ - if (!fHasTrailingStar && tCurPos != end) { - int clen = current.length(); - return regExpRegionMatches(text, end - clen, current, 0, clen); - } - return i == segCount; - } - - /** - * This method parses the given pattern into segments seperated by wildcard - * '*' characters. Since wildcards are not being used in this case, the - * pattern consists of a single segment. - */ - private void parseNoWildCards() { - fSegments = new String[1]; - fSegments[0] = fPattern; - fBound = fLength; - } - - /** - * Parses the given pattern into segments seperated by wildcard '*' - * characters. - * - * @param p - * , a String object that is a simple regular expression with '*' - * and/or '?' - */ - private void parseWildCards() { - if (fPattern.startsWith("*")) { //$NON-NLS-1$ - fHasLeadingStar = true; - } - if (fPattern.endsWith("*")) {//$NON-NLS-1$ - /* make sure it's not an escaped wildcard */ - if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') { - fHasTrailingStar = true; - } - } + /* process final segment */ + if (!fHasTrailingStar && tCurPos != end) { + int clen = current.length(); + return regExpRegionMatches(text, end - clen, current, 0, clen); + } + return i == segCount; + } + + /** + * This method parses the given pattern into segments seperated by wildcard + * '*' characters. Since wildcards are not being used in this case, the + * pattern consists of a single segment. + */ + private void parseNoWildCards() { + fSegments = new String[1]; + fSegments[0] = fPattern; + fBound = fLength; + } + + /** + * Parses the given pattern into segments seperated by wildcard '*' + * characters. + * + * @param p + * , a String object that is a simple regular expression with '*' + * and/or '?' + */ + private void parseWildCards() { + if (fPattern.startsWith("*")) { //$NON-NLS-1$ + fHasLeadingStar = true; + } + if (fPattern.endsWith("*")) {//$NON-NLS-1$ + /* make sure it's not an escaped wildcard */ + if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') { + fHasTrailingStar = true; + } + } - Vector temp = new Vector(); - - int pos = 0; - StringBuffer buf = new StringBuffer(); - while (pos < fLength) { - char c = fPattern.charAt(pos++); - switch (c) { - case '\\': - if (pos >= fLength) { - buf.append(c); - } else { - char next = fPattern.charAt(pos++); - /* if it's an escape sequence */ - if (next == '*' || next == '?' || next == '\\') { - buf.append(next); - } else { - /* not an escape sequence, just insert literally */ - buf.append(c); - buf.append(next); - } - } - break; - case '*': - if (buf.length() > 0) { - /* new segment */ - temp.addElement(buf.toString()); - fBound += buf.length(); - buf.setLength(0); - } - break; - case '?': - /* append special character representing single match wildcard */ - buf.append(fSingleWildCard); - break; - default: - buf.append(c); - } - } + Vector temp = new Vector(); - /* add last buffer to segment list */ + int pos = 0; + StringBuffer buf = new StringBuffer(); + while (pos < fLength) { + char c = fPattern.charAt(pos++); + switch (c) { + case '\\': + if (pos >= fLength) { + buf.append(c); + } else { + char next = fPattern.charAt(pos++); + /* if it's an escape sequence */ + if (next == '*' || next == '?' || next == '\\') { + buf.append(next); + } else { + /* not an escape sequence, just insert literally */ + buf.append(c); + buf.append(next); + } + } + break; + case '*': if (buf.length() > 0) { - temp.addElement(buf.toString()); - fBound += buf.length(); - } - - fSegments = new String[temp.size()]; - temp.copyInto(fSegments); - } - - /** - * @param text - * a string which contains no wildcard - * @param start - * the starting index in the text for search, inclusive - * @param end - * the stopping point of search, exclusive - * @return the starting index in the text of the pattern , or -1 if not - * found - */ - protected int posIn(String text, int start, int end) {// no wild card in - // pattern - int max = end - fLength; - - if (!fIgnoreCase) { - int i = text.indexOf(fPattern, start); - if (i == -1 || i > max) { - return -1; - } - return i; - } - - for (int i = start; i <= max; ++i) { - if (text.regionMatches(true, i, fPattern, 0, fLength)) { - return i; - } - } + /* new segment */ + temp.addElement(buf.toString()); + fBound += buf.length(); + buf.setLength(0); + } + break; + case '?': + /* append special character representing single match wildcard */ + buf.append(fSingleWildCard); + break; + default: + buf.append(c); + } + } - return -1; + /* add last buffer to segment list */ + if (buf.length() > 0) { + temp.addElement(buf.toString()); + fBound += buf.length(); } - /** - * @param text - * a simple regular expression that may only contain '?'(s) - * @param start - * the starting index in the text for search, inclusive - * @param end - * the stopping point of search, exclusive - * @param p - * a simple regular expression that may contains '?' - * @return the starting index in the text of the pattern , or -1 if not - * found - */ - protected int regExpPosIn(String text, int start, int end, String p) { - int plen = p.length(); - - int max = end - plen; - for (int i = start; i <= max; ++i) { - if (regExpRegionMatches(text, i, p, 0, plen)) { - return i; - } - } + fSegments = new String[temp.size()]; + temp.copyInto(fSegments); + } + + /** + * @param text + * a string which contains no wildcard + * @param start + * the starting index in the text for search, inclusive + * @param end + * the stopping point of search, exclusive + * @return the starting index in the text of the pattern , or -1 if not + * found + */ + protected int posIn(String text, int start, int end) {// no wild card in + // pattern + int max = end - fLength; + + if (!fIgnoreCase) { + int i = text.indexOf(fPattern, start); + if (i == -1 || i > max) { return -1; + } + return i; } - /** - * - * @return boolean - * @param text - * a String to match - * @param start - * int that indicates the starting index of match, inclusive - * @param end - * </code> int that indicates the ending index of match, - * exclusive - * @param p - * String, String, a simple regular expression that may contain - * '?' - * @param ignoreCase - * boolean indicating wether code>p</code> is case sensitive - */ - protected boolean regExpRegionMatches(String text, int tStart, String p, - int pStart, int plen) { - while (plen-- > 0) { - char tchar = text.charAt(tStart++); - char pchar = p.charAt(pStart++); - - /* process wild cards */ - if (!fIgnoreWildCards) { - /* skip single wild cards */ - if (pchar == fSingleWildCard) { - continue; - } - } - if (pchar == tchar) { - continue; - } - if (fIgnoreCase) { - if (Character.toUpperCase(tchar) == Character - .toUpperCase(pchar)) { - continue; - } - // comparing after converting to upper case doesn't handle all - // cases; - // also compare after converting to lower case - if (Character.toLowerCase(tchar) == Character - .toLowerCase(pchar)) { - continue; - } - } - return false; - } - return true; - } - - /** - * @param text - * the string to match - * @param start - * the starting index in the text for search, inclusive - * @param end - * the stopping point of search, exclusive - * @param p - * a pattern string that has no wildcard - * @return the starting index in the text of the pattern , or -1 if not - * found - */ - protected int textPosIn(String text, int start, int end, String p) { - - int plen = p.length(); - int max = end - plen; - - if (!fIgnoreCase) { - int i = text.indexOf(p, start); - if (i == -1 || i > max) { - return -1; - } - return i; - } - - for (int i = start; i <= max; ++i) { - if (text.regionMatches(true, i, p, 0, plen)) { - return i; - } - } + for (int i = start; i <= max; ++i) { + if (text.regionMatches(true, i, fPattern, 0, fLength)) { + return i; + } + } + return -1; + } + + /** + * @param text + * a simple regular expression that may only contain '?'(s) + * @param start + * the starting index in the text for search, inclusive + * @param end + * the stopping point of search, exclusive + * @param p + * a simple regular expression that may contains '?' + * @return the starting index in the text of the pattern , or -1 if not + * found + */ + protected int regExpPosIn(String text, int start, int end, String p) { + int plen = p.length(); + + int max = end - plen; + for (int i = start; i <= max; ++i) { + if (regExpRegionMatches(text, i, p, 0, plen)) { + return i; + } + } + return -1; + } + + /** + * + * @return boolean + * @param text + * a String to match + * @param start + * int that indicates the starting index of match, inclusive + * @param end + * </code> int that indicates the ending index of match, + * exclusive + * @param p + * String, String, a simple regular expression that may contain + * '?' + * @param ignoreCase + * boolean indicating wether code>p</code> is case sensitive + */ + protected boolean regExpRegionMatches(String text, int tStart, String p, + int pStart, int plen) { + while (plen-- > 0) { + char tchar = text.charAt(tStart++); + char pchar = p.charAt(pStart++); + + /* process wild cards */ + if (!fIgnoreWildCards) { + /* skip single wild cards */ + if (pchar == fSingleWildCard) { + continue; + } + } + if (pchar == tchar) { + continue; + } + if (fIgnoreCase) { + if (Character.toUpperCase(tchar) == Character + .toUpperCase(pchar)) { + continue; + } + // comparing after converting to upper case doesn't handle all + // cases; + // also compare after converting to lower case + if (Character.toLowerCase(tchar) == Character + .toLowerCase(pchar)) { + continue; + } + } + return false; + } + return true; + } + + /** + * @param text + * the string to match + * @param start + * the starting index in the text for search, inclusive + * @param end + * the stopping point of search, exclusive + * @param p + * a pattern string that has no wildcard + * @return the starting index in the text of the pattern , or -1 if not + * found + */ + protected int textPosIn(String text, int start, int end, String p) { + + int plen = p.length(); + int max = end - plen; + + if (!fIgnoreCase) { + int i = text.indexOf(p, start); + if (i == -1 || i > max) { return -1; + } + return i; } + + for (int i = start; i <= max; ++i) { + if (text.regionMatches(true, i, p, 0, plen)) { + return i; + } + } + + return -1; + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java index 3c44d65e..4d8de8ab 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -14,6 +14,6 @@ public interface IResourceSelectionListener { - public void selectionChanged(ResourceSelectionEvent e); + public void selectionChanged(ResourceSelectionEvent e); } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java index 4b212be3..876dc352 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java index 0daf1c94..a2dc85a3 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -32,199 +32,199 @@ public class ResKeyTreeContentProvider implements ITreeContentProvider { - private IAbstractKeyTreeModel keyTreeModel; - private Viewer viewer; - - private TreeType treeType = TreeType.Tree; - - /** Viewer this provided act upon. */ - protected TreeViewer treeViewer; - - private List<Locale> locales; - private String bundleId; - private String projectName; - - public ResKeyTreeContentProvider(List<Locale> locales, String projectName, - String bundleId, TreeType treeType) { - this.locales = locales; - this.projectName = projectName; - this.bundleId = bundleId; - this.treeType = treeType; - } - - public void setBundleId(String bundleId) { - this.bundleId = bundleId; - } - - public void setProjectName(String projectName) { - this.projectName = projectName; - } - - public ResKeyTreeContentProvider() { - locales = new ArrayList<Locale>(); - } - - public void setLocales(List<Locale> locales) { - this.locales = locales; - } - - @Override - public Object[] getChildren(Object parentElement) { - IKeyTreeNode parentNode = (IKeyTreeNode) parentElement; - switch (treeType) { - case Tree: - return convertKTItoVKTI(keyTreeModel.getChildren(parentNode)); - case Flat: - return new IKeyTreeNode[0]; - default: - // Should not happen - return new IKeyTreeNode[0]; + private IAbstractKeyTreeModel keyTreeModel; + private Viewer viewer; + + private TreeType treeType = TreeType.Tree; + + /** Viewer this provided act upon. */ + protected TreeViewer treeViewer; + + private List<Locale> locales; + private String bundleId; + private String projectName; + + public ResKeyTreeContentProvider(List<Locale> locales, String projectName, + String bundleId, TreeType treeType) { + this.locales = locales; + this.projectName = projectName; + this.bundleId = bundleId; + this.treeType = treeType; + } + + public void setBundleId(String bundleId) { + this.bundleId = bundleId; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public ResKeyTreeContentProvider() { + locales = new ArrayList<Locale>(); + } + + public void setLocales(List<Locale> locales) { + this.locales = locales; + } + + @Override + public Object[] getChildren(Object parentElement) { + IKeyTreeNode parentNode = (IKeyTreeNode) parentElement; + switch (treeType) { + case Tree: + return convertKTItoVKTI(keyTreeModel.getChildren(parentNode)); + case Flat: + return new IKeyTreeNode[0]; + default: + // Should not happen + return new IKeyTreeNode[0]; + } + } + + protected Object[] convertKTItoVKTI(Object[] children) { + Collection<IValuedKeyTreeNode> items = new ArrayList<IValuedKeyTreeNode>(); + IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance( + this.projectName).getMessagesBundleGroup(this.bundleId); + + for (Object o : children) { + if (o instanceof IValuedKeyTreeNode) + items.add((IValuedKeyTreeNode) o); + else { + IKeyTreeNode kti = (IKeyTreeNode) o; + IValuedKeyTreeNode vkti = KeyTreeFactory.createKeyTree( + kti.getParent(), kti.getName(), kti.getMessageKey(), + messagesBundleGroup); + + for (IKeyTreeNode k : kti.getChildren()) { + vkti.addChild(k); } - } - protected Object[] convertKTItoVKTI(Object[] children) { - Collection<IValuedKeyTreeNode> items = new ArrayList<IValuedKeyTreeNode>(); - IMessagesBundleGroup messagesBundleGroup = RBManager.getInstance( - this.projectName).getMessagesBundleGroup(this.bundleId); - - for (Object o : children) { - if (o instanceof IValuedKeyTreeNode) - items.add((IValuedKeyTreeNode) o); - else { - IKeyTreeNode kti = (IKeyTreeNode) o; - IValuedKeyTreeNode vkti = KeyTreeFactory.createKeyTree( - kti.getParent(), kti.getName(), kti.getMessageKey(), - messagesBundleGroup); - - for (IKeyTreeNode k : kti.getChildren()) { - vkti.addChild(k); - } - - // init translations - for (Locale l : locales) { - try { - IMessage message = messagesBundleGroup - .getMessagesBundle(l).getMessage( - kti.getMessageKey()); - if (message != null) { - vkti.addValue(l, message.getValue()); - } - } catch (Exception e) { - } - } - items.add(vkti); + // init translations + for (Locale l : locales) { + try { + IMessage message = messagesBundleGroup + .getMessagesBundle(l).getMessage( + kti.getMessageKey()); + if (message != null) { + vkti.addValue(l, message.getValue()); } + } catch (Exception e) { + } } - - return items.toArray(); - } - - @Override - public Object[] getElements(Object inputElement) { - switch (treeType) { - case Tree: - return convertKTItoVKTI(keyTreeModel.getRootNodes()); - case Flat: - final Collection<IKeyTreeNode> actualKeys = new ArrayList<IKeyTreeNode>(); - IKeyTreeVisitor visitor = new IKeyTreeVisitor() { - public void visitKeyTreeNode(IKeyTreeNode node) { - if (node.isUsedAsKey()) { - actualKeys.add(node); - } - } - }; - keyTreeModel.accept(visitor, keyTreeModel.getRootNode()); - - return actualKeys.toArray(); - default: - // Should not happen - return new IKeyTreeNode[0]; - } - } - - @Override - public Object getParent(Object element) { - IKeyTreeNode node = (IKeyTreeNode) element; - switch (treeType) { - case Tree: - return keyTreeModel.getParent(node); - case Flat: - return keyTreeModel; - default: - // Should not happen - return null; - } - } - - /** - * @see ITreeContentProvider#hasChildren(Object) - */ - public boolean hasChildren(Object element) { - switch (treeType) { - case Tree: - return keyTreeModel.getChildren((IKeyTreeNode) element).length > 0; - case Flat: - return false; - default: - // Should not happen - return false; - } - } - - public int countChildren(Object element) { - - if (element instanceof IKeyTreeNode) { - return ((IKeyTreeNode) element).getChildren().length; - } else if (element instanceof IValuedKeyTreeNode) { - return ((IValuedKeyTreeNode) element).getChildren().length; - } else { - System.out.println("wait a minute"); - return 1; + items.add(vkti); + } + } + + return items.toArray(); + } + + @Override + public Object[] getElements(Object inputElement) { + switch (treeType) { + case Tree: + return convertKTItoVKTI(keyTreeModel.getRootNodes()); + case Flat: + final Collection<IKeyTreeNode> actualKeys = new ArrayList<IKeyTreeNode>(); + IKeyTreeVisitor visitor = new IKeyTreeVisitor() { + public void visitKeyTreeNode(IKeyTreeNode node) { + if (node.isUsedAsKey()) { + actualKeys.add(node); + } } - } - - /** - * Gets the selected key tree item. - * - * @return key tree item - */ - private IKeyTreeNode getTreeSelection() { - IStructuredSelection selection = (IStructuredSelection) treeViewer - .getSelection(); - return ((IKeyTreeNode) selection.getFirstElement()); - } - - @Override - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - this.viewer = (TreeViewer) viewer; - this.keyTreeModel = (IAbstractKeyTreeModel) newInput; - } - - public IMessagesBundleGroup getBundle() { - return RBManager.getInstance(projectName).getMessagesBundleGroup( - this.bundleId); - } - - public String getBundleId() { - return bundleId; - } - - @Override - public void dispose() { - // TODO Auto-generated method stub - - } - - public TreeType getTreeType() { - return treeType; - } - - public void setTreeType(TreeType treeType) { - if (this.treeType != treeType) { - this.treeType = treeType; - if (viewer != null) { - viewer.refresh(); - } - } - } + }; + keyTreeModel.accept(visitor, keyTreeModel.getRootNode()); + + return actualKeys.toArray(); + default: + // Should not happen + return new IKeyTreeNode[0]; + } + } + + @Override + public Object getParent(Object element) { + IKeyTreeNode node = (IKeyTreeNode) element; + switch (treeType) { + case Tree: + return keyTreeModel.getParent(node); + case Flat: + return keyTreeModel; + default: + // Should not happen + return null; + } + } + + /** + * @see ITreeContentProvider#hasChildren(Object) + */ + public boolean hasChildren(Object element) { + switch (treeType) { + case Tree: + return keyTreeModel.getChildren((IKeyTreeNode) element).length > 0; + case Flat: + return false; + default: + // Should not happen + return false; + } + } + + public int countChildren(Object element) { + + if (element instanceof IKeyTreeNode) { + return ((IKeyTreeNode) element).getChildren().length; + } else if (element instanceof IValuedKeyTreeNode) { + return ((IValuedKeyTreeNode) element).getChildren().length; + } else { + System.out.println("wait a minute"); + return 1; + } + } + + /** + * Gets the selected key tree item. + * + * @return key tree item + */ + private IKeyTreeNode getTreeSelection() { + IStructuredSelection selection = (IStructuredSelection) treeViewer + .getSelection(); + return ((IKeyTreeNode) selection.getFirstElement()); + } + + @Override + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + this.viewer = (TreeViewer) viewer; + this.keyTreeModel = (IAbstractKeyTreeModel) newInput; + } + + public IMessagesBundleGroup getBundle() { + return RBManager.getInstance(projectName).getMessagesBundleGroup( + this.bundleId); + } + + public String getBundleId() { + return bundleId; + } + + @Override + public void dispose() { + // TODO Auto-generated method stub + + } + + public TreeType getTreeType() { + return treeType; + } + + public void setTreeType(TreeType treeType) { + if (this.treeType != treeType) { + this.treeType = treeType; + if (viewer != null) { + viewer.refresh(); + } + } + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java index fc9317e7..9b741916 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -35,158 +35,157 @@ public class ResKeyTreeLabelProvider extends KeyTreeLabelProvider { - private List<Locale> locales; - private boolean searchEnabled = false; - - /*** COLORS ***/ - private Color gray = FontUtils.getSystemColor(SWT.COLOR_GRAY); - private Color black = FontUtils.getSystemColor(SWT.COLOR_BLACK); - private Color info_color = FontUtils.getSystemColor(SWT.COLOR_YELLOW); + private List<Locale> locales; + private boolean searchEnabled = false; + + /*** COLORS ***/ + private Color gray = FontUtils.getSystemColor(SWT.COLOR_GRAY); + private Color black = FontUtils.getSystemColor(SWT.COLOR_BLACK); + private Color info_color = FontUtils.getSystemColor(SWT.COLOR_YELLOW); + + public ResKeyTreeLabelProvider(List<Locale> locales) { + this.locales = locales; + } + + /** + * {@inheritDoc} + */ + @Override + public Image getColumnImage(Object element, int columnIndex) { + if (columnIndex == 0) { + IKeyTreeNode kti = (IKeyTreeNode) element; + IMessage[] be = kti.getMessagesBundleGroup().getMessages( + kti.getMessageKey()); + boolean incomplete = false; + + if (be.length != kti.getMessagesBundleGroup() + .getMessagesBundleCount()) + incomplete = true; + else { + for (IMessage b : be) { + if (b.getValue() == null + || b.getValue().trim().length() == 0) { + incomplete = true; + break; + } + } + } - public ResKeyTreeLabelProvider(List<Locale> locales) { - this.locales = locales; + if (incomplete) { + return ImageUtils.getImage(ImageUtils.ICON_RESOURCE_INCOMPLETE); + } else { + return ImageUtils.getImage(ImageUtils.ICON_RESOURCE); + } + } + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getColumnText(Object element, int columnIndex) { + if (columnIndex == 0) { + return ((IKeyTreeNode) element).getName(); } - /** - * {@inheritDoc} - */ - @Override - public Image getColumnImage(Object element, int columnIndex) { - if (columnIndex == 0) { - IKeyTreeNode kti = (IKeyTreeNode) element; - IMessage[] be = kti.getMessagesBundleGroup().getMessages( - kti.getMessageKey()); - boolean incomplete = false; - - if (be.length != kti.getMessagesBundleGroup() - .getMessagesBundleCount()) - incomplete = true; - else { - for (IMessage b : be) { - if (b.getValue() == null - || b.getValue().trim().length() == 0) { - incomplete = true; - break; - } - } - } - - if (incomplete) { - return ImageUtils.getImage(ImageUtils.ICON_RESOURCE_INCOMPLETE); - } else { - return ImageUtils.getImage(ImageUtils.ICON_RESOURCE); - } - } - return null; + if (columnIndex <= locales.size()) { + IValuedKeyTreeNode item = (IValuedKeyTreeNode) element; + String entry = item.getValue(locales.get(columnIndex - 1)); + if (entry != null) { + return entry; + } } + return ""; + } - /** - * {@inheritDoc} - */ - @Override - public String getColumnText(Object element, int columnIndex) { - if (columnIndex == 0) { - return ((IKeyTreeNode) element).getName(); - } + public void setSearchEnabled(boolean enabled) { + this.searchEnabled = enabled; + } - if (columnIndex <= locales.size()) { - IValuedKeyTreeNode item = (IValuedKeyTreeNode) element; - String entry = item.getValue(locales.get(columnIndex - 1)); - if (entry != null) { - return entry; - } - } - return ""; - } + public boolean isSearchEnabled() { + return this.searchEnabled; + } - public void setSearchEnabled(boolean enabled) { - this.searchEnabled = enabled; - } + public void setLocales(List<Locale> visibleLocales) { + locales = visibleLocales; + } - public boolean isSearchEnabled() { - return this.searchEnabled; - } + protected boolean isMatchingToPattern(Object element, int columnIndex) { + boolean matching = false; - public void setLocales(List<Locale> visibleLocales) { - locales = visibleLocales; - } + if (element instanceof IValuedKeyTreeNode) { + IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element; - protected boolean isMatchingToPattern(Object element, int columnIndex) { - boolean matching = false; + if (vkti.getInfo() == null) + return false; - if (element instanceof IValuedKeyTreeNode) { - IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element; + FilterInfo filterInfo = (FilterInfo) vkti.getInfo(); - if (vkti.getInfo() == null) - return false; + if (columnIndex == 0) { + matching = filterInfo.isFoundInKey(); + } else { + matching = filterInfo.hasFoundInLocale(locales + .get(columnIndex - 1)); + } + } - FilterInfo filterInfo = (FilterInfo) vkti.getInfo(); + return matching; + } - if (columnIndex == 0) { - matching = filterInfo.isFoundInKey(); - } else { - matching = filterInfo.hasFoundInLocale(locales - .get(columnIndex - 1)); - } - } + protected boolean isSearchEnabled(Object element) { + return (element instanceof IValuedKeyTreeNode && searchEnabled); + } - return matching; - } + public void updateTreeViewer(TreeViewer treeViewer) { - protected boolean isSearchEnabled(Object element) { - return (element instanceof IValuedKeyTreeNode && searchEnabled); - } + for (TreeItem item : treeViewer.getTree().getItems()) { + Rectangle bounds = item.getBounds(); + ViewerCell cell = treeViewer.getCell(new Point(bounds.x, bounds.y)); + ViewerRow viewerRow = cell.getViewerRow(); - public void updateTreeViewer(TreeViewer treeViewer) { - - for (TreeItem item : treeViewer.getTree().getItems()) { - Rectangle bounds = item.getBounds(); - ViewerCell cell = treeViewer.getCell(new Point(bounds.x, bounds.y)); - ViewerRow viewerRow = cell.getViewerRow(); - - for (int i = 0 ; i < viewerRow.getColumnCount() ; i++) { - updateCell(viewerRow.getCell(i)); - } - } + for (int i = 0; i < viewerRow.getColumnCount(); i++) { + updateCell(viewerRow.getCell(i)); + } } - - private void updateCell(ViewerCell cell) { - Object element = cell.getElement(); - int columnIndex = cell.getColumnIndex(); - - - if (isSearchEnabled(element)) { - if (isMatchingToPattern(element, columnIndex)) { - List<StyleRange> styleRanges = new ArrayList<StyleRange>(); - FilterInfo filterInfo = (FilterInfo) ((IValuedKeyTreeNode) element) - .getInfo(); - - if (columnIndex > 0) { - for (Region reg : filterInfo.getFoundInLocaleRanges(locales - .get(columnIndex - 1))) { - styleRanges.add(new StyleRange(reg.getOffset(), reg - .getLength(), black, info_color, SWT.BOLD)); - } - } else { - // check if the pattern has been found within the key - // section - if (filterInfo.isFoundInKey()) { - for (Region reg : filterInfo.getKeyOccurrences()) { - StyleRange sr = new StyleRange(reg.getOffset(), - reg.getLength(), black, info_color, - SWT.BOLD); - styleRanges.add(sr); - } - } - } - cell.setStyleRanges(styleRanges - .toArray(new StyleRange[styleRanges.size()])); - } else { - cell.setForeground(gray); - } - } else if (columnIndex == 0) { - super.update(cell); + } + + private void updateCell(ViewerCell cell) { + Object element = cell.getElement(); + int columnIndex = cell.getColumnIndex(); + + if (isSearchEnabled(element)) { + if (isMatchingToPattern(element, columnIndex)) { + List<StyleRange> styleRanges = new ArrayList<StyleRange>(); + FilterInfo filterInfo = (FilterInfo) ((IValuedKeyTreeNode) element) + .getInfo(); + + if (columnIndex > 0) { + for (Region reg : filterInfo.getFoundInLocaleRanges(locales + .get(columnIndex - 1))) { + styleRanges.add(new StyleRange(reg.getOffset(), reg + .getLength(), black, info_color, SWT.BOLD)); + } + } else { + // check if the pattern has been found within the key + // section + if (filterInfo.isFoundInKey()) { + for (Region reg : filterInfo.getKeyOccurrences()) { + StyleRange sr = new StyleRange(reg.getOffset(), + reg.getLength(), black, info_color, + SWT.BOLD); + styleRanges.add(sr); + } + } } + cell.setStyleRanges(styleRanges + .toArray(new StyleRange[styleRanges.size()])); + } else { + cell.setForeground(gray); + } + } else if (columnIndex == 0) { + super.update(cell); } + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java index ff4491cd..4efa9f26 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -20,62 +20,62 @@ import org.eclipse.swt.graphics.Image; public class ValueKeyTreeLabelProvider extends KeyTreeLabelProvider implements - ITableColorProvider, ITableFontProvider { + ITableColorProvider, ITableFontProvider { - private IMessagesBundle locale; - - public ValueKeyTreeLabelProvider(IMessagesBundle iBundle) { - this.locale = iBundle; - } + private IMessagesBundle locale; - /** - * {@inheritDoc} - */ - @Override - public Image getColumnImage(Object element, int columnIndex) { - return null; - } + public ValueKeyTreeLabelProvider(IMessagesBundle iBundle) { + this.locale = iBundle; + } - /** - * {@inheritDoc} - */ - @Override - public String getColumnText(Object element, int columnIndex) { - try { - IKeyTreeNode item = (IKeyTreeNode) element; - IMessage entry = locale.getMessage(item.getMessageKey()); - if (entry != null) { - String value = entry.getValue(); - if (value.length() > 40) - value = value.substring(0, 39) + "..."; - } - } catch (Exception e) { - } - return ""; - } + /** + * {@inheritDoc} + */ + @Override + public Image getColumnImage(Object element, int columnIndex) { + return null; + } - /** - * {@inheritDoc} - */ - @Override - public Color getBackground(Object element, int columnIndex) { - return null;// return new Color(Display.getDefault(), 255, 0, 0); + /** + * {@inheritDoc} + */ + @Override + public String getColumnText(Object element, int columnIndex) { + try { + IKeyTreeNode item = (IKeyTreeNode) element; + IMessage entry = locale.getMessage(item.getMessageKey()); + if (entry != null) { + String value = entry.getValue(); + if (value.length() > 40) + value = value.substring(0, 39) + "..."; + } + } catch (Exception e) { } + return ""; + } - /** - * {@inheritDoc} - */ - @Override - public Color getForeground(Object element, int columnIndex) { - return null; - } + /** + * {@inheritDoc} + */ + @Override + public Color getBackground(Object element, int columnIndex) { + return null;// return new Color(Display.getDefault(), 255, 0, 0); + } - /** - * {@inheritDoc} - */ - @Override - public Font getFont(Object element, int columnIndex) { - return null; // UIUtils.createFont(SWT.BOLD); - } + /** + * {@inheritDoc} + */ + @Override + public Color getForeground(Object element, int columnIndex) { + return null; + } + + /** + * {@inheritDoc} + */ + @Override + public Font getFont(Object element, int columnIndex) { + return null; // UIUtils.createFont(SWT.BOLD); + } } diff --git a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java index 30314848..824f7b46 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java +++ b/org.eclipse.babel.tapiji.tools.core.ui/src/org/eclipse/babel/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -20,58 +20,58 @@ public class ValuedKeyTreeItemSorter extends ViewerSorter { - private StructuredViewer viewer; - private SortInfo sortInfo; + private StructuredViewer viewer; + private SortInfo sortInfo; - public ValuedKeyTreeItemSorter(StructuredViewer viewer, SortInfo sortInfo) { - this.viewer = viewer; - this.sortInfo = sortInfo; - } + public ValuedKeyTreeItemSorter(StructuredViewer viewer, SortInfo sortInfo) { + this.viewer = viewer; + this.sortInfo = sortInfo; + } - public StructuredViewer getViewer() { - return viewer; - } + public StructuredViewer getViewer() { + return viewer; + } - public void setViewer(StructuredViewer viewer) { - this.viewer = viewer; - } + public void setViewer(StructuredViewer viewer) { + this.viewer = viewer; + } - public SortInfo getSortInfo() { - return sortInfo; - } + public SortInfo getSortInfo() { + return sortInfo; + } - public void setSortInfo(SortInfo sortInfo) { - this.sortInfo = sortInfo; - } + public void setSortInfo(SortInfo sortInfo) { + this.sortInfo = sortInfo; + } - @Override - public int compare(Viewer viewer, Object e1, Object e2) { - try { - if (!(e1 instanceof IValuedKeyTreeNode && e2 instanceof IValuedKeyTreeNode)) - return super.compare(viewer, e1, e2); - IValuedKeyTreeNode comp1 = (IValuedKeyTreeNode) e1; - IValuedKeyTreeNode comp2 = (IValuedKeyTreeNode) e2; + @Override + public int compare(Viewer viewer, Object e1, Object e2) { + try { + if (!(e1 instanceof IValuedKeyTreeNode && e2 instanceof IValuedKeyTreeNode)) + return super.compare(viewer, e1, e2); + IValuedKeyTreeNode comp1 = (IValuedKeyTreeNode) e1; + IValuedKeyTreeNode comp2 = (IValuedKeyTreeNode) e2; - int result = 0; + int result = 0; - if (sortInfo == null) - return 0; + if (sortInfo == null) + return 0; - if (sortInfo.getColIdx() == 0) - result = comp1.getMessageKey().compareTo(comp2.getMessageKey()); - else { - Locale loc = sortInfo.getVisibleLocales().get( - sortInfo.getColIdx() - 1); - result = (comp1.getValue(loc) == null ? "" : comp1 - .getValue(loc)) - .compareTo((comp2.getValue(loc) == null ? "" : comp2 - .getValue(loc))); - } + if (sortInfo.getColIdx() == 0) + result = comp1.getMessageKey().compareTo(comp2.getMessageKey()); + else { + Locale loc = sortInfo.getVisibleLocales().get( + sortInfo.getColIdx() - 1); + result = (comp1.getValue(loc) == null ? "" : comp1 + .getValue(loc)) + .compareTo((comp2.getValue(loc) == null ? "" : comp2 + .getValue(loc))); + } - return result * (sortInfo.isDESC() ? -1 : 1); - } catch (Exception e) { - return 0; - } + return result * (sortInfo.isDESC() ? -1 : 1); + } catch (Exception e) { + return 0; } + } } diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Activator.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Activator.java index 3d99da71..0ba1c6b4 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Activator.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Activator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java index af681415..733b4f78 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/Logger.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -15,30 +15,30 @@ public class Logger { - public static void logInfo(String message) { - log(IStatus.INFO, IStatus.OK, message, null); - } + public static void logInfo(String message) { + log(IStatus.INFO, IStatus.OK, message, null); + } - public static void logError(Throwable exception) { - logError("Unexpected Exception", exception); - } + public static void logError(Throwable exception) { + logError("Unexpected Exception", exception); + } - public static void logError(String message, Throwable exception) { - log(IStatus.ERROR, IStatus.OK, message, exception); - } + public static void logError(String message, Throwable exception) { + log(IStatus.ERROR, IStatus.OK, message, exception); + } - public static void log(int severity, int code, String message, - Throwable exception) { - log(createStatus(severity, code, message, exception)); - } + public static void log(int severity, int code, String message, + Throwable exception) { + log(createStatus(severity, code, message, exception)); + } - public static IStatus createStatus(int severity, int code, String message, - Throwable exception) { - return new Status(severity, Activator.PLUGIN_ID, code, message, - exception); - } + public static IStatus createStatus(int severity, int code, String message, + Throwable exception) { + return new Status(severity, Activator.PLUGIN_ID, code, message, + exception); + } - public static void log(IStatus status) { - Activator.getDefault().getLog().log(status); - } + public static void log(IStatus status) { + Activator.getDefault().getLog().log(status); + } } diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/ILocation.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/ILocation.java index d8a77ebb..e53d2b94 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/ILocation.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/ILocation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/IMarkerConstants.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/IMarkerConstants.java index b5a62072..916f6ecc 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/IMarkerConstants.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/extensions/IMarkerConstants.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceBundleChangedListener.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceBundleChangedListener.java index a13886a6..f51fbca0 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceBundleChangedListener.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceBundleChangedListener.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceDescriptor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceDescriptor.java index 7a9b5b00..83f073be 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceDescriptor.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceDescriptor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java index 09ac533d..4a85add5 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/IResourceExclusionListener.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java index 9492ce65..dfd91df3 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/ResourceDescriptor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java index 1afbb963..036af55f 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/SLLocation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java index beb7436b..482de433 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/NoSuchResourceAuditorException.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/ResourceBundleException.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/ResourceBundleException.java index 40331555..408fd506 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/ResourceBundleException.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/exception/ResourceBundleException.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/IStateLoader.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/IStateLoader.java index c900c924..762687fa 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/IStateLoader.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/IStateLoader.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java index d1344cf2..17f62868 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleChangedEvent.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleDetector.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleDetector.java index 7bae005b..66521371 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleDetector.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceBundleDetector.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceExclusionEvent.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceExclusionEvent.java index 35611b04..769d49ad 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceExclusionEvent.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/model/manager/ResourceExclusionEvent.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/EditorUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/EditorUtils.java index dfbe4097..94c1a7a1 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/EditorUtils.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/EditorUtils.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Martin Reiterer, Matthias Lettmayer. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -8,7 +8,7 @@ * Contributors: * Martin Reiterer - initial API and implementation * Matthias Lettmayer - added update marker utils to update and get right position of marker (fixed issue 8) - * - fixed openEditor() to open an editor and selecting a key (fixed issue 59) + * - fixed openEditor() to open an editor and selecting a key (fixed issue 59) ******************************************************************************/ package org.eclipse.babel.tapiji.tools.core.util; diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java index 3e3d9319..208bd033 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FileUtils.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Martin Reiterer, Matthias Lettmayer. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java index 5e5038fa..8ffcf52e 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/FragmentProjectUtils.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java index e824855e..e23e07db 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/OverlayIcon.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/PDEUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/PDEUtils.java deleted file mode 100644 index c268c8c4..00000000 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/PDEUtils.java +++ /dev/null @@ -1,347 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 TapiJI. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Martin Reiterer - initial API and implementation - ******************************************************************************/ -/* - * Copyright (C) 2007 Uwe Voigt - * - * This file is part of Essiembre ResourceBundle Editor. - * - * Essiembre ResourceBundle Editor is free software; you can redistribute it - * and/or modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * Essiembre ResourceBundle Editor is distributed in the hope that it will be - * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with Essiembre ResourceBundle Editor; if not, write to the - * Free Software Foundation, Inc., 59 Temple Place, Suite 330, - * Boston, MA 02111-1307 USA - */ -package org.eclipse.babel.tapiji.tools.core.util; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; -import java.util.StringTokenizer; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.osgi.framework.Constants; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -/** - * A class that helps to find fragment and plugin projects. - * - * @author Uwe Voigt (http://sourceforge.net/users/uwe_ewald/) - */ -public class PDEUtils { - - /** Bundle manifest name */ - public static final String OSGI_BUNDLE_MANIFEST = "META-INF/MANIFEST.MF"; //$NON-NLS-1$ - /** Plugin manifest name */ - public static final String PLUGIN_MANIFEST = "plugin.xml"; //$NON-NLS-1$ - /** Fragment manifest name */ - public static final String FRAGMENT_MANIFEST = "fragment.xml"; //$NON-NLS-1$ - - /** - * Returns the plugin-id of the project if it is a plugin project. Else null - * is returned. - * - * @param project - * the project - * @return the plugin-id or null - */ - public static String getPluginId(IProject project) { - if (project == null) { - return null; - } - IResource manifest = project.findMember(OSGI_BUNDLE_MANIFEST); - String id = getManifestEntryValue(manifest, - Constants.BUNDLE_SYMBOLICNAME); - if (id != null) { - return id; - } - manifest = project.findMember(PLUGIN_MANIFEST); - if (manifest == null) { - manifest = project.findMember(FRAGMENT_MANIFEST); - } - if (manifest instanceof IFile) { - InputStream in = null; - try { - DocumentBuilder builder = DocumentBuilderFactory.newInstance() - .newDocumentBuilder(); - in = ((IFile) manifest).getContents(); - Document document = builder.parse(in); - Node node = getXMLElement(document, "plugin"); //$NON-NLS-1$ - if (node == null) { - node = getXMLElement(document, "fragment"); //$NON-NLS-1$ - } - if (node != null) { - node = node.getAttributes().getNamedItem("id"); //$NON-NLS-1$ - } - if (node != null) { - return node.getNodeValue(); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - if (in != null) { - in.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - return null; - } - - /** - * Returns all project containing plugin/fragment of the specified project. - * If the specified project itself is a fragment, then only this is - * returned. - * - * @param pluginProject - * the plugin project - * @return the all project containing a fragment or null if none - */ - public static IProject[] lookupFragment(IProject pluginProject) { - List<IProject> fragmentIds = new ArrayList<IProject>(); - - String pluginId = PDEUtils.getPluginId(pluginProject); - if (pluginId == null) { - return null; - } - String fragmentId = getFragmentId(pluginProject, - getPluginId(getFragmentHost(pluginProject))); - if (fragmentId != null) { - fragmentIds.add(pluginProject); - return fragmentIds.toArray(new IProject[0]); - } - - IProject[] projects = pluginProject.getWorkspace().getRoot() - .getProjects(); - for (int i = 0; i < projects.length; i++) { - IProject project = projects[i]; - if (!project.isOpen()) { - continue; - } - if (getFragmentId(project, pluginId) == null) { - continue; - } - fragmentIds.add(project); - } - - if (fragmentIds.size() > 0) { - return fragmentIds.toArray(new IProject[0]); - } else { - return null; - } - } - - public static boolean isFragment(IProject pluginProject) { - String pluginId = PDEUtils.getPluginId(pluginProject); - if (pluginId == null) { - return false; - } - String fragmentId = getFragmentId(pluginProject, - getPluginId(getFragmentHost(pluginProject))); - if (fragmentId != null) { - return true; - } else { - return false; - } - } - - public static List<IProject> getFragments(IProject hostProject) { - List<IProject> fragmentIds = new ArrayList<IProject>(); - - String pluginId = PDEUtils.getPluginId(hostProject); - IProject[] projects = hostProject.getWorkspace().getRoot() - .getProjects(); - - for (int i = 0; i < projects.length; i++) { - IProject project = projects[i]; - if (!project.isOpen()) { - continue; - } - if (getFragmentId(project, pluginId) == null) { - continue; - } - fragmentIds.add(project); - } - - return fragmentIds; - } - - /** - * Returns the fragment-id of the project if it is a fragment project with - * the specified host plugin id as host. Else null is returned. - * - * @param project - * the project - * @param hostPluginId - * the host plugin id - * @return the plugin-id or null - */ - public static String getFragmentId(IProject project, String hostPluginId) { - IResource manifest = project.findMember(FRAGMENT_MANIFEST); - Node fragmentNode = getXMLElement(getXMLDocument(manifest), "fragment"); //$NON-NLS-1$ - if (fragmentNode != null) { - Node hostNode = fragmentNode.getAttributes().getNamedItem( - "plugin-id"); //$NON-NLS-1$ - if (hostNode != null - && hostNode.getNodeValue().equals(hostPluginId)) { - Node idNode = fragmentNode.getAttributes().getNamedItem("id"); //$NON-NLS-1$ - if (idNode != null) { - return idNode.getNodeValue(); - } - } - } - manifest = project.findMember(OSGI_BUNDLE_MANIFEST); - String hostId = getManifestEntryValue(manifest, Constants.FRAGMENT_HOST); - if (hostId != null && hostId.equals(hostPluginId)) { - return getManifestEntryValue(manifest, - Constants.BUNDLE_SYMBOLICNAME); - } - return null; - } - - /** - * Returns the host plugin project of the specified project if it contains a - * fragment. - * - * @param fragment - * the fragment project - * @return the host plugin project or null - */ - public static IProject getFragmentHost(IProject fragment) { - IResource manifest = fragment.findMember(FRAGMENT_MANIFEST); - Node fragmentNode = getXMLElement(getXMLDocument(manifest), "fragment"); //$NON-NLS-1$ - if (fragmentNode != null) { - Node hostNode = fragmentNode.getAttributes().getNamedItem( - "plugin-id"); //$NON-NLS-1$ - if (hostNode != null) { - return fragment.getWorkspace().getRoot() - .getProject(hostNode.getNodeValue()); - } - } - manifest = fragment.findMember(OSGI_BUNDLE_MANIFEST); - String hostId = getManifestEntryValue(manifest, Constants.FRAGMENT_HOST); - if (hostId != null) { - return fragment.getWorkspace().getRoot().getProject(hostId); - } - return null; - } - - /** - * Returns the file content as UTF8 string. - * - * @param file - * @param charset - * @return - */ - public static String getFileContent(IFile file, String charset) { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - InputStream in = null; - try { - in = file.getContents(true); - byte[] buf = new byte[8000]; - for (int count; (count = in.read(buf)) != -1;) { - outputStream.write(buf, 0, count); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException ignore) { - } - } - } - try { - return outputStream.toString(charset); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - return outputStream.toString(); - } - } - - private static String getManifestEntryValue(IResource manifest, - String entryKey) { - if (manifest instanceof IFile) { - String content = getFileContent((IFile) manifest, "UTF8"); //$NON-NLS-1$ - int index = content.indexOf(entryKey); - if (index != -1) { - StringTokenizer st = new StringTokenizer( - content.substring(index + entryKey.length()), ";:\r\n"); //$NON-NLS-1$ - return st.nextToken().trim(); - } - } - return null; - } - - private static Document getXMLDocument(IResource resource) { - if (!(resource instanceof IFile)) { - return null; - } - InputStream in = null; - try { - DocumentBuilder builder = DocumentBuilderFactory.newInstance() - .newDocumentBuilder(); - in = ((IFile) resource).getContents(); - return builder.parse(in); - } catch (Exception e) { - e.printStackTrace(); - return null; - } finally { - try { - if (in != null) { - in.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - private static Node getXMLElement(Document document, String name) { - if (document == null) { - return null; - } - NodeList list = document.getChildNodes(); - for (int i = 0; i < list.getLength(); i++) { - Node node = list.item(i); - if (node.getNodeType() != Node.ELEMENT_NODE) { - continue; - } - if (name.equals(node.getNodeName())) { - return node; - } - } - return null; - } - -} diff --git a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/RBFileUtils.java b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/RBFileUtils.java index b8873ceb..f5cfe749 100644 --- a/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/RBFileUtils.java +++ b/org.eclipse.babel.tapiji.tools.core/src/org/eclipse/babel/tapiji/tools/core/util/RBFileUtils.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -15,22 +15,22 @@ import org.eclipse.jface.action.Action; public class RBFileUtils extends Action { - public static final String PROPERTIES_EXT = "properties"; + public static final String PROPERTIES_EXT = "properties"; - /** - * Checks whether a RB-file has a problem-marker - */ - public static boolean hasResourceBundleMarker(IResource r) { - try { - if (r.findMarkers(EditorUtils.RB_MARKER_ID, true, - IResource.DEPTH_INFINITE).length > 0) { - return true; - } else { - return false; - } - } catch (CoreException e) { - return false; - } + /** + * Checks whether a RB-file has a problem-marker + */ + public static boolean hasResourceBundleMarker(IResource r) { + try { + if (r.findMarkers(EditorUtils.RB_MARKER_ID, true, + IResource.DEPTH_INFINITE).length > 0) { + return true; + } else { + return false; + } + } catch (CoreException e) { + return false; } + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java index c3e5e692..a564ecf5 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/ConstantStringHover.java @@ -1,9 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 - initial API and implementation ******************************************************************************/ package org.eclipse.babel.tapiji.tools.java.ui; @@ -20,75 +23,75 @@ public class ConstantStringHover implements IJavaEditorTextHover { - IEditorPart editor = null; - ResourceAuditVisitor csf = null; - ResourceBundleManager manager = null; + IEditorPart editor = null; + ResourceAuditVisitor csf = null; + ResourceBundleManager manager = null; - @Override - public void setEditor(IEditorPart editor) { - this.editor = editor; - initConstantStringAuditor(); - } + @Override + public void setEditor(IEditorPart editor) { + this.editor = editor; + initConstantStringAuditor(); + } + + protected void initConstantStringAuditor() { + // parse editor content and extract resource-bundle access strings - protected void initConstantStringAuditor() { - // parse editor content and extract resource-bundle access strings + // get the type of the currently loaded resource + ITypeRoot typeRoot = JavaUI.getEditorInputTypeRoot(editor + .getEditorInput()); - // get the type of the currently loaded resource - ITypeRoot typeRoot = JavaUI.getEditorInputTypeRoot(editor - .getEditorInput()); + if (typeRoot == null) { + return; + } - if (typeRoot == null) { - return; - } + CompilationUnit cu = ASTutilsUI.getCompilationUnit(typeRoot); - CompilationUnit cu = ASTutilsUI.getCompilationUnit(typeRoot); + if (cu == null) { + return; + } - if (cu == null) { - return; - } + manager = ResourceBundleManager.getManager(cu.getJavaElement() + .getResource().getProject()); - manager = ResourceBundleManager.getManager(cu.getJavaElement() - .getResource().getProject()); + // determine the element at the position of the cursur + csf = new ResourceAuditVisitor(null, manager.getProject().getName()); + cu.accept(csf); + } - // determine the element at the position of the cursur - csf = new ResourceAuditVisitor(null, manager.getProject().getName()); - cu.accept(csf); + @Override + public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { + initConstantStringAuditor(); + if (hoverRegion == null) { + return null; } - @Override - public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { - initConstantStringAuditor(); - if (hoverRegion == null) { - return null; - } - - // get region for string literals - hoverRegion = getHoverRegion(textViewer, hoverRegion.getOffset()); - - if (hoverRegion == null) { - return null; - } - - String bundleName = csf.getBundleReference(hoverRegion); - String key = csf.getKeyAt(hoverRegion); - - String hoverText = manager.getKeyHoverString(bundleName, key); - if (hoverText == null || hoverText.equals("")) { - return null; - } else { - return hoverText; - } + // get region for string literals + hoverRegion = getHoverRegion(textViewer, hoverRegion.getOffset()); + + if (hoverRegion == null) { + return null; } - @Override - public IRegion getHoverRegion(ITextViewer textViewer, int offset) { - if (editor == null) { - return null; - } + String bundleName = csf.getBundleReference(hoverRegion); + String key = csf.getKeyAt(hoverRegion); + + String hoverText = manager.getKeyHoverString(bundleName, key); + if (hoverText == null || hoverText.equals("")) { + return null; + } else { + return hoverText; + } + } - // Retrieve the property key at this position. Otherwise, null is - // returned. - return csf.getKeyAt(Long.valueOf(offset)); + @Override + public IRegion getHoverRegion(ITextViewer textViewer, int offset) { + if (editor == null) { + return null; } + // Retrieve the property key at this position. Otherwise, null is + // returned. + return csf.getKeyAt(Long.valueOf(offset)); + } + } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/JavaResourceAuditor.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/JavaResourceAuditor.java index db3864da..ac697121 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/JavaResourceAuditor.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/JavaResourceAuditor.java @@ -1,9 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 - initial API and implementation ******************************************************************************/ package org.eclipse.babel.tapiji.tools.java.ui; @@ -34,129 +37,129 @@ public class JavaResourceAuditor extends I18nResourceAuditor { - protected List<SLLocation> constantLiterals = new ArrayList<SLLocation>(); - protected List<SLLocation> brokenResourceReferences = new ArrayList<SLLocation>(); - protected List<SLLocation> brokenBundleReferences = new ArrayList<SLLocation>(); + protected List<SLLocation> constantLiterals = new ArrayList<SLLocation>(); + protected List<SLLocation> brokenResourceReferences = new ArrayList<SLLocation>(); + protected List<SLLocation> brokenBundleReferences = new ArrayList<SLLocation>(); - @Override - public String[] getFileEndings() { - return new String[] { "java" }; - } - - @Override - public void audit(IResource resource) { - - ResourceAuditVisitor csav = new ResourceAuditVisitor(resource - .getProject().getFile(resource.getProjectRelativePath()), - resource.getProject().getName()); - - // get a reference to the shared AST of the loaded CompilationUnit - CompilationUnit cu = ASTutilsUI.getCompilationUnit(resource); - if (cu == null) { - System.out.println("Cannot audit resource: " - + resource.getFullPath()); - return; - } - cu.accept(csav); - - // Report all constant string literals - constantLiterals = csav.getConstantStringLiterals(); - - // Report all broken Resource-Bundle references - brokenResourceReferences = csav.getBrokenResourceReferences(); - - // Report all broken definitions to Resource-Bundle references - brokenBundleReferences = csav.getBrokenRBReferences(); - } - - @Override - public List<ILocation> getConstantStringLiterals() { - return new ArrayList<ILocation>(constantLiterals); - } + @Override + public String[] getFileEndings() { + return new String[] { "java" }; + } - @Override - public List<ILocation> getBrokenResourceReferences() { - return new ArrayList<ILocation>(brokenResourceReferences); - } + @Override + public void audit(IResource resource) { - @Override - public List<ILocation> getBrokenBundleReferences() { - return new ArrayList<ILocation>(brokenBundleReferences); - } + ResourceAuditVisitor csav = new ResourceAuditVisitor(resource + .getProject().getFile(resource.getProjectRelativePath()), + resource.getProject().getName()); - @Override - public String getContextId() { - return "java"; + // get a reference to the shared AST of the loaded CompilationUnit + CompilationUnit cu = ASTutilsUI.getCompilationUnit(resource); + if (cu == null) { + System.out.println("Cannot audit resource: " + + resource.getFullPath()); + return; } - - @Override - public List<IMarkerResolution> getMarkerResolutions(IMarker marker) { - List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>(); - - switch (marker.getAttribute("cause", -1)) { - case IMarkerConstants.CAUSE_CONSTANT_LITERAL: - resolutions.add(new IgnoreStringFromInternationalization()); - resolutions.add(new ExcludeResourceFromInternationalization()); - resolutions.add(new ExportToResourceBundleResolution()); - break; - case IMarkerConstants.CAUSE_BROKEN_REFERENCE: - String dataName = marker.getAttribute("bundleName", ""); - int dataStart = marker.getAttribute("bundleStart", 0); - int dataEnd = marker.getAttribute("bundleEnd", 0); - - IProject project = marker.getResource().getProject(); - ResourceBundleManager manager = ResourceBundleManager - .getManager(project); - - if (manager.getResourceBundle(dataName) != null) { - String key = marker.getAttribute("key", ""); - - resolutions.add(new CreateResourceBundleEntry(key, dataName)); - resolutions.add(new ReplaceResourceBundleReference(key, - dataName)); - resolutions.add(new ReplaceResourceBundleDefReference(dataName, - dataStart, dataEnd)); - } else { - String bname = dataName; - - Set<IResource> bundleResources = ResourceBundleManager - .getManager(marker.getResource().getProject()) - .getAllResourceBundleResources(bname); - - if (bundleResources != null && bundleResources.size() > 0) { - resolutions - .add(new IncludeResource(bname, bundleResources)); - } else { - resolutions.add(new CreateResourceBundle(bname, marker - .getResource(), dataStart, dataEnd)); - } - resolutions.add(new ReplaceResourceBundleDefReference(bname, - dataStart, dataEnd)); - } - - break; - case IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE: - String bname = marker.getAttribute("key", ""); - - Set<IResource> bundleResources = ResourceBundleManager.getManager( - marker.getResource().getProject()) - .getAllResourceBundleResources(bname); - - if (bundleResources != null && bundleResources.size() > 0) { - resolutions.add(new IncludeResource(bname, bundleResources)); - } else { - resolutions.add(new CreateResourceBundle(marker.getAttribute( - "key", ""), marker.getResource(), marker.getAttribute( - IMarker.CHAR_START, 0), marker.getAttribute( - IMarker.CHAR_END, 0))); - } - resolutions.add(new ReplaceResourceBundleDefReference(marker - .getAttribute("key", ""), marker.getAttribute( - IMarker.CHAR_START, 0), marker.getAttribute( - IMarker.CHAR_END, 0))); + cu.accept(csav); + + // Report all constant string literals + constantLiterals = csav.getConstantStringLiterals(); + + // Report all broken Resource-Bundle references + brokenResourceReferences = csav.getBrokenResourceReferences(); + + // Report all broken definitions to Resource-Bundle references + brokenBundleReferences = csav.getBrokenRBReferences(); + } + + @Override + public List<ILocation> getConstantStringLiterals() { + return new ArrayList<ILocation>(constantLiterals); + } + + @Override + public List<ILocation> getBrokenResourceReferences() { + return new ArrayList<ILocation>(brokenResourceReferences); + } + + @Override + public List<ILocation> getBrokenBundleReferences() { + return new ArrayList<ILocation>(brokenBundleReferences); + } + + @Override + public String getContextId() { + return "java"; + } + + @Override + public List<IMarkerResolution> getMarkerResolutions(IMarker marker) { + List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>(); + + switch (marker.getAttribute("cause", -1)) { + case IMarkerConstants.CAUSE_CONSTANT_LITERAL: + resolutions.add(new IgnoreStringFromInternationalization()); + resolutions.add(new ExcludeResourceFromInternationalization()); + resolutions.add(new ExportToResourceBundleResolution()); + break; + case IMarkerConstants.CAUSE_BROKEN_REFERENCE: + String dataName = marker.getAttribute("bundleName", ""); + int dataStart = marker.getAttribute("bundleStart", 0); + int dataEnd = marker.getAttribute("bundleEnd", 0); + + IProject project = marker.getResource().getProject(); + ResourceBundleManager manager = ResourceBundleManager + .getManager(project); + + if (manager.getResourceBundle(dataName) != null) { + String key = marker.getAttribute("key", ""); + + resolutions.add(new CreateResourceBundleEntry(key, dataName)); + resolutions.add(new ReplaceResourceBundleReference(key, + dataName)); + resolutions.add(new ReplaceResourceBundleDefReference(dataName, + dataStart, dataEnd)); + } else { + String bname = dataName; + + Set<IResource> bundleResources = ResourceBundleManager + .getManager(marker.getResource().getProject()) + .getAllResourceBundleResources(bname); + + if (bundleResources != null && bundleResources.size() > 0) { + resolutions + .add(new IncludeResource(bname, bundleResources)); + } else { + resolutions.add(new CreateResourceBundle(bname, marker + .getResource(), dataStart, dataEnd)); } - - return resolutions; + resolutions.add(new ReplaceResourceBundleDefReference(bname, + dataStart, dataEnd)); + } + + break; + case IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE: + String bname = marker.getAttribute("key", ""); + + Set<IResource> bundleResources = ResourceBundleManager.getManager( + marker.getResource().getProject()) + .getAllResourceBundleResources(bname); + + if (bundleResources != null && bundleResources.size() > 0) { + resolutions.add(new IncludeResource(bname, bundleResources)); + } else { + resolutions.add(new CreateResourceBundle(marker.getAttribute( + "key", ""), marker.getResource(), marker.getAttribute( + IMarker.CHAR_START, 0), marker.getAttribute( + IMarker.CHAR_END, 0))); + } + resolutions.add(new ReplaceResourceBundleDefReference(marker + .getAttribute("key", ""), marker.getAttribute( + IMarker.CHAR_START, 0), marker.getAttribute( + IMarker.CHAR_END, 0))); } + return resolutions; + } + } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java index fff6d5b6..efe9c951 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/MessageCompletionProposalComputer.java @@ -1,9 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 - initial API and implementation ******************************************************************************/ package org.eclipse.babel.tapiji.tools.java.ui; @@ -36,230 +39,231 @@ import org.eclipse.jface.text.contentassist.IContextInformation; public class MessageCompletionProposalComputer implements - IJavaCompletionProposalComputer { + IJavaCompletionProposalComputer { - private ResourceAuditVisitor csav; - private IResource resource; - private CompilationUnit cu; - private ResourceBundleManager manager; + private ResourceAuditVisitor csav; + private IResource resource; + private CompilationUnit cu; + private ResourceBundleManager manager; - public MessageCompletionProposalComputer() { + public MessageCompletionProposalComputer() { - } - - @Override - public List<ICompletionProposal> computeCompletionProposals( - ContentAssistInvocationContext context, IProgressMonitor monitor) { + } - List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); + @Override + public List<ICompletionProposal> computeCompletionProposals( + ContentAssistInvocationContext context, IProgressMonitor monitor) { - if (!InternationalizationNature - .hasNature(((JavaContentAssistInvocationContext) context) - .getCompilationUnit().getResource().getProject())) { - return completions; - } + List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); - try { - JavaContentAssistInvocationContext javaContext = ((JavaContentAssistInvocationContext) context); - CompletionContext coreContext = javaContext.getCoreContext(); - - int tokenStart = coreContext.getTokenStart(); - int tokenEnd = coreContext.getTokenEnd(); - int tokenOffset = coreContext.getOffset(); - boolean isStringLiteral = coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_STRING_LITERAL; - - if (coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_NAME - && (tokenEnd + 1) - tokenStart > 0) { - return completions; - } - - if (cu == null) { - manager = ResourceBundleManager.getManager(javaContext - .getCompilationUnit().getResource().getProject()); - - resource = javaContext.getCompilationUnit().getResource(); - - csav = new ResourceAuditVisitor(null, manager.getProject() - .getName()); - - cu = ASTutilsUI.getCompilationUnit(resource); - - cu.accept(csav); - } - - if (tokenStart < 0) { - // is string literal in front of cursor? - StringLiteral strLit = ASTutils.getStringLiteralAtPos(cu, tokenOffset-1); - if (strLit != null) { - tokenStart = strLit.getStartPosition(); - tokenEnd = tokenStart + strLit.getLength() - 1; - tokenOffset = tokenOffset-1; - isStringLiteral = true; - } else { - tokenStart = tokenOffset; - tokenEnd = tokenOffset; - } - } - - if (isStringLiteral) { - tokenStart++; - } - - tokenEnd = Math.max(tokenEnd, tokenStart); - - String fullToken = ""; - - if (tokenStart < tokenEnd) { - fullToken = context.getDocument().get(tokenStart, - tokenEnd - tokenStart); - } - - // Check if the string literal is up to be written within the - // context of a resource-bundle accessor method - if (csav.getKeyAt(new Long(tokenOffset)) != null && isStringLiteral) { - completions.addAll(getResourceBundleCompletionProposals( - tokenStart, tokenEnd, tokenOffset, isStringLiteral, - fullToken, manager, csav, resource)); - } else if (csav.getRBReferenceAt(new Long(tokenOffset)) != null - && isStringLiteral) { - completions.addAll(getRBReferenceCompletionProposals( - tokenStart, tokenEnd, fullToken, isStringLiteral, - manager, resource)); - } else { - completions.addAll(getBasicJavaCompletionProposals(tokenStart, - tokenEnd, tokenOffset, fullToken, isStringLiteral, - manager, csav, resource)); - } - if (completions.size() == 1) { - completions.add(new NoActionProposal()); - } - - } catch (Exception e) { - Logger.logError(e); - } - return completions; + if (!InternationalizationNature + .hasNature(((JavaContentAssistInvocationContext) context) + .getCompilationUnit().getResource().getProject())) { + return completions; } - private Collection<ICompletionProposal> getRBReferenceCompletionProposals( - int tokenStart, int tokenEnd, String fullToken, - boolean isStringLiteral, ResourceBundleManager manager, - IResource resource) { - List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); - boolean hit = false; - - // Show a list of available resource bundles - List<String> resourceBundles = manager.getResourceBundleIdentifiers(); - for (String rbName : resourceBundles) { - if (rbName.startsWith(fullToken)) { - if (rbName.equals(fullToken)) { - hit = true; - } else { - completions.add(new MessageCompletionProposal(tokenStart, - tokenEnd - tokenStart, rbName, true)); - } - } - } + try { + JavaContentAssistInvocationContext javaContext = ((JavaContentAssistInvocationContext) context); + CompletionContext coreContext = javaContext.getCoreContext(); - if (!hit && fullToken.trim().length() > 0) { - completions.add(new CreateResourceBundleProposal(fullToken, - resource, tokenStart, tokenEnd)); - } + int tokenStart = coreContext.getTokenStart(); + int tokenEnd = coreContext.getTokenEnd(); + int tokenOffset = coreContext.getOffset(); + boolean isStringLiteral = coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_STRING_LITERAL; + if (coreContext.getTokenKind() == CompletionContext.TOKEN_KIND_NAME + && (tokenEnd + 1) - tokenStart > 0) { return completions; - } + } + + if (cu == null) { + manager = ResourceBundleManager.getManager(javaContext + .getCompilationUnit().getResource().getProject()); + + resource = javaContext.getCompilationUnit().getResource(); + + csav = new ResourceAuditVisitor(null, manager.getProject() + .getName()); - protected List<ICompletionProposal> getBasicJavaCompletionProposals( - int tokenStart, int tokenEnd, int tokenOffset, String fullToken, - boolean isStringLiteral, ResourceBundleManager manager, - ResourceAuditVisitor csav, IResource resource) { - List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); - - if (fullToken.length() == 0) { - // If nothing has been entered - completions.add(new InsertResourceBundleReferenceProposal( - tokenStart, tokenEnd - tokenStart, manager.getProject() - .getName(), resource, csav - .getDefinedResourceBundles(tokenOffset))); - completions.add(new NewResourceBundleEntryProposal(resource, - tokenStart, tokenEnd, fullToken, isStringLiteral, false, - manager.getProject().getName(), null)); + cu = ASTutilsUI.getCompilationUnit(resource); + + cu.accept(csav); + } + + if (tokenStart < 0) { + // is string literal in front of cursor? + StringLiteral strLit = ASTutils.getStringLiteralAtPos(cu, + tokenOffset - 1); + if (strLit != null) { + tokenStart = strLit.getStartPosition(); + tokenEnd = tokenStart + strLit.getLength() - 1; + tokenOffset = tokenOffset - 1; + isStringLiteral = true; } else { - completions.add(new NewResourceBundleEntryProposal(resource, - tokenStart, tokenEnd, fullToken, isStringLiteral, false, - manager.getProject().getName(), null)); + tokenStart = tokenOffset; + tokenEnd = tokenOffset; } - return completions; + } + + if (isStringLiteral) { + tokenStart++; + } + + tokenEnd = Math.max(tokenEnd, tokenStart); + + String fullToken = ""; + + if (tokenStart < tokenEnd) { + fullToken = context.getDocument().get(tokenStart, + tokenEnd - tokenStart); + } + + // Check if the string literal is up to be written within the + // context of a resource-bundle accessor method + if (csav.getKeyAt(new Long(tokenOffset)) != null && isStringLiteral) { + completions.addAll(getResourceBundleCompletionProposals( + tokenStart, tokenEnd, tokenOffset, isStringLiteral, + fullToken, manager, csav, resource)); + } else if (csav.getRBReferenceAt(new Long(tokenOffset)) != null + && isStringLiteral) { + completions.addAll(getRBReferenceCompletionProposals( + tokenStart, tokenEnd, fullToken, isStringLiteral, + manager, resource)); + } else { + completions.addAll(getBasicJavaCompletionProposals(tokenStart, + tokenEnd, tokenOffset, fullToken, isStringLiteral, + manager, csav, resource)); + } + if (completions.size() == 1) { + completions.add(new NoActionProposal()); + } + + } catch (Exception e) { + Logger.logError(e); } - - protected List<ICompletionProposal> getResourceBundleCompletionProposals( - int tokenStart, int tokenEnd, int tokenOffset, - boolean isStringLiteral, String fullToken, - ResourceBundleManager manager, ResourceAuditVisitor csav, - IResource resource) { - - List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); - IRegion region = csav.getKeyAt(new Long(tokenOffset)); - String bundleName = csav.getBundleReference(region); - IMessagesBundleGroup bundleGroup = manager - .getResourceBundle(bundleName); - - if (fullToken.length() > 0) { - boolean hit = false; - // If a part of a String has already been entered - for (String key : bundleGroup.getMessageKeys()) { - if (key.toLowerCase().startsWith(fullToken)) { - if (!key.equals(fullToken)) { - completions.add(new MessageCompletionProposal( - tokenStart, tokenEnd - tokenStart, key, false)); - } else { - hit = true; - } - } - } - if (!hit) { - completions.add(new NewResourceBundleEntryProposal(resource, - tokenStart, tokenEnd, fullToken, isStringLiteral, true, - manager.getProject().getName(), bundleName)); - - // TODO: reference to existing resource - } + return completions; + } + + private Collection<ICompletionProposal> getRBReferenceCompletionProposals( + int tokenStart, int tokenEnd, String fullToken, + boolean isStringLiteral, ResourceBundleManager manager, + IResource resource) { + List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); + boolean hit = false; + + // Show a list of available resource bundles + List<String> resourceBundles = manager.getResourceBundleIdentifiers(); + for (String rbName : resourceBundles) { + if (rbName.startsWith(fullToken)) { + if (rbName.equals(fullToken)) { + hit = true; } else { - for (String key : bundleGroup.getMessageKeys()) { - completions.add(new MessageCompletionProposal(tokenStart, - tokenEnd - tokenStart, key, false)); - } - completions.add(new NewResourceBundleEntryProposal(resource, - tokenStart, tokenEnd, fullToken, isStringLiteral, true, - manager.getProject().getName(), bundleName)); - + completions.add(new MessageCompletionProposal(tokenStart, + tokenEnd - tokenStart, rbName, true)); } - return completions; + } } - @Override - public String getErrorMessage() { - // TODO Auto-generated method stub - return ""; + if (!hit && fullToken.trim().length() > 0) { + completions.add(new CreateResourceBundleProposal(fullToken, + resource, tokenStart, tokenEnd)); } - @Override - public void sessionEnded() { - cu = null; - csav = null; - resource = null; - manager = null; - } - - @Override - public void sessionStarted() { - + return completions; + } + + protected List<ICompletionProposal> getBasicJavaCompletionProposals( + int tokenStart, int tokenEnd, int tokenOffset, String fullToken, + boolean isStringLiteral, ResourceBundleManager manager, + ResourceAuditVisitor csav, IResource resource) { + List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); + + if (fullToken.length() == 0) { + // If nothing has been entered + completions.add(new InsertResourceBundleReferenceProposal( + tokenStart, tokenEnd - tokenStart, manager.getProject() + .getName(), resource, csav + .getDefinedResourceBundles(tokenOffset))); + completions.add(new NewResourceBundleEntryProposal(resource, + tokenStart, tokenEnd, fullToken, isStringLiteral, false, + manager.getProject().getName(), null)); + } else { + completions.add(new NewResourceBundleEntryProposal(resource, + tokenStart, tokenEnd, fullToken, isStringLiteral, false, + manager.getProject().getName(), null)); } + return completions; + } + + protected List<ICompletionProposal> getResourceBundleCompletionProposals( + int tokenStart, int tokenEnd, int tokenOffset, + boolean isStringLiteral, String fullToken, + ResourceBundleManager manager, ResourceAuditVisitor csav, + IResource resource) { + + List<ICompletionProposal> completions = new ArrayList<ICompletionProposal>(); + IRegion region = csav.getKeyAt(new Long(tokenOffset)); + String bundleName = csav.getBundleReference(region); + IMessagesBundleGroup bundleGroup = manager + .getResourceBundle(bundleName); + + if (fullToken.length() > 0) { + boolean hit = false; + // If a part of a String has already been entered + for (String key : bundleGroup.getMessageKeys()) { + if (key.toLowerCase().startsWith(fullToken)) { + if (!key.equals(fullToken)) { + completions.add(new MessageCompletionProposal( + tokenStart, tokenEnd - tokenStart, key, false)); + } else { + hit = true; + } + } + } + if (!hit) { + completions.add(new NewResourceBundleEntryProposal(resource, + tokenStart, tokenEnd, fullToken, isStringLiteral, true, + manager.getProject().getName(), bundleName)); + + // TODO: reference to existing resource + } + } else { + for (String key : bundleGroup.getMessageKeys()) { + completions.add(new MessageCompletionProposal(tokenStart, + tokenEnd - tokenStart, key, false)); + } + completions.add(new NewResourceBundleEntryProposal(resource, + tokenStart, tokenEnd, fullToken, isStringLiteral, true, + manager.getProject().getName(), bundleName)); - @Override - public List<IContextInformation> computeContextInformation( - ContentAssistInvocationContext arg0, IProgressMonitor arg1) { - // TODO Auto-generated method stub - return null; } + return completions; + } + + @Override + public String getErrorMessage() { + // TODO Auto-generated method stub + return ""; + } + + @Override + public void sessionEnded() { + cu = null; + csav = null; + resource = null; + manager = null; + } + + @Override + public void sessionStarted() { + + } + + @Override + public List<IContextInformation> computeContextInformation( + ContentAssistInvocationContext arg0, IProgressMonitor arg1) { + // TODO Auto-generated method stub + return null; + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java index c6f5b402..72fe63e4 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/CreateResourceBundleProposal.java @@ -1,9 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 - Initial implementation ******************************************************************************/ package org.eclipse.babel.tapiji.tools.java.ui.autocompletion; @@ -38,191 +41,191 @@ public class CreateResourceBundleProposal implements IJavaCompletionProposal { - private IResource resource; - private int start; - private int end; - private String key; - private final String newBunldeWizard = "org.eclipse.babel.editor.wizards.ResourceBundleWizard"; - - public CreateResourceBundleProposal(String key, IResource resource, - int start, int end) { - this.key = ResourceUtils.deriveNonExistingRBName(key, - ResourceBundleManager.getManager(resource.getProject())); - this.resource = resource; - this.start = start; - this.end = end; + private IResource resource; + private int start; + private int end; + private String key; + private final String newBunldeWizard = "org.eclipse.babel.editor.wizards.ResourceBundleWizard"; + + public CreateResourceBundleProposal(String key, IResource resource, + int start, int end) { + this.key = ResourceUtils.deriveNonExistingRBName(key, + ResourceBundleManager.getManager(resource.getProject())); + this.resource = resource; + this.start = start; + this.end = end; + } + + public String getDescription() { + return "Creates a new Resource-Bundle with the id '" + key + "'"; + } + + public String getLabel() { + return "Create Resource-Bundle '" + key + "'"; + } + + @SuppressWarnings("deprecation") + protected void runAction() { + // First see if this is a "new wizard". + IWizardDescriptor descriptor = PlatformUI.getWorkbench() + .getNewWizardRegistry().findWizard(newBunldeWizard); + // If not check if it is an "import wizard". + if (descriptor == null) { + descriptor = PlatformUI.getWorkbench().getImportWizardRegistry() + .findWizard(newBunldeWizard); } - - public String getDescription() { - return "Creates a new Resource-Bundle with the id '" + key + "'"; - } - - public String getLabel() { - return "Create Resource-Bundle '" + key + "'"; + // Or maybe an export wizard + if (descriptor == null) { + descriptor = PlatformUI.getWorkbench().getExportWizardRegistry() + .findWizard(newBunldeWizard); } + try { + // Then if we have a wizard, open it. + if (descriptor != null) { + IWizard wizard = descriptor.createWizard(); - @SuppressWarnings("deprecation") - protected void runAction() { - // First see if this is a "new wizard". - IWizardDescriptor descriptor = PlatformUI.getWorkbench() - .getNewWizardRegistry().findWizard(newBunldeWizard); - // If not check if it is an "import wizard". - if (descriptor == null) { - descriptor = PlatformUI.getWorkbench().getImportWizardRegistry() - .findWizard(newBunldeWizard); + if (!(wizard instanceof IResourceBundleWizard)) { + return; } - // Or maybe an export wizard - if (descriptor == null) { - descriptor = PlatformUI.getWorkbench().getExportWizardRegistry() - .findWizard(newBunldeWizard); + + IResourceBundleWizard rbw = (IResourceBundleWizard) wizard; + String[] keySilbings = key.split("\\."); + String rbName = keySilbings[keySilbings.length - 1]; + String packageName = ""; + + rbw.setBundleId(rbName); + + // Set the default path according to the specified package name + String pathName = ""; + if (keySilbings.length > 1) { + try { + IJavaProject jp = JavaCore + .create(resource.getProject()); + packageName = key.substring(0, key.lastIndexOf(".")); + + for (IPackageFragmentRoot fr : jp + .getAllPackageFragmentRoots()) { + IPackageFragment pf = fr + .getPackageFragment(packageName); + if (pf.exists()) { + pathName = pf.getResource().getFullPath() + .removeFirstSegments(0).toOSString(); + break; + } + } + } catch (Exception e) { + pathName = ""; + } } + try { - // Then if we have a wizard, open it. - if (descriptor != null) { - IWizard wizard = descriptor.createWizard(); - - if (!(wizard instanceof IResourceBundleWizard)) { - return; - } - - IResourceBundleWizard rbw = (IResourceBundleWizard) wizard; - String[] keySilbings = key.split("\\."); - String rbName = keySilbings[keySilbings.length - 1]; - String packageName = ""; - - rbw.setBundleId(rbName); - - // Set the default path according to the specified package name - String pathName = ""; - if (keySilbings.length > 1) { - try { - IJavaProject jp = JavaCore - .create(resource.getProject()); - packageName = key.substring(0, key.lastIndexOf(".")); - - for (IPackageFragmentRoot fr : jp - .getAllPackageFragmentRoots()) { - IPackageFragment pf = fr - .getPackageFragment(packageName); - if (pf.exists()) { - pathName = pf.getResource().getFullPath() - .removeFirstSegments(0).toOSString(); - break; - } - } - } catch (Exception e) { - pathName = ""; - } - } - - try { - IJavaProject jp = JavaCore.create(resource.getProject()); - if (pathName.trim().equals("")) { - for (IPackageFragmentRoot fr : jp - .getAllPackageFragmentRoots()) { - if (!fr.isReadOnly()) { - pathName = fr.getResource().getFullPath() - .removeFirstSegments(0).toOSString(); - break; - } - } - } - } catch (Exception e) { - pathName = ""; - } - - rbw.setDefaultPath(pathName); - - WizardDialog wd = new WizardDialog(Display.getDefault() - .getActiveShell(), wizard); - - wd.setTitle(wizard.getWindowTitle()); - if (wd.open() == WizardDialog.OK) { - try { - resource.getProject().build( - IncrementalProjectBuilder.FULL_BUILD, - I18nBuilder.BUILDER_ID, null, null); - } catch (CoreException e) { - Logger.logError(e); - } - - ITextFileBufferManager bufferManager = FileBuffers - .getTextFileBufferManager(); - IPath path = resource.getRawLocation(); - try { - bufferManager.connect(path, LocationKind.NORMALIZE, - null); - ITextFileBuffer textFileBuffer = bufferManager - .getTextFileBuffer(path, LocationKind.NORMALIZE); - IDocument document = textFileBuffer.getDocument(); - - if (document.get().charAt(start - 1) == '"' - && document.get().charAt(start) != '"') { - start--; - end++; - } - if (document.get().charAt(end + 1) == '"' - && document.get().charAt(end) != '"') { - end++; - } - - document.replace(start, end - start, "\"" - + (packageName.equals("") ? "" : packageName - + ".") + rbName + "\""); - - textFileBuffer.commit(null, false); - } catch (Exception e) { - } finally { - try { - bufferManager.disconnect(path, null); - } catch (CoreException e) { - } - } - } + IJavaProject jp = JavaCore.create(resource.getProject()); + if (pathName.trim().equals("")) { + for (IPackageFragmentRoot fr : jp + .getAllPackageFragmentRoots()) { + if (!fr.isReadOnly()) { + pathName = fr.getResource().getFullPath() + .removeFirstSegments(0).toOSString(); + break; + } } - } catch (CoreException e) { + } + } catch (Exception e) { + pathName = ""; } - } - - @Override - public void apply(IDocument document) { - this.runAction(); - } - - @Override - public String getAdditionalProposalInfo() { - return getDescription(); - } - @Override - public IContextInformation getContextInformation() { - return null; - } - - @Override - public String getDisplayString() { - return getLabel(); - } - - @Override - public Point getSelection(IDocument document) { - return null; - } + rbw.setDefaultPath(pathName); + + WizardDialog wd = new WizardDialog(Display.getDefault() + .getActiveShell(), wizard); + + wd.setTitle(wizard.getWindowTitle()); + if (wd.open() == WizardDialog.OK) { + try { + resource.getProject().build( + IncrementalProjectBuilder.FULL_BUILD, + I18nBuilder.BUILDER_ID, null, null); + } catch (CoreException e) { + Logger.logError(e); + } + + ITextFileBufferManager bufferManager = FileBuffers + .getTextFileBufferManager(); + IPath path = resource.getRawLocation(); + try { + bufferManager.connect(path, LocationKind.NORMALIZE, + null); + ITextFileBuffer textFileBuffer = bufferManager + .getTextFileBuffer(path, LocationKind.NORMALIZE); + IDocument document = textFileBuffer.getDocument(); + + if (document.get().charAt(start - 1) == '"' + && document.get().charAt(start) != '"') { + start--; + end++; + } + if (document.get().charAt(end + 1) == '"' + && document.get().charAt(end) != '"') { + end++; + } - @Override - public Image getImage() { - return PlatformUI.getWorkbench().getSharedImages() - .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage(); - } + document.replace(start, end - start, "\"" + + (packageName.equals("") ? "" : packageName + + ".") + rbName + "\""); - @Override - public int getRelevance() { - // TODO Auto-generated method stub - if (end - start == 0) { - return 99; - } else { - return 1099; + textFileBuffer.commit(null, false); + } catch (Exception e) { + } finally { + try { + bufferManager.disconnect(path, null); + } catch (CoreException e) { + } + } } + } + } catch (CoreException e) { + } + } + + @Override + public void apply(IDocument document) { + this.runAction(); + } + + @Override + public String getAdditionalProposalInfo() { + return getDescription(); + } + + @Override + public IContextInformation getContextInformation() { + return null; + } + + @Override + public String getDisplayString() { + return getLabel(); + } + + @Override + public Point getSelection(IDocument document) { + return null; + } + + @Override + public Image getImage() { + return PlatformUI.getWorkbench().getSharedImages() + .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage(); + } + + @Override + public int getRelevance() { + // TODO Auto-generated method stub + if (end - start == 0) { + return 99; + } else { + return 1099; } + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java index cc00eb45..066271c7 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/InsertResourceBundleReferenceProposal.java @@ -1,9 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 - initial API and implementation ******************************************************************************/ package org.eclipse.babel.tapiji.tools.java.ui.autocompletion; @@ -24,78 +27,78 @@ import org.eclipse.ui.PlatformUI; public class InsertResourceBundleReferenceProposal implements - IJavaCompletionProposal { - - private int offset = 0; - private int length = 0; - private IResource resource; - private String reference; - private String projectName; - - public InsertResourceBundleReferenceProposal(int offset, int length, - String projectName, IResource resource, - Collection<String> availableBundles) { - this.offset = offset; - this.length = length; - this.resource = resource; - this.projectName = projectName; + IJavaCompletionProposal { + + private int offset = 0; + private int length = 0; + private IResource resource; + private String reference; + private String projectName; + + public InsertResourceBundleReferenceProposal(int offset, int length, + String projectName, IResource resource, + Collection<String> availableBundles) { + this.offset = offset; + this.length = length; + this.resource = resource; + this.projectName = projectName; + } + + @Override + public void apply(IDocument document) { + ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog( + Display.getDefault().getActiveShell()); + dialog.setProjectName(projectName); + + if (dialog.open() != InputDialog.OK) { + return; } - @Override - public void apply(IDocument document) { - ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog( - Display.getDefault().getActiveShell()); - dialog.setProjectName(projectName); - - if (dialog.open() != InputDialog.OK) { - return; - } - - String resourceBundleId = dialog.getSelectedResourceBundle(); - String key = dialog.getSelectedResource(); - Locale locale = dialog.getSelectedLocale(); - - reference = ASTutilsUI.insertExistingBundleRef(document, resource, - offset, length, resourceBundleId, key, locale); - } - - @Override - public String getAdditionalProposalInfo() { - // TODO Auto-generated method stub - return null; - } - - @Override - public IContextInformation getContextInformation() { - return null; - } - - @Override - public String getDisplayString() { - return "Insert reference to a localized string literal"; - } - - @Override - public Image getImage() { - return PlatformUI.getWorkbench().getSharedImages() - .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage(); - } - - @Override - public Point getSelection(IDocument document) { - // TODO Auto-generated method stub - int referenceLength = reference == null ? 0 : reference.length(); - return new Point(offset + referenceLength, 0); - } - - @Override - public int getRelevance() { - // TODO Auto-generated method stub - if (this.length == 0) { - return 97; - } else { - return 1097; - } + String resourceBundleId = dialog.getSelectedResourceBundle(); + String key = dialog.getSelectedResource(); + Locale locale = dialog.getSelectedLocale(); + + reference = ASTutilsUI.insertExistingBundleRef(document, resource, + offset, length, resourceBundleId, key, locale); + } + + @Override + public String getAdditionalProposalInfo() { + // TODO Auto-generated method stub + return null; + } + + @Override + public IContextInformation getContextInformation() { + return null; + } + + @Override + public String getDisplayString() { + return "Insert reference to a localized string literal"; + } + + @Override + public Image getImage() { + return PlatformUI.getWorkbench().getSharedImages() + .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage(); + } + + @Override + public Point getSelection(IDocument document) { + // TODO Auto-generated method stub + int referenceLength = reference == null ? 0 : reference.length(); + return new Point(offset + referenceLength, 0); + } + + @Override + public int getRelevance() { + // TODO Auto-generated method stub + if (this.length == 0) { + return 97; + } else { + return 1097; } + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java index 75ecf676..a56d19c3 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/MessageCompletionProposal.java @@ -1,9 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 - initial API and implementation ******************************************************************************/ package org.eclipse.babel.tapiji.tools.java.ui.autocompletion; @@ -17,58 +20,58 @@ public class MessageCompletionProposal implements IJavaCompletionProposal { - private int offset = 0; - private int length = 0; - private String content = ""; - private boolean messageAccessor = false; + private int offset = 0; + private int length = 0; + private String content = ""; + private boolean messageAccessor = false; - public MessageCompletionProposal(int offset, int length, String content, - boolean messageAccessor) { - this.offset = offset; - this.length = length; - this.content = content; - this.messageAccessor = messageAccessor; - } + public MessageCompletionProposal(int offset, int length, String content, + boolean messageAccessor) { + this.offset = offset; + this.length = length; + this.content = content; + this.messageAccessor = messageAccessor; + } - @Override - public void apply(IDocument document) { - try { - document.replace(offset, length, content); - } catch (Exception e) { - Logger.logError(e); - } + @Override + public void apply(IDocument document) { + try { + document.replace(offset, length, content); + } catch (Exception e) { + Logger.logError(e); } + } - @Override - public String getAdditionalProposalInfo() { - return "Inserts the resource key '" + this.content + "'"; - } + @Override + public String getAdditionalProposalInfo() { + return "Inserts the resource key '" + this.content + "'"; + } - @Override - public IContextInformation getContextInformation() { - return null; - } + @Override + public IContextInformation getContextInformation() { + return null; + } - @Override - public String getDisplayString() { - return content; - } + @Override + public String getDisplayString() { + return content; + } - @Override - public Image getImage() { - if (messageAccessor) - return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE); - return ImageUtils.getImage(ImageUtils.IMAGE_PROPERTIES_FILE); - } + @Override + public Image getImage() { + if (messageAccessor) + return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE); + return ImageUtils.getImage(ImageUtils.IMAGE_PROPERTIES_FILE); + } - @Override - public Point getSelection(IDocument document) { - return new Point(offset + content.length() + 1, 0); - } + @Override + public Point getSelection(IDocument document) { + return new Point(offset + content.length() + 1, 0); + } - @Override - public int getRelevance() { - return 99; - } + @Override + public int getRelevance() { + return 99; + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java index 3cbe372e..6960fa36 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NewResourceBundleEntryProposal.java @@ -1,9 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 - initial API and implementation ******************************************************************************/ package org.eclipse.babel.tapiji.tools.java.ui.autocompletion; @@ -25,114 +28,114 @@ public class NewResourceBundleEntryProposal implements IJavaCompletionProposal { - private int startPos; - private int endPos; - private String value; - private boolean bundleContext; - private String projectName; - private IResource resource; - private String bundleName; - private String reference; - - public NewResourceBundleEntryProposal(IResource resource, int startPos, - int endPos, String value, boolean isStringLiteral, - boolean bundleContext, String projectName, String bundleName) { - - this.startPos = startPos; - this.endPos = endPos; - this.value = value; - this.bundleContext = bundleContext; - this.projectName = projectName; - this.resource = resource; - this.bundleName = bundleName; + private int startPos; + private int endPos; + private String value; + private boolean bundleContext; + private String projectName; + private IResource resource; + private String bundleName; + private String reference; + + public NewResourceBundleEntryProposal(IResource resource, int startPos, + int endPos, String value, boolean isStringLiteral, + boolean bundleContext, String projectName, String bundleName) { + + this.startPos = startPos; + this.endPos = endPos; + this.value = value; + this.bundleContext = bundleContext; + this.projectName = projectName; + this.resource = resource; + this.bundleName = bundleName; + } + + @Override + public void apply(IDocument document) { + + CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( + Display.getDefault().getActiveShell()); + + DialogConfiguration config = dialog.new DialogConfiguration(); + config.setPreselectedKey(bundleContext ? value : ""); + config.setPreselectedMessage(value); + config.setPreselectedBundle(bundleName == null ? "" : bundleName); + config.setPreselectedLocale(""); + config.setProjectName(projectName); + + dialog.setDialogConfiguration(config); + + if (dialog.open() != InputDialog.OK) { + return; } - @Override - public void apply(IDocument document) { - - CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( - Display.getDefault().getActiveShell()); - - DialogConfiguration config = dialog.new DialogConfiguration(); - config.setPreselectedKey(bundleContext ? value : ""); - config.setPreselectedMessage(value); - config.setPreselectedBundle(bundleName == null ? "" : bundleName); - config.setPreselectedLocale(""); - config.setProjectName(projectName); - - dialog.setDialogConfiguration(config); - - if (dialog.open() != InputDialog.OK) { - return; - } - - String resourceBundleId = dialog.getSelectedResourceBundle(); - String key = dialog.getSelectedKey(); - - try { - if (!bundleContext) { - reference = ASTutilsUI.insertNewBundleRef(document, resource, - startPos, endPos - startPos, resourceBundleId, key); - } else { - document.replace(startPos, endPos - startPos, key); - reference = key + "\""; - } - ResourceBundleManager.rebuildProject(resource); - } catch (Exception e) { - Logger.logError(e); - } + String resourceBundleId = dialog.getSelectedResourceBundle(); + String key = dialog.getSelectedKey(); + + try { + if (!bundleContext) { + reference = ASTutilsUI.insertNewBundleRef(document, resource, + startPos, endPos - startPos, resourceBundleId, key); + } else { + document.replace(startPos, endPos - startPos, key); + reference = key + "\""; + } + ResourceBundleManager.rebuildProject(resource); + } catch (Exception e) { + Logger.logError(e); } - - @Override - public String getAdditionalProposalInfo() { - if (value != null && value.length() > 0) { - return "Exports the focused string literal into a Java Resource-Bundle. This action results " - + "in a Resource-Bundle reference!"; - } else { - return ""; - } - } - - @Override - public IContextInformation getContextInformation() { - return null; - } - - @Override - public String getDisplayString() { - String displayStr = ""; - if (bundleContext) { - displayStr = "Create a new resource-bundle-entry"; - } else { - displayStr = "Create a new localized string literal"; - } - - if (value != null && value.length() > 0) { - displayStr += " for '" + value + "'"; - } - - return displayStr; + } + + @Override + public String getAdditionalProposalInfo() { + if (value != null && value.length() > 0) { + return "Exports the focused string literal into a Java Resource-Bundle. This action results " + + "in a Resource-Bundle reference!"; + } else { + return ""; } - - @Override - public Image getImage() { - return PlatformUI.getWorkbench().getSharedImages() - .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage(); + } + + @Override + public IContextInformation getContextInformation() { + return null; + } + + @Override + public String getDisplayString() { + String displayStr = ""; + if (bundleContext) { + displayStr = "Create a new resource-bundle-entry"; + } else { + displayStr = "Create a new localized string literal"; } - @Override - public Point getSelection(IDocument document) { - int refLength = reference == null ? 0 : reference.length() - 1; - return new Point(startPos + refLength, 0); + if (value != null && value.length() > 0) { + displayStr += " for '" + value + "'"; } - @Override - public int getRelevance() { - if (this.value.trim().length() == 0) { - return 96; - } else { - return 1096; - } + return displayStr; + } + + @Override + public Image getImage() { + return PlatformUI.getWorkbench().getSharedImages() + .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage(); + } + + @Override + public Point getSelection(IDocument document) { + int refLength = reference == null ? 0 : reference.length() - 1; + return new Point(startPos + refLength, 0); + } + + @Override + public int getRelevance() { + if (this.value.trim().length() == 0) { + return 96; + } else { + return 1096; } + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java index f16c4cd6..1af9bca7 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/NoActionProposal.java @@ -1,9 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 - initial API and implementation ******************************************************************************/ package org.eclipse.babel.tapiji.tools.java.ui.autocompletion; @@ -15,50 +18,50 @@ public class NoActionProposal implements IJavaCompletionProposal { - public NoActionProposal() { - super(); - } + public NoActionProposal() { + super(); + } - @Override - public void apply(IDocument document) { - // TODO Auto-generated method stub + @Override + public void apply(IDocument document) { + // TODO Auto-generated method stub - } + } - @Override - public String getAdditionalProposalInfo() { - // TODO Auto-generated method stub - return null; - } + @Override + public String getAdditionalProposalInfo() { + // TODO Auto-generated method stub + return null; + } - @Override - public IContextInformation getContextInformation() { - // TODO Auto-generated method stub - return null; - } + @Override + public IContextInformation getContextInformation() { + // TODO Auto-generated method stub + return null; + } - @Override - public String getDisplayString() { - // TODO Auto-generated method stub - return "No Default Proposals"; - } + @Override + public String getDisplayString() { + // TODO Auto-generated method stub + return "No Default Proposals"; + } - @Override - public Image getImage() { - // TODO Auto-generated method stub - return null; - } + @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 Point getSelection(IDocument document) { + // TODO Auto-generated method stub + return null; + } - @Override - public int getRelevance() { - // TODO Auto-generated method stub - return 100; - } + @Override + public int getRelevance() { + // TODO Auto-generated method stub + return 100; + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java index 2961808c..4c35d723 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/autocompletion/Sorter.java @@ -1,9 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 - initial API and implementation ******************************************************************************/ package org.eclipse.babel.tapiji.tools.java.ui.autocompletion; @@ -13,32 +16,32 @@ public class Sorter extends AbstractProposalSorter { - public Sorter() { - } + public Sorter() { + } - @Override - public void beginSorting(ContentAssistInvocationContext context) { - // TODO Auto-generated method stub - super.beginSorting(context); - } + @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); - } + @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; - } + 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.ui/src/org/eclipse/babel/tapiji/tools/java/ui/model/SLLocation.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/model/SLLocation.java index 3fb44e82..3e2ddc97 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/model/SLLocation.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/model/SLLocation.java @@ -1,9 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 - initial API and implementation ******************************************************************************/ package org.eclipse.babel.tapiji.tools.java.ui.model; @@ -14,60 +17,60 @@ public class SLLocation implements Serializable, ILocation { - private static final long serialVersionUID = 1L; - private IFile file = null; - private int startPos = -1; - private int endPos = -1; - private String literal; - private Serializable data; + private static final long serialVersionUID = 1L; + private IFile file = null; + private int startPos = -1; + private int endPos = -1; + private String literal; + private Serializable data; - public SLLocation(IFile file, int startPos, int endPos, String literal) { - super(); - this.file = file; - this.startPos = startPos; - this.endPos = endPos; - this.literal = literal; - } + public SLLocation(IFile file, int startPos, int endPos, String literal) { + super(); + this.file = file; + this.startPos = startPos; + this.endPos = endPos; + this.literal = literal; + } - @Override - public IFile getFile() { - return file; - } + @Override + public IFile getFile() { + return file; + } - public void setFile(IFile file) { - this.file = file; - } + public void setFile(IFile file) { + this.file = file; + } - @Override - public int getStartPos() { - return startPos; - } + @Override + public int getStartPos() { + return startPos; + } - public void setStartPos(int startPos) { - this.startPos = startPos; - } + public void setStartPos(int startPos) { + this.startPos = startPos; + } - @Override - public int getEndPos() { - return endPos; - } + @Override + public int getEndPos() { + return endPos; + } - public void setEndPos(int endPos) { - this.endPos = endPos; - } + public void setEndPos(int endPos) { + this.endPos = endPos; + } - @Override - public String getLiteral() { - return literal; - } + @Override + public String getLiteral() { + return literal; + } - @Override - public Serializable getData() { - return data; - } + @Override + public Serializable getData() { + return data; + } - public void setData(Serializable data) { - this.data = data; - } + public void setData(Serializable data) { + this.data = data; + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExcludeResourceFromInternationalization.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExcludeResourceFromInternationalization.java index 1b394ed4..75e71b8c 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExcludeResourceFromInternationalization.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExcludeResourceFromInternationalization.java @@ -1,9 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 - initial API and implementation ******************************************************************************/ package org.eclipse.babel.tapiji.tools.java.ui.quickfix; @@ -19,48 +22,48 @@ import org.eclipse.ui.progress.IProgressService; public class ExcludeResourceFromInternationalization implements - IMarkerResolution2 { + IMarkerResolution2 { - @Override - public String getLabel() { - return "Exclude Resource"; - } + @Override + public String getLabel() { + return "Exclude Resource"; + } - @Override - public void run(IMarker marker) { - final IResource resource = marker.getResource(); + @Override + public void run(IMarker marker) { + final IResource resource = marker.getResource(); - IWorkbench wb = PlatformUI.getWorkbench(); - IProgressService ps = wb.getProgressService(); - try { - ps.busyCursorWhile(new IRunnableWithProgress() { - public void run(IProgressMonitor pm) { + IWorkbench wb = PlatformUI.getWorkbench(); + IProgressService ps = wb.getProgressService(); + try { + ps.busyCursorWhile(new IRunnableWithProgress() { + public void run(IProgressMonitor pm) { - ResourceBundleManager manager = null; - pm.beginTask( - "Excluding Resource from Internationalization", 1); + ResourceBundleManager manager = null; + pm.beginTask( + "Excluding Resource from Internationalization", 1); - if (manager == null - || (manager.getProject() != resource.getProject())) - manager = ResourceBundleManager.getManager(resource - .getProject()); - manager.excludeResource(resource, pm); - pm.worked(1); - pm.done(); - } - }); - } catch (Exception e) { + if (manager == null + || (manager.getProject() != resource.getProject())) + manager = ResourceBundleManager.getManager(resource + .getProject()); + manager.excludeResource(resource, pm); + pm.worked(1); + pm.done(); } + }); + } catch (Exception e) { } + } - @Override - public String getDescription() { - return "Exclude Resource from Internationalization"; - } + @Override + public String getDescription() { + return "Exclude Resource from Internationalization"; + } - @Override - public Image getImage() { - return null; - } + @Override + public Image getImage() { + return null; + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java index a325404b..e55f10f8 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ExportToResourceBundleResolution.java @@ -1,9 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 - initial API and implementation ******************************************************************************/ package org.eclipse.babel.tapiji.tools.java.ui.quickfix; @@ -26,70 +29,72 @@ public class ExportToResourceBundleResolution implements IMarkerResolution2 { - public ExportToResourceBundleResolution() { + public ExportToResourceBundleResolution() { + } + + @Override + public String getDescription() { + return "Export constant string literal to a resource bundle."; + } + + @Override + public Image getImage() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getLabel() { + return "Export to Resource-Bundle"; + } + + @Override + public void run(IMarker marker) { + int startPos = marker.getAttribute(IMarker.CHAR_START, 0); + int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos; + IResource resource = marker.getResource(); + + ITextFileBufferManager bufferManager = FileBuffers + .getTextFileBufferManager(); + IPath path = resource.getRawLocation(); + try { + bufferManager.connect(path, LocationKind.NORMALIZE, null); + ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer( + path, LocationKind.NORMALIZE); + IDocument document = textFileBuffer.getDocument(); + + CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( + Display.getDefault().getActiveShell()); + + DialogConfiguration config = dialog.new DialogConfiguration(); + config.setPreselectedKey(""); + config.setPreselectedMessage(""); + config.setPreselectedBundle((startPos + 1 < document.getLength() && endPos > 1) ? document + .get(startPos + 1, endPos - 2) : ""); + config.setPreselectedLocale(""); + config.setProjectName(resource.getProject().getName()); + + dialog.setDialogConfiguration(config); + + if (dialog.open() != InputDialog.OK) + return; + + ASTutilsUI + .insertNewBundleRef(document, resource, startPos, endPos, + dialog.getSelectedResourceBundle(), + dialog.getSelectedKey()); + + textFileBuffer.commit(null, false); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + bufferManager.disconnect(path, null); + } catch (CoreException e) { + e.printStackTrace(); + } } - @Override - public String getDescription() { - return "Export constant string literal to a resource bundle."; - } - - @Override - public Image getImage() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getLabel() { - return "Export to Resource-Bundle"; - } - - @Override - public void run(IMarker marker) { - int startPos = marker.getAttribute(IMarker.CHAR_START, 0); - int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos; - IResource resource = marker.getResource(); - - ITextFileBufferManager bufferManager = FileBuffers - .getTextFileBufferManager(); - IPath path = resource.getRawLocation(); - try { - bufferManager.connect(path, LocationKind.NORMALIZE, null); - ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer( - path, LocationKind.NORMALIZE); - IDocument document = textFileBuffer.getDocument(); - - CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( - Display.getDefault().getActiveShell()); - - DialogConfiguration config = dialog.new DialogConfiguration(); - config.setPreselectedKey(""); - config.setPreselectedMessage(""); - config.setPreselectedBundle((startPos + 1 < document.getLength() && endPos > 1) ? document - .get(startPos + 1, endPos - 2) : ""); - config.setPreselectedLocale(""); - config.setProjectName(resource.getProject().getName()); - - dialog.setDialogConfiguration(config); - - if (dialog.open() != InputDialog.OK) - return; - - ASTutilsUI.insertNewBundleRef(document, resource, startPos, endPos, - dialog.getSelectedResourceBundle(), dialog.getSelectedKey()); - - textFileBuffer.commit(null, false); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - bufferManager.disconnect(path, null); - } catch (CoreException e) { - e.printStackTrace(); - } - } - - } + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/IgnoreStringFromInternationalization.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/IgnoreStringFromInternationalization.java index 6cf88284..ce3b10b1 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/IgnoreStringFromInternationalization.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/IgnoreStringFromInternationalization.java @@ -1,9 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 - initial API and implementation ******************************************************************************/ package org.eclipse.babel.tapiji.tools.java.ui.quickfix; @@ -26,50 +29,50 @@ public class IgnoreStringFromInternationalization implements IMarkerResolution2 { - @Override - public String getLabel() { - return "Ignore String"; - } - - @Override - public void run(IMarker marker) { - IResource resource = marker.getResource(); + @Override + public String getLabel() { + return "Ignore String"; + } - CompilationUnit cu = ASTutilsUI.getCompilationUnit(resource); + @Override + public void run(IMarker marker) { + IResource resource = marker.getResource(); - ITextFileBufferManager bufferManager = FileBuffers - .getTextFileBufferManager(); - IPath path = resource.getRawLocation(); + CompilationUnit cu = ASTutilsUI.getCompilationUnit(resource); - try { - bufferManager.connect(path, LocationKind.NORMALIZE, null); - ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer( - path, LocationKind.NORMALIZE); - IDocument document = textFileBuffer.getDocument(); + ITextFileBufferManager bufferManager = FileBuffers + .getTextFileBufferManager(); + IPath path = resource.getRawLocation(); - int position = marker.getAttribute(IMarker.CHAR_START, 0); + try { + bufferManager.connect(path, LocationKind.NORMALIZE, null); + ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer( + path, LocationKind.NORMALIZE); + IDocument document = textFileBuffer.getDocument(); - ASTutils.createReplaceNonInternationalisationComment(cu, document, - position); - textFileBuffer.commit(null, false); + int position = marker.getAttribute(IMarker.CHAR_START, 0); - } catch (JavaModelException e) { - Logger.logError(e); - } catch (CoreException e) { - Logger.logError(e); - } + ASTutils.createReplaceNonInternationalisationComment(cu, document, + position); + textFileBuffer.commit(null, false); + } catch (JavaModelException e) { + Logger.logError(e); + } catch (CoreException e) { + Logger.logError(e); } - @Override - public String getDescription() { - return "Ignore String from Internationalization"; - } + } - @Override - public Image getImage() { - // TODO Auto-generated method stub - return null; - } + @Override + public String getDescription() { + return "Ignore String from Internationalization"; + } + + @Override + public Image getImage() { + // TODO Auto-generated method stub + return null; + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java index 5cc5bd0f..2fa6cfc7 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleDefReference.java @@ -1,9 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 - initial API and implementation ******************************************************************************/ package org.eclipse.babel.tapiji.tools.java.ui.quickfix; @@ -24,71 +27,71 @@ public class ReplaceResourceBundleDefReference implements IMarkerResolution2 { - private String key; - private int start; - private int end; + private String key; + private int start; + private int end; - public ReplaceResourceBundleDefReference(String key, int start, int end) { - this.key = key; - this.start = start; - this.end = end; - } + public ReplaceResourceBundleDefReference(String key, int start, int end) { + this.key = key; + this.start = start; + this.end = end; + } - @Override - public String getDescription() { - return "Replaces the non-existing Resource-Bundle reference '" + key - + "' with a reference to an already existing Resource-Bundle."; - } + @Override + public String getDescription() { + return "Replaces the non-existing Resource-Bundle reference '" + key + + "' with a reference to an already existing Resource-Bundle."; + } - @Override - public Image getImage() { - // TODO Auto-generated method stub - return null; - } + @Override + public Image getImage() { + // TODO Auto-generated method stub + return null; + } - @Override - public String getLabel() { - return "Select an alternative Resource-Bundle"; - } + @Override + public String getLabel() { + return "Select an alternative Resource-Bundle"; + } - @Override - public void run(IMarker marker) { - int startPos = start; - int endPos = end - start; - IResource resource = marker.getResource(); + @Override + public void run(IMarker marker) { + int startPos = start; + int endPos = end - start; + IResource resource = marker.getResource(); - ITextFileBufferManager bufferManager = FileBuffers - .getTextFileBufferManager(); - IPath path = resource.getRawLocation(); - try { - bufferManager.connect(path, LocationKind.NORMALIZE, null); - ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer( - path, LocationKind.NORMALIZE); - IDocument document = textFileBuffer.getDocument(); + ITextFileBufferManager bufferManager = FileBuffers + .getTextFileBufferManager(); + IPath path = resource.getRawLocation(); + try { + bufferManager.connect(path, LocationKind.NORMALIZE, null); + ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer( + path, LocationKind.NORMALIZE); + IDocument document = textFileBuffer.getDocument(); - ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog( - Display.getDefault().getActiveShell(), - resource.getProject()); + ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog( + Display.getDefault().getActiveShell(), + resource.getProject()); - if (dialog.open() != InputDialog.OK) - return; + if (dialog.open() != InputDialog.OK) + return; - key = dialog.getSelectedBundleId(); - int iSep = key.lastIndexOf("/"); - key = iSep != -1 ? key.substring(iSep + 1) : key; + key = dialog.getSelectedBundleId(); + int iSep = key.lastIndexOf("/"); + key = iSep != -1 ? key.substring(iSep + 1) : key; - document.replace(startPos, endPos, "\"" + key + "\""); + document.replace(startPos, endPos, "\"" + key + "\""); - textFileBuffer.commit(null, false); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - bufferManager.disconnect(path, LocationKind.NORMALIZE, null); - } catch (CoreException e) { - e.printStackTrace(); - } - } + textFileBuffer.commit(null, false); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + bufferManager.disconnect(path, LocationKind.NORMALIZE, null); + } catch (CoreException e) { + e.printStackTrace(); + } } + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java index f75cf058..f0eaedc3 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/quickfix/ReplaceResourceBundleReference.java @@ -1,9 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 - initial API and implementation ******************************************************************************/ package org.eclipse.babel.tapiji.tools.java.ui.quickfix; @@ -26,70 +29,70 @@ public class ReplaceResourceBundleReference implements IMarkerResolution2 { - private String key; - private String bundleId; - - public ReplaceResourceBundleReference(String key, String bundleId) { - this.key = key; - this.bundleId = bundleId; - } - - @Override - public String getDescription() { - return "Replaces the non-existing Resource-Bundle key '" - + key - + "' with a reference to an already existing localized string literal."; - } - - @Override - public Image getImage() { - return null; - } - - @Override - public String getLabel() { - return "Select alternative Resource-Bundle entry"; - } - - @Override - public void run(IMarker marker) { - int startPos = marker.getAttribute(IMarker.CHAR_START, 0); - int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos; - IResource resource = marker.getResource(); - - ITextFileBufferManager bufferManager = FileBuffers - .getTextFileBufferManager(); - IPath path = resource.getRawLocation(); - try { - bufferManager.connect(path, LocationKind.NORMALIZE, null); - ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer( - path, LocationKind.NORMALIZE); - IDocument document = textFileBuffer.getDocument(); - - ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog( - Display.getDefault().getActiveShell()); - - dialog.setProjectName(resource.getProject().getName()); - dialog.setBundleName(bundleId); - - if (dialog.open() != InputDialog.OK) - return; - - String key = dialog.getSelectedResource(); - Locale locale = dialog.getSelectedLocale(); - - document.replace(startPos, endPos, "\"" + key + "\""); - - textFileBuffer.commit(null, false); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - bufferManager.disconnect(path, LocationKind.NORMALIZE, null); - } catch (CoreException e) { - e.printStackTrace(); - } - } + private String key; + private String bundleId; + + public ReplaceResourceBundleReference(String key, String bundleId) { + this.key = key; + this.bundleId = bundleId; + } + + @Override + public String getDescription() { + return "Replaces the non-existing Resource-Bundle key '" + + key + + "' with a reference to an already existing localized string literal."; + } + + @Override + public Image getImage() { + return null; + } + + @Override + public String getLabel() { + return "Select alternative Resource-Bundle entry"; + } + + @Override + public void run(IMarker marker) { + int startPos = marker.getAttribute(IMarker.CHAR_START, 0); + int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos; + IResource resource = marker.getResource(); + + ITextFileBufferManager bufferManager = FileBuffers + .getTextFileBufferManager(); + IPath path = resource.getRawLocation(); + try { + bufferManager.connect(path, LocationKind.NORMALIZE, null); + ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer( + path, LocationKind.NORMALIZE); + IDocument document = textFileBuffer.getDocument(); + + ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog( + Display.getDefault().getActiveShell()); + + dialog.setProjectName(resource.getProject().getName()); + dialog.setBundleName(bundleId); + + if (dialog.open() != InputDialog.OK) + return; + + String key = dialog.getSelectedResource(); + Locale locale = dialog.getSelectedLocale(); + + document.replace(startPos, endPos, "\"" + key + "\""); + + textFileBuffer.commit(null, false); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + bufferManager.disconnect(path, LocationKind.NORMALIZE, null); + } catch (CoreException e) { + e.printStackTrace(); + } } + } } diff --git a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/util/ASTutilsUI.java b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/util/ASTutilsUI.java index 8b96bc7d..0c1ad87c 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/util/ASTutilsUI.java +++ b/org.eclipse.babel.tapiji.tools.java.ui/src/org/eclipse/babel/tapiji/tools/java/ui/util/ASTutilsUI.java @@ -1,12 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * * Contributors: - * Martin Reiterer - initial API and implementation + * Contributors: + * Martin Reiterer - initial API and implementation * Alexej Strelzow - seperation of ui/non-ui (methods moved from ASTUtils) ******************************************************************************/ @@ -27,124 +27,126 @@ public class ASTutilsUI { - public static CompilationUnit getCompilationUnit(IResource resource) { - IJavaElement je = JavaCore.create(resource, - JavaCore.create(resource.getProject())); - // get the type of the currently loaded resource - ITypeRoot typeRoot = ((ICompilationUnit) je); + public static CompilationUnit getCompilationUnit(IResource resource) { + IJavaElement je = JavaCore.create(resource, + JavaCore.create(resource.getProject())); + // get the type of the currently loaded resource + ITypeRoot typeRoot = ((ICompilationUnit) je); - if (typeRoot == null) { - return null; - } + if (typeRoot == null) { + return null; + } + + return getCompilationUnit(typeRoot); + } + + public static CompilationUnit getCompilationUnit(ITypeRoot typeRoot) { + // get a reference to the shared AST of the loaded CompilationUnit + CompilationUnit cu = SharedASTProvider.getAST(typeRoot, + // do not wait for AST creation + SharedASTProvider.WAIT_YES, null); + + return cu; + } + + public static String insertNewBundleRef(IDocument document, + IResource resource, int startPos, int endPos, + String resourceBundleId, String key) { + String newName = null; + String reference = ""; + + CompilationUnit cu = getCompilationUnit(resource); - return getCompilationUnit(typeRoot); + if (cu == null) { + return null; } - public static CompilationUnit getCompilationUnit(ITypeRoot typeRoot) { - // get a reference to the shared AST of the loaded CompilationUnit - CompilationUnit cu = SharedASTProvider.getAST(typeRoot, - // do not wait for AST creation - SharedASTProvider.WAIT_YES, null); + String variableName = ASTutils.resolveRBReferenceVar(document, + resource, startPos, resourceBundleId, cu); + if (variableName == null) { + newName = ASTutils.getNonExistingRBRefName(resourceBundleId, + document, cu); + } - return cu; + try { + reference = ASTutils.createResourceReference(resourceBundleId, key, + null, resource, startPos, variableName == null ? newName + : variableName, document, cu); + + if (startPos > 0 && document.get().charAt(startPos - 1) == '\"') { + startPos--; + endPos++; + } + + if ((startPos + endPos) < document.getLength() + && document.get().charAt(startPos + endPos) == '\"') { + endPos++; + } + + if ((startPos + endPos) < document.getLength() + && document.get().charAt(startPos + endPos - 1) == ';') { + endPos--; + } + + document.replace(startPos, endPos, reference); + + // create non-internationalisation-comment + ASTutils.createReplaceNonInternationalisationComment(cu, document, + startPos); + } catch (BadLocationException e) { + e.printStackTrace(); } - - public static String insertNewBundleRef(IDocument document, - IResource resource, int startPos, int endPos, - String resourceBundleId, String key) { - String newName = null; - String reference = ""; - - CompilationUnit cu = getCompilationUnit(resource); - - if (cu == null) { - return null; - } - - String variableName = ASTutils.resolveRBReferenceVar(document, - resource, startPos, resourceBundleId, cu); - if (variableName == null) { - newName = ASTutils.getNonExistingRBRefName(resourceBundleId, - document, cu); - } - - try { - reference = ASTutils.createResourceReference(resourceBundleId, key, - null, resource, startPos, variableName == null ? newName - : variableName, document, cu); - - if (startPos > 0 && document.get().charAt(startPos - 1) == '\"') { - startPos--; - endPos++; - } - - if ((startPos + endPos) < document.getLength() - && document.get().charAt(startPos + endPos) == '\"') { - endPos++; - } - - if ((startPos + endPos) < document.getLength() - && document.get().charAt(startPos + endPos - 1) == ';') { - endPos--; - } - - document.replace(startPos, endPos, reference); - - // create non-internationalisation-comment - ASTutils.createReplaceNonInternationalisationComment(cu, document, startPos); - } catch (BadLocationException e) { - e.printStackTrace(); - } - - if (variableName == null) { - // refresh reference to the shared AST of the loaded CompilationUnit - cu = getCompilationUnit(resource); - - ASTutils.createResourceBundleReference(resource, startPos, - document, resourceBundleId, null, true, newName, cu); - // createReplaceNonInternationalisationComment(cu, document, pos); - } - - return reference; + + if (variableName == null) { + // refresh reference to the shared AST of the loaded CompilationUnit + cu = getCompilationUnit(resource); + + ASTutils.createResourceBundleReference(resource, startPos, + document, resourceBundleId, null, true, newName, cu); + // createReplaceNonInternationalisationComment(cu, document, pos); } - - public static String insertExistingBundleRef(IDocument document, - IResource resource, int offset, int length, - String resourceBundleId, String key, Locale locale) { - String reference = ""; - String newName = null; - - CompilationUnit cu = getCompilationUnit(resource); - - String variableName = ASTutils.resolveRBReferenceVar(document, - resource, offset, resourceBundleId, cu); - if (variableName == null) { - newName = ASTutils.getNonExistingRBRefName(resourceBundleId, - document, cu); - } - - try { - reference = ASTutils.createResourceReference(resourceBundleId, key, - locale, resource, offset, variableName == null ? newName - : variableName, document, cu); - - document.replace(offset, length, reference); - - // create non-internationalisation-comment - ASTutils.createReplaceNonInternationalisationComment(cu, document, offset); - } catch (BadLocationException e) { - e.printStackTrace(); - } - - // TODO retrieve cu in the same way as in createResourceReference - // the current version does not parse method bodies - - if (variableName == null) { - ASTutils.createResourceBundleReference(resource, offset, document, - resourceBundleId, locale, true, newName, cu); - // createReplaceNonInternationalisationComment(cu, document, pos); - } - return reference; + + return reference; + } + + public static String insertExistingBundleRef(IDocument document, + IResource resource, int offset, int length, + String resourceBundleId, String key, Locale locale) { + String reference = ""; + String newName = null; + + CompilationUnit cu = getCompilationUnit(resource); + + String variableName = ASTutils.resolveRBReferenceVar(document, + resource, offset, resourceBundleId, cu); + if (variableName == null) { + newName = ASTutils.getNonExistingRBRefName(resourceBundleId, + document, cu); + } + + try { + reference = ASTutils.createResourceReference(resourceBundleId, key, + locale, resource, offset, variableName == null ? newName + : variableName, document, cu); + + document.replace(offset, length, reference); + + // create non-internationalisation-comment + ASTutils.createReplaceNonInternationalisationComment(cu, document, + offset); + } catch (BadLocationException e) { + e.printStackTrace(); } - + + // TODO retrieve cu in the same way as in createResourceReference + // the current version does not parse method bodies + + if (variableName == null) { + ASTutils.createResourceBundleReference(resource, offset, document, + resourceBundleId, locale, true, newName, cu); + // createReplaceNonInternationalisationComment(cu, document, pos); + } + return reference; + } + } diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java index 7d912328..e89b5cac 100644 --- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java +++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/util/ASTutils.java @@ -1,12 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Martin Reiterer, Alexej Strelzow. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * - * * Contributors: - * Martin Reiterer - initial API and implementation + * Contributors: + * Martin Reiterer - initial API and implementation * Alexej Strelzow - seperation of ui/non-ui ******************************************************************************/ package org.eclipse.babel.tapiji.tools.java.util; @@ -54,890 +54,891 @@ public class ASTutils { - private static MethodParameterDescriptor rbDefinition; - private static MethodParameterDescriptor rbAccessor; + private static MethodParameterDescriptor rbDefinition; + private static MethodParameterDescriptor rbAccessor; - public static MethodParameterDescriptor getRBDefinitionDesc() { - if (rbDefinition == null) { - // Init descriptor for Resource-Bundle-Definition - List<String> definition = new ArrayList<String>(); - definition.add("getBundle"); - rbDefinition = new MethodParameterDescriptor(definition, - "java.util.ResourceBundle", true, 0); - } + public static MethodParameterDescriptor getRBDefinitionDesc() { + if (rbDefinition == null) { + // Init descriptor for Resource-Bundle-Definition + List<String> definition = new ArrayList<String>(); + definition.add("getBundle"); + rbDefinition = new MethodParameterDescriptor(definition, + "java.util.ResourceBundle", true, 0); + } - return rbDefinition; + return rbDefinition; + } + + public static MethodParameterDescriptor getRBAccessorDesc() { + if (rbAccessor == null) { + // Init descriptor for Resource-Bundle-Accessors + List<String> accessors = new ArrayList<String>(); + accessors.add("getString"); + accessors.add("getStringArray"); + rbAccessor = new MethodParameterDescriptor(accessors, + "java.util.ResourceBundle", true, 0); } - public static MethodParameterDescriptor getRBAccessorDesc() { - if (rbAccessor == null) { - // Init descriptor for Resource-Bundle-Accessors - List<String> accessors = new ArrayList<String>(); - accessors.add("getString"); - accessors.add("getStringArray"); - rbAccessor = new MethodParameterDescriptor(accessors, - "java.util.ResourceBundle", true, 0); - } + return rbAccessor; + } + + public static String resolveRBReferenceVar(IDocument document, + IResource resource, int pos, final String bundleId, + CompilationUnit cu) { + String bundleVar; + + PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos); + cu.accept(typeFinder); + AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType(); + TypeDeclaration td = typeFinder.getEnclosingType(); + MethodDeclaration meth = typeFinder.getEnclosingMethod(); + + if (atd == null) { + BundleDeclarationFinder bdf = new BundleDeclarationFinder( + bundleId, + td, + meth != null + && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC); + td.accept(bdf); + + bundleVar = bdf.getVariableName(); + } else { + BundleDeclarationFinder bdf = new BundleDeclarationFinder( + bundleId, + atd, + meth != null + && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC); + atd.accept(bdf); + + bundleVar = bdf.getVariableName(); + } - return rbAccessor; + // Check also method body + if (meth != null) { + try { + InMethodBundleDeclFinder imbdf = new InMethodBundleDeclFinder( + bundleId, pos); + typeFinder.getEnclosingMethod().accept(imbdf); + bundleVar = imbdf.getVariableName() != null ? imbdf + .getVariableName() : bundleVar; + } catch (Exception e) { + // ignore + } } - public static String resolveRBReferenceVar(IDocument document, - IResource resource, int pos, final String bundleId, - CompilationUnit cu) { - String bundleVar; + return bundleVar; + } - PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos); - cu.accept(typeFinder); - AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType(); - TypeDeclaration td = typeFinder.getEnclosingType(); - MethodDeclaration meth = typeFinder.getEnclosingMethod(); + public static String getNonExistingRBRefName(String bundleId, + IDocument document, CompilationUnit cu) { + String referenceName = null; + int i = 0; - if (atd == null) { - BundleDeclarationFinder bdf = new BundleDeclarationFinder( - bundleId, - td, - meth != null - && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC); - td.accept(bdf); + while (referenceName == null) { + String actRef = bundleId.substring(bundleId.lastIndexOf(".") + 1) + + "Ref" + (i == 0 ? "" : i); + actRef = actRef.toLowerCase(); - bundleVar = bdf.getVariableName(); - } else { - BundleDeclarationFinder bdf = new BundleDeclarationFinder( - bundleId, - atd, - meth != null - && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC); - atd.accept(bdf); - - bundleVar = bdf.getVariableName(); - } + VariableFinder vf = new VariableFinder(actRef); + cu.accept(vf); - // Check also method body - if (meth != null) { - try { - InMethodBundleDeclFinder imbdf = new InMethodBundleDeclFinder( - bundleId, pos); - typeFinder.getEnclosingMethod().accept(imbdf); - bundleVar = imbdf.getVariableName() != null ? imbdf - .getVariableName() : bundleVar; - } catch (Exception e) { - // ignore - } - } + if (!vf.isVariableFound()) { + referenceName = actRef; + break; + } - return bundleVar; + i++; } - public static String getNonExistingRBRefName(String bundleId, - IDocument document, CompilationUnit cu) { - String referenceName = null; - int i = 0; + return referenceName; + } + + @Deprecated + public static String resolveResourceBundle( + MethodInvocation methodInvocation, + MethodParameterDescriptor rbDefinition, + Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) { + String bundleName = null; - while (referenceName == null) { - String actRef = bundleId.substring(bundleId.lastIndexOf(".") + 1) - + "Ref" + (i == 0 ? "" : i); - actRef = actRef.toLowerCase(); + if (methodInvocation.getExpression() instanceof SimpleName) { + SimpleName vName = (SimpleName) methodInvocation.getExpression(); + IVariableBinding vBinding = (IVariableBinding) vName + .resolveBinding(); + VariableDeclarationFragment dec = variableBindingManagers + .get(vBinding); - VariableFinder vf = new VariableFinder(actRef); - cu.accept(vf); + if (dec.getInitializer() instanceof MethodInvocation) { + MethodInvocation init = (MethodInvocation) dec.getInitializer(); - if (!vf.isVariableFound()) { - referenceName = actRef; - break; + // Check declaring class + boolean isValidClass = false; + ITypeBinding type = init.resolveMethodBinding() + .getDeclaringClass(); + while (type != null) { + if (type.getQualifiedName().equals( + rbDefinition.getDeclaringClass())) { + isValidClass = true; + break; + } else { + if (rbDefinition.isConsiderSuperclass()) { + type = type.getSuperclass(); + } else { + type = null; } + } - i++; } - - return referenceName; - } - - @Deprecated - public static String resolveResourceBundle( - MethodInvocation methodInvocation, - MethodParameterDescriptor rbDefinition, - Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) { - String bundleName = null; - - if (methodInvocation.getExpression() instanceof SimpleName) { - SimpleName vName = (SimpleName) methodInvocation.getExpression(); - IVariableBinding vBinding = (IVariableBinding) vName - .resolveBinding(); - VariableDeclarationFragment dec = variableBindingManagers - .get(vBinding); - - if (dec.getInitializer() instanceof MethodInvocation) { - MethodInvocation init = (MethodInvocation) dec.getInitializer(); - - // Check declaring class - boolean isValidClass = false; - ITypeBinding type = init.resolveMethodBinding() - .getDeclaringClass(); - while (type != null) { - if (type.getQualifiedName().equals( - rbDefinition.getDeclaringClass())) { - isValidClass = true; - break; - } else { - if (rbDefinition.isConsiderSuperclass()) { - type = type.getSuperclass(); - } else { - type = null; - } - } - - } - if (!isValidClass) { - return null; - } - - boolean isValidMethod = false; - for (String mn : rbDefinition.getMethodName()) { - if (init.getName().getFullyQualifiedName().equals(mn)) { - isValidMethod = true; - break; - } - } - if (!isValidMethod) { - return null; - } - - // retrieve bundlename - if (init.arguments().size() < rbDefinition.getPosition() + 1) { - return null; - } - - bundleName = ((StringLiteral) init.arguments().get( - rbDefinition.getPosition())).getLiteralValue(); - } + if (!isValidClass) { + return null; } - return bundleName; - } - - public static SLLocation resolveResourceBundleLocation( - MethodInvocation methodInvocation, - MethodParameterDescriptor rbDefinition, - Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) { - SLLocation bundleDesc = null; - - if (methodInvocation.getExpression() instanceof SimpleName) { - SimpleName vName = (SimpleName) methodInvocation.getExpression(); - IVariableBinding vBinding = (IVariableBinding) vName - .resolveBinding(); - VariableDeclarationFragment dec = variableBindingManagers - .get(vBinding); - - if (dec.getInitializer() instanceof MethodInvocation) { - MethodInvocation init = (MethodInvocation) dec.getInitializer(); - - // Check declaring class - boolean isValidClass = false; - ITypeBinding type = init.resolveMethodBinding() - .getDeclaringClass(); - while (type != null) { - if (type.getQualifiedName().equals( - rbDefinition.getDeclaringClass())) { - isValidClass = true; - break; - } else { - if (rbDefinition.isConsiderSuperclass()) { - type = type.getSuperclass(); - } else { - type = null; - } - } - - } - if (!isValidClass) { - return null; - } - - boolean isValidMethod = false; - for (String mn : rbDefinition.getMethodName()) { - if (init.getName().getFullyQualifiedName().equals(mn)) { - isValidMethod = true; - break; - } - } - if (!isValidMethod) { - return null; - } - - // retrieve bundlename - if (init.arguments().size() < rbDefinition.getPosition() + 1) { - return null; - } + boolean isValidMethod = false; + for (String mn : rbDefinition.getMethodName()) { + if (init.getName().getFullyQualifiedName().equals(mn)) { + isValidMethod = true; + break; + } + } + if (!isValidMethod) { + return null; + } - StringLiteral bundleLiteral = ((StringLiteral) init.arguments() - .get(rbDefinition.getPosition())); - bundleDesc = new SLLocation(null, - bundleLiteral.getStartPosition(), - bundleLiteral.getLength() - + bundleLiteral.getStartPosition(), - bundleLiteral.getLiteralValue()); - } + // retrieve bundlename + if (init.arguments().size() < rbDefinition.getPosition() + 1) { + return null; } - return bundleDesc; + bundleName = ((StringLiteral) init.arguments().get( + rbDefinition.getPosition())).getLiteralValue(); + } } - private static boolean isMatchingMethodDescriptor( - MethodInvocation methodInvocation, MethodParameterDescriptor desc) { - boolean result = false; + return bundleName; + } - if (methodInvocation.resolveMethodBinding() == null) { - return false; - } + public static SLLocation resolveResourceBundleLocation( + MethodInvocation methodInvocation, + MethodParameterDescriptor rbDefinition, + Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers) { + SLLocation bundleDesc = null; + + if (methodInvocation.getExpression() instanceof SimpleName) { + SimpleName vName = (SimpleName) methodInvocation.getExpression(); + IVariableBinding vBinding = (IVariableBinding) vName + .resolveBinding(); + VariableDeclarationFragment dec = variableBindingManagers + .get(vBinding); - String methodName = methodInvocation.resolveMethodBinding().getName(); + if (dec.getInitializer() instanceof MethodInvocation) { + MethodInvocation init = (MethodInvocation) dec.getInitializer(); // Check declaring class - ITypeBinding type = methodInvocation.resolveMethodBinding() - .getDeclaringClass(); + boolean isValidClass = false; + ITypeBinding type = init.resolveMethodBinding() + .getDeclaringClass(); while (type != null) { - if (type.getQualifiedName().equals(desc.getDeclaringClass())) { - result = true; - break; + if (type.getQualifiedName().equals( + rbDefinition.getDeclaringClass())) { + isValidClass = true; + break; + } else { + if (rbDefinition.isConsiderSuperclass()) { + type = type.getSuperclass(); } else { - if (desc.isConsiderSuperclass()) { - type = type.getSuperclass(); - } else { - type = null; - } + type = null; } + } } - - if (!result) { - return false; + if (!isValidClass) { + return null; } - result = !result; - - // Check method name - for (String method : desc.getMethodName()) { - if (method.equals(methodName)) { - result = true; - break; - } + boolean isValidMethod = false; + for (String mn : rbDefinition.getMethodName()) { + if (init.getName().getFullyQualifiedName().equals(mn)) { + isValidMethod = true; + break; + } } - - return result; - } - - public static boolean isMatchingMethodParamDesc( - MethodInvocation methodInvocation, String literal, - MethodParameterDescriptor desc) { - boolean result = isMatchingMethodDescriptor(methodInvocation, desc); - - if (!result) { - return false; - } else { - result = false; + if (!isValidMethod) { + return null; } - if (methodInvocation.arguments().size() > desc.getPosition()) { - if (methodInvocation.arguments().get(desc.getPosition()) instanceof StringLiteral) { - StringLiteral sl = (StringLiteral) methodInvocation.arguments() - .get(desc.getPosition()); - if (sl.getLiteralValue().trim().toLowerCase() - .equals(literal.toLowerCase())) { - result = true; - } - } + // retrieve bundlename + if (init.arguments().size() < rbDefinition.getPosition() + 1) { + return null; } - return result; + StringLiteral bundleLiteral = ((StringLiteral) init.arguments() + .get(rbDefinition.getPosition())); + bundleDesc = new SLLocation(null, + bundleLiteral.getStartPosition(), + bundleLiteral.getLength() + + bundleLiteral.getStartPosition(), + bundleLiteral.getLiteralValue()); + } } - public static boolean isMatchingMethodParamDesc( - MethodInvocation methodInvocation, StringLiteral literal, - MethodParameterDescriptor desc) { - int keyParameter = desc.getPosition(); - boolean result = isMatchingMethodDescriptor(methodInvocation, desc); + return bundleDesc; + } - if (!result) { - return false; - } - - // Check position within method call - StructuralPropertyDescriptor spd = literal.getLocationInParent(); - if (spd.isChildListProperty()) { - @SuppressWarnings("unchecked") - List<ASTNode> arguments = (List<ASTNode>) methodInvocation - .getStructuralProperty(spd); - result = (arguments.size() > keyParameter && arguments - .get(keyParameter) == literal); - } + private static boolean isMatchingMethodDescriptor( + MethodInvocation methodInvocation, MethodParameterDescriptor desc) { + boolean result = false; - return result; + if (methodInvocation.resolveMethodBinding() == null) { + return false; } - public static ICompilationUnit createCompilationUnit(IResource resource) { - // Instantiate a new AST parser - ASTParser parser = ASTParser.newParser(AST.JLS3); - parser.setResolveBindings(true); - - ICompilationUnit cu = JavaCore.createCompilationUnitFrom(resource - .getProject().getFile(resource.getRawLocation())); + String methodName = methodInvocation.resolveMethodBinding().getName(); + + // Check declaring class + ITypeBinding type = methodInvocation.resolveMethodBinding() + .getDeclaringClass(); + while (type != null) { + if (type.getQualifiedName().equals(desc.getDeclaringClass())) { + result = true; + break; + } else { + if (desc.isConsiderSuperclass()) { + type = type.getSuperclass(); + } else { + type = null; + } + } - return cu; } - public static CompilationUnit createCompilationUnit(IDocument document) { - // Instantiate a new AST parser - ASTParser parser = ASTParser.newParser(AST.JLS3); - parser.setResolveBindings(true); - - parser.setSource(document.get().toCharArray()); - return (CompilationUnit) parser.createAST(null); + if (!result) { + return false; } - public static void createImport(IDocument doc, IResource resource, - CompilationUnit cu, AST ast, ASTRewrite rewriter, - String qualifiedClassName) throws CoreException, - BadLocationException { - - ImportFinder impFinder = new ImportFinder(qualifiedClassName); + result = !result; - cu.accept(impFinder); - - if (!impFinder.isImportFound()) { - // ITextFileBufferManager bufferManager = - // FileBuffers.getTextFileBufferManager(); - // IPath path = resource.getFullPath(); - // - // bufferManager.connect(path, LocationKind.IFILE, null); - // ITextFileBuffer textFileBuffer = - // bufferManager.getTextFileBuffer(doc); + // Check method name + for (String method : desc.getMethodName()) { + if (method.equals(methodName)) { + result = true; + break; + } + } - // TODO create new import - ImportDeclaration id = ast.newImportDeclaration(); - id.setName(ast.newName(qualifiedClassName.split("\\."))); - id.setStatic(false); + return result; + } - ListRewrite lrw = rewriter.getListRewrite(cu, - CompilationUnit.IMPORTS_PROPERTY); - lrw.insertFirst(id, null); - - // TextEdit te = rewriter.rewriteAST(doc, null); - // te.apply(doc); - // - // if (textFileBuffer != null) - // textFileBuffer.commit(null, false); - // else - // FileUtils.saveTextFile(resource.getProject().getFile(resource.getProjectRelativePath()), - // doc.get()); - // bufferManager.disconnect(path, LocationKind.IFILE, null); - } + public static boolean isMatchingMethodParamDesc( + MethodInvocation methodInvocation, String literal, + MethodParameterDescriptor desc) { + boolean result = isMatchingMethodDescriptor(methodInvocation, desc); + if (!result) { + return false; + } else { + result = false; } - - public static void createReplaceNonInternationalisationComment( - CompilationUnit cu, IDocument doc, int position) { - int i = findNonInternationalisationPosition(cu, doc, position); - IRegion reg; - try { - reg = doc.getLineInformationOfOffset(position); - doc.replace(reg.getOffset() + reg.getLength(), 0, " //$NON-NLS-" - + i + "$"); - } catch (BadLocationException e) { - Logger.logError(e); + if (methodInvocation.arguments().size() > desc.getPosition()) { + if (methodInvocation.arguments().get(desc.getPosition()) instanceof StringLiteral) { + StringLiteral sl = (StringLiteral) methodInvocation.arguments() + .get(desc.getPosition()); + if (sl.getLiteralValue().trim().toLowerCase() + .equals(literal.toLowerCase())) { + result = true; } + } } - // TODO export initializer specification into a methodinvocationdefinition - @SuppressWarnings("unchecked") - public static void createResourceBundleReference(IResource resource, - int typePos, IDocument doc, String bundleId, Locale locale, - boolean globalReference, String variableName, CompilationUnit cu) { - - try { - - if (globalReference) { - - // retrieve compilation unit from document - PositionalTypeFinder typeFinder = new PositionalTypeFinder( - typePos); - cu.accept(typeFinder); - ASTNode node = typeFinder.getEnclosingType(); - ASTNode anonymNode = typeFinder.getEnclosingAnonymType(); - if (anonymNode != null) { - node = anonymNode; - } + return result; + } - MethodDeclaration meth = typeFinder.getEnclosingMethod(); - AST ast = node.getAST(); + public static boolean isMatchingMethodParamDesc( + MethodInvocation methodInvocation, StringLiteral literal, + MethodParameterDescriptor desc) { + int keyParameter = desc.getPosition(); + boolean result = isMatchingMethodDescriptor(methodInvocation, desc); - VariableDeclarationFragment vdf = ast - .newVariableDeclarationFragment(); - vdf.setName(ast.newSimpleName(variableName)); + if (!result) { + return false; + } - // set initializer - vdf.setInitializer(createResourceBundleGetter(ast, bundleId, - locale)); + // Check position within method call + StructuralPropertyDescriptor spd = literal.getLocationInParent(); + if (spd.isChildListProperty()) { + @SuppressWarnings("unchecked") + List<ASTNode> arguments = (List<ASTNode>) methodInvocation + .getStructuralProperty(spd); + result = (arguments.size() > keyParameter && arguments + .get(keyParameter) == literal); + } - FieldDeclaration fd = ast.newFieldDeclaration(vdf); - fd.setType(ast.newSimpleType(ast - .newName(new String[] { "ResourceBundle" }))); + return result; + } + + public static ICompilationUnit createCompilationUnit(IResource resource) { + // Instantiate a new AST parser + ASTParser parser = ASTParser.newParser(AST.JLS3); + parser.setResolveBindings(true); + + ICompilationUnit cu = JavaCore.createCompilationUnitFrom(resource + .getProject().getFile(resource.getRawLocation())); + + return cu; + } + + public static CompilationUnit createCompilationUnit(IDocument document) { + // Instantiate a new AST parser + ASTParser parser = ASTParser.newParser(AST.JLS3); + parser.setResolveBindings(true); + + parser.setSource(document.get().toCharArray()); + return (CompilationUnit) parser.createAST(null); + } + + public static void createImport(IDocument doc, IResource resource, + CompilationUnit cu, AST ast, ASTRewrite rewriter, + String qualifiedClassName) throws CoreException, + BadLocationException { + + ImportFinder impFinder = new ImportFinder(qualifiedClassName); + + cu.accept(impFinder); + + if (!impFinder.isImportFound()) { + // ITextFileBufferManager bufferManager = + // FileBuffers.getTextFileBufferManager(); + // IPath path = resource.getFullPath(); + // + // bufferManager.connect(path, LocationKind.IFILE, null); + // ITextFileBuffer textFileBuffer = + // bufferManager.getTextFileBuffer(doc); + + // TODO create new import + ImportDeclaration id = ast.newImportDeclaration(); + id.setName(ast.newName(qualifiedClassName.split("\\."))); + id.setStatic(false); + + ListRewrite lrw = rewriter.getListRewrite(cu, + CompilationUnit.IMPORTS_PROPERTY); + lrw.insertFirst(id, null); + + // TextEdit te = rewriter.rewriteAST(doc, null); + // te.apply(doc); + // + // if (textFileBuffer != null) + // textFileBuffer.commit(null, false); + // else + // FileUtils.saveTextFile(resource.getProject().getFile(resource.getProjectRelativePath()), + // doc.get()); + // bufferManager.disconnect(path, LocationKind.IFILE, null); + } - if (meth != null - && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC) { - fd.modifiers().addAll(ast.newModifiers(Modifier.STATIC)); - } + } - // rewrite AST - ASTRewrite rewriter = ASTRewrite.create(ast); - ListRewrite lrw = rewriter - .getListRewrite( - node, - node instanceof TypeDeclaration ? TypeDeclaration.BODY_DECLARATIONS_PROPERTY - : AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY); - lrw.insertAt(fd, /* - * findIndexOfLastField(node.bodyDeclarations()) - * +1 - */ - 0, null); - - // create import if required - createImport(doc, resource, cu, ast, rewriter, - getRBDefinitionDesc().getDeclaringClass()); - - TextEdit te = rewriter.rewriteAST(doc, null); - te.apply(doc); - } else { + public static void createReplaceNonInternationalisationComment( + CompilationUnit cu, IDocument doc, int position) { + int i = findNonInternationalisationPosition(cu, doc, position); - } - } catch (Exception e) { - e.printStackTrace(); - } + IRegion reg; + try { + reg = doc.getLineInformationOfOffset(position); + doc.replace(reg.getOffset() + reg.getLength(), 0, " //$NON-NLS-" + + i + "$"); + } catch (BadLocationException e) { + Logger.logError(e); } + } - @SuppressWarnings("unchecked") - protected static MethodInvocation createResourceBundleGetter(AST ast, - String bundleId, Locale locale) { - MethodInvocation mi = ast.newMethodInvocation(); + // TODO export initializer specification into a methodinvocationdefinition + @SuppressWarnings("unchecked") + public static void createResourceBundleReference(IResource resource, + int typePos, IDocument doc, String bundleId, Locale locale, + boolean globalReference, String variableName, CompilationUnit cu) { - mi.setName(ast.newSimpleName("getBundle")); - mi.setExpression(ast.newName(new String[] { "ResourceBundle" })); + try { - // Add bundle argument - StringLiteral sl = ast.newStringLiteral(); - sl.setLiteralValue(bundleId); - mi.arguments().add(sl); + if (globalReference) { - // TODO Add Locale argument + // retrieve compilation unit from document + PositionalTypeFinder typeFinder = new PositionalTypeFinder( + typePos); + cu.accept(typeFinder); + ASTNode node = typeFinder.getEnclosingType(); + ASTNode anonymNode = typeFinder.getEnclosingAnonymType(); + if (anonymNode != null) { + node = anonymNode; + } - return mi; - } + MethodDeclaration meth = typeFinder.getEnclosingMethod(); + AST ast = node.getAST(); - public static ASTNode getEnclosingType(CompilationUnit cu, int pos) { - PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos); - cu.accept(typeFinder); - return (typeFinder.getEnclosingAnonymType() != null) ? typeFinder - .getEnclosingAnonymType() : typeFinder.getEnclosingType(); + VariableDeclarationFragment vdf = ast + .newVariableDeclarationFragment(); + vdf.setName(ast.newSimpleName(variableName)); + + // set initializer + vdf.setInitializer(createResourceBundleGetter(ast, bundleId, + locale)); + + FieldDeclaration fd = ast.newFieldDeclaration(vdf); + fd.setType(ast.newSimpleType(ast + .newName(new String[] { "ResourceBundle" }))); + + if (meth != null + && (meth.getModifiers() & Modifier.STATIC) == Modifier.STATIC) { + fd.modifiers().addAll(ast.newModifiers(Modifier.STATIC)); + } + + // rewrite AST + ASTRewrite rewriter = ASTRewrite.create(ast); + ListRewrite lrw = rewriter + .getListRewrite( + node, + node instanceof TypeDeclaration ? TypeDeclaration.BODY_DECLARATIONS_PROPERTY + : AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY); + lrw.insertAt(fd, /* + * findIndexOfLastField(node.bodyDeclarations()) + * +1 + */ + 0, null); + + // create import if required + createImport(doc, resource, cu, ast, rewriter, + getRBDefinitionDesc().getDeclaringClass()); + + TextEdit te = rewriter.rewriteAST(doc, null); + te.apply(doc); + } else { + + } + } catch (Exception e) { + e.printStackTrace(); } - - public static ASTNode getEnclosingType(ASTNode cu, int pos) { - PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos); - cu.accept(typeFinder); - return (typeFinder.getEnclosingAnonymType() != null) ? typeFinder - .getEnclosingAnonymType() : typeFinder.getEnclosingType(); + } + + @SuppressWarnings("unchecked") + protected static MethodInvocation createResourceBundleGetter(AST ast, + String bundleId, Locale locale) { + MethodInvocation mi = ast.newMethodInvocation(); + + mi.setName(ast.newSimpleName("getBundle")); + mi.setExpression(ast.newName(new String[] { "ResourceBundle" })); + + // Add bundle argument + StringLiteral sl = ast.newStringLiteral(); + sl.setLiteralValue(bundleId); + mi.arguments().add(sl); + + // TODO Add Locale argument + + return mi; + } + + public static ASTNode getEnclosingType(CompilationUnit cu, int pos) { + PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos); + cu.accept(typeFinder); + return (typeFinder.getEnclosingAnonymType() != null) ? typeFinder + .getEnclosingAnonymType() : typeFinder.getEnclosingType(); + } + + public static ASTNode getEnclosingType(ASTNode cu, int pos) { + PositionalTypeFinder typeFinder = new PositionalTypeFinder(pos); + cu.accept(typeFinder); + return (typeFinder.getEnclosingAnonymType() != null) ? typeFinder + .getEnclosingAnonymType() : typeFinder.getEnclosingType(); + } + + @SuppressWarnings("unchecked") + protected static MethodInvocation referenceResource(AST ast, + String accessorName, String key, Locale locale) { + MethodParameterDescriptor accessorDesc = getRBAccessorDesc(); + MethodInvocation mi = ast.newMethodInvocation(); + + mi.setName(ast.newSimpleName(accessorDesc.getMethodName().get(0))); + + // Declare expression + StringLiteral sl = ast.newStringLiteral(); + sl.setLiteralValue(key); + + // TODO define locale expression + if (mi.arguments().size() == accessorDesc.getPosition()) { + mi.arguments().add(sl); } - @SuppressWarnings("unchecked") - protected static MethodInvocation referenceResource(AST ast, - String accessorName, String key, Locale locale) { - MethodParameterDescriptor accessorDesc = getRBAccessorDesc(); - MethodInvocation mi = ast.newMethodInvocation(); + SimpleName name = ast.newSimpleName(accessorName); + mi.setExpression(name); - mi.setName(ast.newSimpleName(accessorDesc.getMethodName().get(0))); + return mi; + } - // Declare expression - StringLiteral sl = ast.newStringLiteral(); - sl.setLiteralValue(key); + public static String createResourceReference(String bundleId, String key, + Locale locale, IResource resource, int typePos, + String accessorName, IDocument doc, CompilationUnit cu) { - // TODO define locale expression - if (mi.arguments().size() == accessorDesc.getPosition()) { - mi.arguments().add(sl); - } + PositionalTypeFinder typeFinder = new PositionalTypeFinder(typePos); + cu.accept(typeFinder); + AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType(); + TypeDeclaration td = typeFinder.getEnclosingType(); - SimpleName name = ast.newSimpleName(accessorName); - mi.setExpression(name); + // retrieve compilation unit from document + ASTNode node = atd == null ? td : atd; + AST ast = node.getAST(); - return mi; - } + ExpressionStatement expressionStatement = ast + .newExpressionStatement(referenceResource(ast, accessorName, + key, locale)); - public static String createResourceReference(String bundleId, String key, - Locale locale, IResource resource, int typePos, - String accessorName, IDocument doc, CompilationUnit cu) { + String exp = expressionStatement.toString(); - PositionalTypeFinder typeFinder = new PositionalTypeFinder(typePos); - cu.accept(typeFinder); - AnonymousClassDeclaration atd = typeFinder.getEnclosingAnonymType(); - TypeDeclaration td = typeFinder.getEnclosingType(); + // remove semicolon and line break at the end of this expression + // statement + if (exp.endsWith(";\n")) { + exp = exp.substring(0, exp.length() - 2); + } - // retrieve compilation unit from document - ASTNode node = atd == null ? td : atd; - AST ast = node.getAST(); + return exp; + } + + private static int findNonInternationalisationPosition(CompilationUnit cu, + IDocument doc, int offset) { + LinePreStringsFinder lsfinder = null; + try { + lsfinder = new LinePreStringsFinder(offset, doc); + cu.accept(lsfinder); + } catch (BadLocationException e) { + Logger.logError(e); + } + if (lsfinder == null) { + return 1; + } - ExpressionStatement expressionStatement = ast - .newExpressionStatement(referenceResource(ast, accessorName, - key, locale)); + List<StringLiteral> strings = lsfinder.getStrings(); - String exp = expressionStatement.toString(); + return strings.size() + 1; + } - // remove semicolon and line break at the end of this expression - // statement - if (exp.endsWith(";\n")) { - exp = exp.substring(0, exp.length() - 2); - } + public static boolean existsNonInternationalisationComment( + StringLiteral literal) throws BadLocationException { + CompilationUnit cu = (CompilationUnit) literal.getRoot(); + ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement(); - return exp; + IDocument doc = null; + try { + doc = new Document(icu.getSource()); + } catch (JavaModelException e) { + Logger.logError(e); } - private static int findNonInternationalisationPosition(CompilationUnit cu, - IDocument doc, int offset) { - LinePreStringsFinder lsfinder = null; - try { - lsfinder = new LinePreStringsFinder(offset, doc); - cu.accept(lsfinder); - } catch (BadLocationException e) { - Logger.logError(e); - } - if (lsfinder == null) { - return 1; - } + // get whole line in which string literal + int lineNo = doc.getLineOfOffset(literal.getStartPosition()); + int lineOffset = doc.getLineOffset(lineNo); + int lineLength = doc.getLineLength(lineNo); + String lineOfString = doc.get(lineOffset, lineLength); - List<StringLiteral> strings = lsfinder.getStrings(); + // search for a line comment in this line + int indexComment = lineOfString.indexOf("//"); - return strings.size() + 1; + if (indexComment == -1) { + return false; } - public static boolean existsNonInternationalisationComment( - StringLiteral literal) throws BadLocationException { - CompilationUnit cu = (CompilationUnit) literal.getRoot(); - ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement(); + String comment = lineOfString.substring(indexComment); - IDocument doc = null; - try { - doc = new Document(icu.getSource()); - } catch (JavaModelException e) { - Logger.logError(e); - } + // remove first "//" of line comment + comment = comment.substring(2).toLowerCase(); + + // split line comments, necessary if more NON-NLS comments exist in one line, eg.: $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3 + String[] comments = comment.split("//"); - // get whole line in which string literal - int lineNo = doc.getLineOfOffset(literal.getStartPosition()); - int lineOffset = doc.getLineOffset(lineNo); - int lineLength = doc.getLineLength(lineNo); - String lineOfString = doc.get(lineOffset, lineLength); + for (String commentFrag : comments) { + commentFrag = commentFrag.trim(); - // search for a line comment in this line - int indexComment = lineOfString.indexOf("//"); + // if comment match format: "$non-nls$" then ignore whole line + if (commentFrag.matches("^\\$non-nls\\$$")) { + return true; - if (indexComment == -1) { - return false; + // if comment match format: "$non-nls-{number}$" then only + // ignore string which is on given position + } else if (commentFrag.matches("^\\$non-nls-\\d+\\$$")) { + int iString = findNonInternationalisationPosition(cu, doc, + literal.getStartPosition()); + int iComment = new Integer(commentFrag.substring(9, 10)); + if (iString == iComment) { + return true; } + } + } + return false; + } - String comment = lineOfString.substring(indexComment); + public static StringLiteral getStringLiteralAtPos(CompilationUnit cu, + int position) { + StringLiteralFinder strFinder = new StringLiteralFinder(position); + cu.accept(strFinder); + return strFinder.getStringLiteral(); + } - // remove first "//" of line comment - comment = comment.substring(2).toLowerCase(); + static class PositionalTypeFinder extends ASTVisitor { - // split line comments, necessary if more NON-NLS comments exist in one line, eg.: $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3 - String[] comments = comment.split("//"); + private int position; + private TypeDeclaration enclosingType; + private AnonymousClassDeclaration enclosingAnonymType; + private MethodDeclaration enclosingMethod; - for (String commentFrag : comments) { - commentFrag = commentFrag.trim(); + public PositionalTypeFinder(int pos) { + position = pos; + } - // if comment match format: "$non-nls$" then ignore whole line - if (commentFrag.matches("^\\$non-nls\\$$")) { - return true; + public TypeDeclaration getEnclosingType() { + return enclosingType; + } - // if comment match format: "$non-nls-{number}$" then only - // ignore string which is on given position - } else if (commentFrag.matches("^\\$non-nls-\\d+\\$$")) { - int iString = findNonInternationalisationPosition(cu, doc, - literal.getStartPosition()); - int iComment = new Integer(commentFrag.substring(9, 10)); - if (iString == iComment) { - return true; - } - } - } - return false; + public AnonymousClassDeclaration getEnclosingAnonymType() { + return enclosingAnonymType; } - public static StringLiteral getStringLiteralAtPos(CompilationUnit cu, int position) { - StringLiteralFinder strFinder = new StringLiteralFinder(position); - cu.accept(strFinder); - return strFinder.getStringLiteral(); + public MethodDeclaration getEnclosingMethod() { + return enclosingMethod; } - static class PositionalTypeFinder extends ASTVisitor { + @Override + public boolean visit(MethodDeclaration node) { + if (position >= node.getStartPosition() + && position <= (node.getStartPosition() + node.getLength())) { + enclosingMethod = node; + return true; + } else { + return false; + } + } - private int position; - private TypeDeclaration enclosingType; - private AnonymousClassDeclaration enclosingAnonymType; - private MethodDeclaration enclosingMethod; + @Override + public boolean visit(TypeDeclaration node) { + if (position >= node.getStartPosition() + && position <= (node.getStartPosition() + node.getLength())) { + enclosingType = node; + return true; + } else { + return false; + } + } - public PositionalTypeFinder(int pos) { - position = pos; - } + @Override + public boolean visit(AnonymousClassDeclaration node) { + if (position >= node.getStartPosition() + && position <= (node.getStartPosition() + node.getLength())) { + enclosingAnonymType = node; + return true; + } else { + return false; + } + } + } - public TypeDeclaration getEnclosingType() { - return enclosingType; - } + static class ImportFinder extends ASTVisitor { - public AnonymousClassDeclaration getEnclosingAnonymType() { - return enclosingAnonymType; - } + String qName; + boolean importFound = false; - public MethodDeclaration getEnclosingMethod() { - return enclosingMethod; - } + public ImportFinder(String qName) { + this.qName = qName; + } - @Override - public boolean visit(MethodDeclaration node) { - if (position >= node.getStartPosition() - && position <= (node.getStartPosition() + node.getLength())) { - enclosingMethod = node; - return true; - } else { - return false; - } - } + public boolean isImportFound() { + return importFound; + } - @Override - public boolean visit(TypeDeclaration node) { - if (position >= node.getStartPosition() - && position <= (node.getStartPosition() + node.getLength())) { - enclosingType = node; - return true; - } else { - return false; - } - } + @Override + public boolean visit(ImportDeclaration id) { + if (id.getName().getFullyQualifiedName().equals(qName)) { + importFound = true; + } - @Override - public boolean visit(AnonymousClassDeclaration node) { - if (position >= node.getStartPosition() - && position <= (node.getStartPosition() + node.getLength())) { - enclosingAnonymType = node; - return true; - } else { - return false; - } - } + return true; } + } - static class ImportFinder extends ASTVisitor { + static class VariableFinder extends ASTVisitor { - String qName; - boolean importFound = false; + boolean found = false; + String variableName; - public ImportFinder(String qName) { - this.qName = qName; - } + public boolean isVariableFound() { + return found; + } - public boolean isImportFound() { - return importFound; - } + public VariableFinder(String variableName) { + this.variableName = variableName; + } - @Override - public boolean visit(ImportDeclaration id) { - if (id.getName().getFullyQualifiedName().equals(qName)) { - importFound = true; - } + @Override + public boolean visit(VariableDeclarationFragment vdf) { + if (vdf.getName().getFullyQualifiedName().equals(variableName)) { + found = true; + return false; + } - return true; - } + return true; } + } - static class VariableFinder extends ASTVisitor { + static class InMethodBundleDeclFinder extends ASTVisitor { + String varName; + String bundleId; + int pos; - boolean found = false; - String variableName; + public InMethodBundleDeclFinder(String bundleId, int pos) { + this.bundleId = bundleId; + this.pos = pos; + } - public boolean isVariableFound() { - return found; - } + public String getVariableName() { + return varName; + } - public VariableFinder(String variableName) { - this.variableName = variableName; - } + @Override + public boolean visit(VariableDeclarationFragment fdvd) { + if (fdvd.getStartPosition() > pos) { + return false; + } - @Override - public boolean visit(VariableDeclarationFragment vdf) { - if (vdf.getName().getFullyQualifiedName().equals(variableName)) { - found = true; - return false; - } + // boolean bStatic = (fdvd.resolveBinding().getModifiers() & + // Modifier.STATIC) == Modifier.STATIC; + // if (!bStatic && isStatic) + // return true; - return true; + String tmpVarName = fdvd.getName().getFullyQualifiedName(); + + if (fdvd.getInitializer() instanceof MethodInvocation) { + MethodInvocation fdi = (MethodInvocation) fdvd.getInitializer(); + if (isMatchingMethodParamDesc(fdi, bundleId, + getRBDefinitionDesc())) { + varName = tmpVarName; } + } + return true; } + } - static class InMethodBundleDeclFinder extends ASTVisitor { - String varName; - String bundleId; - int pos; + static class BundleDeclarationFinder extends ASTVisitor { - public InMethodBundleDeclFinder(String bundleId, int pos) { - this.bundleId = bundleId; - this.pos = pos; - } + String varName; + String bundleId; + ASTNode typeDef; + boolean isStatic; - public String getVariableName() { - return varName; - } - - @Override - public boolean visit(VariableDeclarationFragment fdvd) { - if (fdvd.getStartPosition() > pos) { - return false; - } + public BundleDeclarationFinder(String bundleId, ASTNode td, + boolean isStatic) { + this.bundleId = bundleId; + this.typeDef = td; + this.isStatic = isStatic; + } - // boolean bStatic = (fdvd.resolveBinding().getModifiers() & - // Modifier.STATIC) == Modifier.STATIC; - // if (!bStatic && isStatic) - // return true; + public String getVariableName() { + return varName; + } - String tmpVarName = fdvd.getName().getFullyQualifiedName(); + @Override + public boolean visit(MethodDeclaration md) { + return true; + } - if (fdvd.getInitializer() instanceof MethodInvocation) { - MethodInvocation fdi = (MethodInvocation) fdvd.getInitializer(); + @Override + public boolean visit(FieldDeclaration fd) { + if (getEnclosingType(typeDef, fd.getStartPosition()) != typeDef) { + return false; + } + + boolean bStatic = (fd.getModifiers() & Modifier.STATIC) == Modifier.STATIC; + if (!bStatic && isStatic) { + return true; + } + + if (fd.getType() instanceof SimpleType) { + SimpleType fdType = (SimpleType) fd.getType(); + String typeName = fdType.getName().getFullyQualifiedName(); + String referenceName = getRBDefinitionDesc() + .getDeclaringClass(); + if (typeName.equals(referenceName) + || (referenceName.lastIndexOf(".") >= 0 && typeName + .equals(referenceName.substring(referenceName + .lastIndexOf(".") + 1)))) { + // Check VariableDeclarationFragment + if (fd.fragments().size() == 1) { + if (fd.fragments().get(0) instanceof VariableDeclarationFragment) { + VariableDeclarationFragment fdvd = (VariableDeclarationFragment) fd + .fragments().get(0); + String tmpVarName = fdvd.getName() + .getFullyQualifiedName(); + + if (fdvd.getInitializer() instanceof MethodInvocation) { + MethodInvocation fdi = (MethodInvocation) fdvd + .getInitializer(); if (isMatchingMethodParamDesc(fdi, bundleId, - getRBDefinitionDesc())) { - varName = tmpVarName; + getRBDefinitionDesc())) { + varName = tmpVarName; } + } } - return true; + } } + } + return false; } - static class BundleDeclarationFinder extends ASTVisitor { - - String varName; - String bundleId; - ASTNode typeDef; - boolean isStatic; + } - public BundleDeclarationFinder(String bundleId, ASTNode td, - boolean isStatic) { - this.bundleId = bundleId; - this.typeDef = td; - this.isStatic = isStatic; - } - - public String getVariableName() { - return varName; - } - - @Override - public boolean visit(MethodDeclaration md) { - return true; - } - - @Override - public boolean visit(FieldDeclaration fd) { - if (getEnclosingType(typeDef, fd.getStartPosition()) != typeDef) { - return false; - } - - boolean bStatic = (fd.getModifiers() & Modifier.STATIC) == Modifier.STATIC; - if (!bStatic && isStatic) { - return true; - } - - if (fd.getType() instanceof SimpleType) { - SimpleType fdType = (SimpleType) fd.getType(); - String typeName = fdType.getName().getFullyQualifiedName(); - String referenceName = getRBDefinitionDesc() - .getDeclaringClass(); - if (typeName.equals(referenceName) - || (referenceName.lastIndexOf(".") >= 0 && typeName - .equals(referenceName.substring(referenceName - .lastIndexOf(".") + 1)))) { - // Check VariableDeclarationFragment - if (fd.fragments().size() == 1) { - if (fd.fragments().get(0) instanceof VariableDeclarationFragment) { - VariableDeclarationFragment fdvd = (VariableDeclarationFragment) fd - .fragments().get(0); - String tmpVarName = fdvd.getName() - .getFullyQualifiedName(); - - if (fdvd.getInitializer() instanceof MethodInvocation) { - MethodInvocation fdi = (MethodInvocation) fdvd - .getInitializer(); - if (isMatchingMethodParamDesc(fdi, bundleId, - getRBDefinitionDesc())) { - varName = tmpVarName; - } - } - } - } - } - } - return false; - } + static class LinePreStringsFinder extends ASTVisitor { + private int position; + private int line; + private List<StringLiteral> strings; + private IDocument document; + public LinePreStringsFinder(int position, IDocument document) + throws BadLocationException { + this.document = document; + this.position = position; + line = document.getLineOfOffset(position); + strings = new ArrayList<StringLiteral>(); } - static class LinePreStringsFinder extends ASTVisitor { - private int position; - private int line; - private List<StringLiteral> strings; - private IDocument document; - - public LinePreStringsFinder(int position, IDocument document) - throws BadLocationException { - this.document = document; - this.position = position; - line = document.getLineOfOffset(position); - strings = new ArrayList<StringLiteral>(); - } - - public List<StringLiteral> getStrings() { - return strings; - } + public List<StringLiteral> getStrings() { + return strings; + } - @Override - public boolean visit(StringLiteral node) { - try { - if (line == document.getLineOfOffset(node.getStartPosition()) - && node.getStartPosition() < position) { - strings.add(node); - return true; - } - } catch (BadLocationException e) { - } - return true; - } + @Override + public boolean visit(StringLiteral node) { + try { + if (line == document.getLineOfOffset(node.getStartPosition()) + && node.getStartPosition() < position) { + strings.add(node); + return true; + } + } catch (BadLocationException e) { + } + return true; } + } - static class StringLiteralFinder extends ASTVisitor { - private int position; - private StringLiteral string; + static class StringLiteralFinder extends ASTVisitor { + private int position; + private StringLiteral string; - public StringLiteralFinder(int position) { - this.position = position; - } + public StringLiteralFinder(int position) { + this.position = position; + } - public StringLiteral getStringLiteral() { - return string; - } + public StringLiteral getStringLiteral() { + return string; + } - @Override - public boolean visit(StringLiteral node) { - if (position > node.getStartPosition() - && position < (node.getStartPosition() + node.getLength())) { - string = node; - } - return true; - } + @Override + public boolean visit(StringLiteral node) { + if (position > node.getStartPosition() + && position < (node.getStartPosition() + node.getLength())) { + string = node; + } + return true; } + } } diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/MethodParameterDescriptor.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/MethodParameterDescriptor.java index 9b8639ad..5cb23c1b 100644 --- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/MethodParameterDescriptor.java +++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/MethodParameterDescriptor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -14,50 +14,50 @@ public class MethodParameterDescriptor { - private List<String> methodName; - private String declaringClass; - private boolean considerSuperclass; - private int position; - - public MethodParameterDescriptor(List<String> methodName, - String declaringClass, boolean considerSuperclass, int position) { - super(); - this.setMethodName(methodName); - this.declaringClass = declaringClass; - this.considerSuperclass = considerSuperclass; - this.position = position; - } - - public String getDeclaringClass() { - return declaringClass; - } - - public void setDeclaringClass(String declaringClass) { - this.declaringClass = declaringClass; - } - - public boolean isConsiderSuperclass() { - return considerSuperclass; - } - - public void setConsiderSuperclass(boolean considerSuperclass) { - this.considerSuperclass = considerSuperclass; - } - - public int getPosition() { - return position; - } - - public void setPosition(int position) { - this.position = position; - } - - public void setMethodName(List<String> methodName) { - this.methodName = methodName; - } - - public List<String> getMethodName() { - return methodName; - } + private List<String> methodName; + private String declaringClass; + private boolean considerSuperclass; + private int position; + + public MethodParameterDescriptor(List<String> methodName, + String declaringClass, boolean considerSuperclass, int position) { + super(); + this.setMethodName(methodName); + this.declaringClass = declaringClass; + this.considerSuperclass = considerSuperclass; + this.position = position; + } + + public String getDeclaringClass() { + return declaringClass; + } + + public void setDeclaringClass(String declaringClass) { + this.declaringClass = declaringClass; + } + + public boolean isConsiderSuperclass() { + return considerSuperclass; + } + + public void setConsiderSuperclass(boolean considerSuperclass) { + this.considerSuperclass = considerSuperclass; + } + + public int getPosition() { + return position; + } + + public void setPosition(int position) { + this.position = position; + } + + public void setMethodName(List<String> methodName) { + this.methodName = methodName; + } + + public List<String> getMethodName() { + return methodName; + } } diff --git a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java index f19d95e8..36ac0510 100644 --- a/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java +++ b/org.eclipse.babel.tapiji.tools.java/src/org/eclipse/babel/tapiji/tools/java/visitor/ResourceAuditVisitor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -43,219 +43,219 @@ * */ public class ResourceAuditVisitor extends ASTVisitor implements - IResourceVisitor { - - private List<SLLocation> constants; - private List<SLLocation> brokenStrings; - private List<SLLocation> brokenRBReferences; - private SortedMap<Long, IRegion> rbDefReferences = new TreeMap<Long, IRegion>(); - private SortedMap<Long, IRegion> keyPositions = new TreeMap<Long, IRegion>(); - private Map<IRegion, String> bundleKeys = new HashMap<IRegion, String>(); - private Map<IRegion, String> bundleReferences = new HashMap<IRegion, String>(); - private IFile file; - private Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers = new HashMap<IVariableBinding, VariableDeclarationFragment>(); - private String projectName; - - public ResourceAuditVisitor(IFile file, String projectName) { - constants = new ArrayList<SLLocation>(); - brokenStrings = new ArrayList<SLLocation>(); - brokenRBReferences = new ArrayList<SLLocation>(); - this.file = file; - this.projectName = projectName; + IResourceVisitor { + + private List<SLLocation> constants; + private List<SLLocation> brokenStrings; + private List<SLLocation> brokenRBReferences; + private SortedMap<Long, IRegion> rbDefReferences = new TreeMap<Long, IRegion>(); + private SortedMap<Long, IRegion> keyPositions = new TreeMap<Long, IRegion>(); + private Map<IRegion, String> bundleKeys = new HashMap<IRegion, String>(); + private Map<IRegion, String> bundleReferences = new HashMap<IRegion, String>(); + private IFile file; + private Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers = new HashMap<IVariableBinding, VariableDeclarationFragment>(); + private String projectName; + + public ResourceAuditVisitor(IFile file, String projectName) { + constants = new ArrayList<SLLocation>(); + brokenStrings = new ArrayList<SLLocation>(); + brokenRBReferences = new ArrayList<SLLocation>(); + this.file = file; + this.projectName = projectName; + } + + @SuppressWarnings("unchecked") + @Override + public boolean visit(VariableDeclarationStatement varDeclaration) { + for (Iterator<VariableDeclarationFragment> itFrag = varDeclaration + .fragments().iterator(); itFrag.hasNext();) { + VariableDeclarationFragment fragment = itFrag.next(); + parseVariableDeclarationFragment(fragment); } - - @SuppressWarnings("unchecked") - @Override - public boolean visit(VariableDeclarationStatement varDeclaration) { - for (Iterator<VariableDeclarationFragment> itFrag = varDeclaration - .fragments().iterator(); itFrag.hasNext();) { - VariableDeclarationFragment fragment = itFrag.next(); - parseVariableDeclarationFragment(fragment); - } - return true; - } - - @SuppressWarnings("unchecked") - @Override - public boolean visit(FieldDeclaration fieldDeclaration) { - for (Iterator<VariableDeclarationFragment> itFrag = fieldDeclaration - .fragments().iterator(); itFrag.hasNext();) { - VariableDeclarationFragment fragment = itFrag.next(); - parseVariableDeclarationFragment(fragment); - } - return true; + return true; + } + + @SuppressWarnings("unchecked") + @Override + public boolean visit(FieldDeclaration fieldDeclaration) { + for (Iterator<VariableDeclarationFragment> itFrag = fieldDeclaration + .fragments().iterator(); itFrag.hasNext();) { + VariableDeclarationFragment fragment = itFrag.next(); + parseVariableDeclarationFragment(fragment); } - - protected void parseVariableDeclarationFragment( - VariableDeclarationFragment fragment) { - IVariableBinding vBinding = fragment.resolveBinding(); - this.variableBindingManagers.put(vBinding, fragment); - } - - @Override - public boolean visit(StringLiteral stringLiteral) { - try { - ASTNode parent = stringLiteral.getParent(); - ResourceBundleManager manager = ResourceBundleManager - .getManager(projectName); - - if (manager == null) { - return false; - } - - if (parent instanceof MethodInvocation) { - MethodInvocation methodInvocation = (MethodInvocation) parent; - - IRegion region = new Region(stringLiteral.getStartPosition(), - stringLiteral.getLength()); - - // Check if this method invokes the getString-Method on a - // ResourceBundle Implementation - if (ASTutils.isMatchingMethodParamDesc(methodInvocation, - stringLiteral, ASTutils.getRBAccessorDesc())) { - // Check if the given Resource-Bundle reference is broken - SLLocation rbName = ASTutils.resolveResourceBundleLocation( - methodInvocation, ASTutils.getRBDefinitionDesc(), - variableBindingManagers); - if (rbName == null - || manager.isKeyBroken(rbName.getLiteral(), - stringLiteral.getLiteralValue())) { - // report new problem - SLLocation desc = new SLLocation(file, - stringLiteral.getStartPosition(), - stringLiteral.getStartPosition() - + stringLiteral.getLength(), - stringLiteral.getLiteralValue()); - desc.setData(rbName); - brokenStrings.add(desc); - } - - // store position of resource-bundle access - keyPositions.put( - Long.valueOf(stringLiteral.getStartPosition()), - region); - bundleKeys.put(region, stringLiteral.getLiteralValue()); - bundleReferences.put(region, rbName.getLiteral()); - return false; - } else if (ASTutils.isMatchingMethodParamDesc(methodInvocation, - stringLiteral, ASTutils.getRBDefinitionDesc())) { - rbDefReferences.put( - Long.valueOf(stringLiteral.getStartPosition()), - region); - boolean referenceBroken = true; - for (String bundle : manager.getResourceBundleIdentifiers()) { - if (bundle.trim().equals( - stringLiteral.getLiteralValue())) { - referenceBroken = false; - } - } - if (referenceBroken) { - this.brokenRBReferences.add(new SLLocation(file, - stringLiteral.getStartPosition(), stringLiteral - .getStartPosition() - + stringLiteral.getLength(), - stringLiteral.getLiteralValue())); - } - - return false; - } - } - - // check if string is followed by a "$NON-NLS$" line comment - if (ASTutils.existsNonInternationalisationComment(stringLiteral)) { - return false; - } - - // constant string literal found - constants.add(new SLLocation(file, - stringLiteral.getStartPosition(), stringLiteral - .getStartPosition() + stringLiteral.getLength(), - stringLiteral.getLiteralValue())); - } catch (Exception e) { - e.printStackTrace(); - } + return true; + } + + protected void parseVariableDeclarationFragment( + VariableDeclarationFragment fragment) { + IVariableBinding vBinding = fragment.resolveBinding(); + this.variableBindingManagers.put(vBinding, fragment); + } + + @Override + public boolean visit(StringLiteral stringLiteral) { + try { + ASTNode parent = stringLiteral.getParent(); + ResourceBundleManager manager = ResourceBundleManager + .getManager(projectName); + + if (manager == null) { return false; - } - - public List<SLLocation> getConstantStringLiterals() { - return constants; - } - - public List<SLLocation> getBrokenResourceReferences() { - return brokenStrings; - } - - public List<SLLocation> getBrokenRBReferences() { - return this.brokenRBReferences; - } - - public IRegion getKeyAt(Long position) { - IRegion reg = null; - - Iterator<Long> keys = keyPositions.keySet().iterator(); - while (keys.hasNext()) { - Long startPos = keys.next(); - if (startPos > position) { - break; - } - - IRegion region = keyPositions.get(startPos); - if (region.getOffset() <= position - && (region.getOffset() + region.getLength()) >= position) { - reg = region; - break; + } + + if (parent instanceof MethodInvocation) { + MethodInvocation methodInvocation = (MethodInvocation) parent; + + IRegion region = new Region(stringLiteral.getStartPosition(), + stringLiteral.getLength()); + + // Check if this method invokes the getString-Method on a + // ResourceBundle Implementation + if (ASTutils.isMatchingMethodParamDesc(methodInvocation, + stringLiteral, ASTutils.getRBAccessorDesc())) { + // Check if the given Resource-Bundle reference is broken + SLLocation rbName = ASTutils.resolveResourceBundleLocation( + methodInvocation, ASTutils.getRBDefinitionDesc(), + variableBindingManagers); + if (rbName == null + || manager.isKeyBroken(rbName.getLiteral(), + stringLiteral.getLiteralValue())) { + // report new problem + SLLocation desc = new SLLocation(file, + stringLiteral.getStartPosition(), + stringLiteral.getStartPosition() + + stringLiteral.getLength(), + stringLiteral.getLiteralValue()); + desc.setData(rbName); + brokenStrings.add(desc); + } + + // store position of resource-bundle access + keyPositions.put( + Long.valueOf(stringLiteral.getStartPosition()), + region); + bundleKeys.put(region, stringLiteral.getLiteralValue()); + bundleReferences.put(region, rbName.getLiteral()); + return false; + } else if (ASTutils.isMatchingMethodParamDesc(methodInvocation, + stringLiteral, ASTutils.getRBDefinitionDesc())) { + rbDefReferences.put( + Long.valueOf(stringLiteral.getStartPosition()), + region); + boolean referenceBroken = true; + for (String bundle : manager.getResourceBundleIdentifiers()) { + if (bundle.trim().equals( + stringLiteral.getLiteralValue())) { + referenceBroken = false; } + } + if (referenceBroken) { + this.brokenRBReferences.add(new SLLocation(file, + stringLiteral.getStartPosition(), stringLiteral + .getStartPosition() + + stringLiteral.getLength(), + stringLiteral.getLiteralValue())); + } + + return false; } + } - return reg; + // check if string is followed by a "$NON-NLS$" line comment + if (ASTutils.existsNonInternationalisationComment(stringLiteral)) { + return false; + } + + // constant string literal found + constants.add(new SLLocation(file, + stringLiteral.getStartPosition(), stringLiteral + .getStartPosition() + stringLiteral.getLength(), + stringLiteral.getLiteralValue())); + } catch (Exception e) { + e.printStackTrace(); } - - public String getKeyAt(IRegion region) { - if (bundleKeys.containsKey(region)) { - return bundleKeys.get(region); - } else { - return ""; - } + return false; + } + + public List<SLLocation> getConstantStringLiterals() { + return constants; + } + + public List<SLLocation> getBrokenResourceReferences() { + return brokenStrings; + } + + public List<SLLocation> getBrokenRBReferences() { + return this.brokenRBReferences; + } + + public IRegion getKeyAt(Long position) { + IRegion reg = null; + + Iterator<Long> keys = keyPositions.keySet().iterator(); + while (keys.hasNext()) { + Long startPos = keys.next(); + if (startPos > position) { + break; + } + + IRegion region = keyPositions.get(startPos); + if (region.getOffset() <= position + && (region.getOffset() + region.getLength()) >= position) { + reg = region; + break; + } } - public String getBundleReference(IRegion region) { - return bundleReferences.get(region); - } + return reg; + } - @Override - public boolean visit(IResource resource) throws CoreException { - // TODO Auto-generated method stub - return false; + public String getKeyAt(IRegion region) { + if (bundleKeys.containsKey(region)) { + return bundleKeys.get(region); + } else { + return ""; } - - public Collection<String> getDefinedResourceBundles(int offset) { - Collection<String> result = new HashSet<String>(); - for (String s : bundleReferences.values()) { - if (s != null) { - result.add(s); - } - } - return result; + } + + public String getBundleReference(IRegion region) { + return bundleReferences.get(region); + } + + @Override + public boolean visit(IResource resource) throws CoreException { + // TODO Auto-generated method stub + return false; + } + + public Collection<String> getDefinedResourceBundles(int offset) { + Collection<String> result = new HashSet<String>(); + for (String s : bundleReferences.values()) { + if (s != null) { + result.add(s); + } } - - public IRegion getRBReferenceAt(Long offset) { - IRegion reg = null; - - Iterator<Long> keys = rbDefReferences.keySet().iterator(); - while (keys.hasNext()) { - Long startPos = keys.next(); - if (startPos > offset) { - break; - } - - IRegion region = rbDefReferences.get(startPos); - if (region != null && region.getOffset() <= offset - && (region.getOffset() + region.getLength()) >= offset) { - reg = region; - break; - } - } - - return reg; + return result; + } + + public IRegion getRBReferenceAt(Long offset) { + IRegion reg = null; + + Iterator<Long> keys = rbDefReferences.keySet().iterator(); + while (keys.hasNext()) { + Long startPos = keys.next(); + if (startPos > offset) { + break; + } + + IRegion region = rbDefReferences.get(startPos); + if (region != null && region.getOffset() <= offset + && (region.getOffset() + region.getLength()) >= offset) { + reg = region; + break; + } } + + return reg; + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ImageUtils.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ImageUtils.java index 58f1b718..8db317c5 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ImageUtils.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ImageUtils.java @@ -1,12 +1,12 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2007 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the 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: - * Michael Gasser - initial API and implementation + * Michael Gasser - initial implementation ******************************************************************************/ package org.eclipse.babel.tapiji.tools.rbmanager; @@ -20,102 +20,102 @@ import org.eclipse.swt.graphics.Image; public class ImageUtils { - private static final ImageRegistry imageRegistry = new ImageRegistry(); - - private static final String WARNING_FLAG_IMAGE = "warning_flag.gif"; - private static final String FRAGMENT_FLAG_IMAGE = "fragment_flag.gif"; - public static final String WARNING_IMAGE = "warning.gif"; - public static final String FRAGMENT_PROJECT_IMAGE = "fragmentproject.gif"; - public static final String RESOURCEBUNDLE_IMAGE = "resourcebundle.gif"; - public static final String EXPAND = "expand.gif"; - public static final String DEFAULT_LOCALICON = File.separatorChar - + "countries" + File.separatorChar + "_f.gif"; - public static final String LOCATION_WITHOUT_ICON = File.separatorChar - + "countries" + File.separatorChar + "un.gif"; - - /** - * @return a Image from the folder 'icons' - * @throws URISyntaxException - */ - public static Image getBaseImage(String imageName) { - Image image = imageRegistry.get(imageName); - if (image == null) { - ImageDescriptor descriptor = RBManagerActivator - .getImageDescriptor(imageName); - - if (descriptor.getImageData() != null) { - image = descriptor.createImage(false); - imageRegistry.put(imageName, image); - } - } - - return image; + private static final ImageRegistry imageRegistry = new ImageRegistry(); + + private static final String WARNING_FLAG_IMAGE = "warning_flag.gif"; //$NON-NLS-1$ + private static final String FRAGMENT_FLAG_IMAGE = "fragment_flag.gif"; //$NON-NLS-1$ + public static final String WARNING_IMAGE = "warning.gif"; //$NON-NLS-1$ + public static final String FRAGMENT_PROJECT_IMAGE = "fragmentproject.gif"; //$NON-NLS-1$ + public static final String RESOURCEBUNDLE_IMAGE = "resourcebundle.gif"; //$NON-NLS-1$ + public static final String EXPAND = "expand.gif"; //$NON-NLS-1$ + public static final String DEFAULT_LOCALICON = File.separatorChar + + "countries" + File.separatorChar + "_f.gif"; + public static final String LOCATION_WITHOUT_ICON = File.separatorChar + + "countries" + File.separatorChar + "un.gif"; + + /** + * @return a Image from the folder 'icons' + * @throws URISyntaxException + */ + public static Image getBaseImage(String imageName) { + Image image = imageRegistry.get(imageName); + if (image == null) { + ImageDescriptor descriptor = RBManagerActivator + .getImageDescriptor(imageName); + + if (descriptor.getImageData() != null) { + image = descriptor.createImage(false); + imageRegistry.put(imageName, image); + } } - /** - * @param baseImage - * @return baseImage with a overlay warning-image - */ - public static Image getImageWithWarning(Image baseImage) { - String imageWithWarningId = baseImage.toString() + ".w"; - Image imageWithWarning = imageRegistry.get(imageWithWarningId); - - if (imageWithWarning == null) { - Image warningImage = getBaseImage(WARNING_FLAG_IMAGE); - imageWithWarning = new OverlayIcon(baseImage, warningImage, - OverlayIcon.BOTTOM_LEFT).createImage(); - imageRegistry.put(imageWithWarningId, imageWithWarning); - } - - return imageWithWarning; + return image; + } + + /** + * @param baseImage + * @return baseImage with a overlay warning-image + */ + public static Image getImageWithWarning(Image baseImage) { + String imageWithWarningId = baseImage.toString() + ".w"; + Image imageWithWarning = imageRegistry.get(imageWithWarningId); + + if (imageWithWarning == null) { + Image warningImage = getBaseImage(WARNING_FLAG_IMAGE); + imageWithWarning = new OverlayIcon(baseImage, warningImage, + OverlayIcon.BOTTOM_LEFT).createImage(); + imageRegistry.put(imageWithWarningId, imageWithWarning); } - /** - * - * @param baseImage - * @return baseImage with a overlay fragment-image - */ - public static Image getImageWithFragment(Image baseImage) { - String imageWithFragmentId = baseImage.toString() + ".f"; - Image imageWithFragment = imageRegistry.get(imageWithFragmentId); - - if (imageWithFragment == null) { - Image fragement = getBaseImage(FRAGMENT_FLAG_IMAGE); - imageWithFragment = new OverlayIcon(baseImage, fragement, - OverlayIcon.BOTTOM_RIGHT).createImage(); - imageRegistry.put(imageWithFragmentId, imageWithFragment); - } - - return imageWithFragment; + return imageWithWarning; + } + + /** + * + * @param baseImage + * @return baseImage with a overlay fragment-image + */ + public static Image getImageWithFragment(Image baseImage) { + String imageWithFragmentId = baseImage.toString() + ".f"; + Image imageWithFragment = imageRegistry.get(imageWithFragmentId); + + if (imageWithFragment == null) { + Image fragement = getBaseImage(FRAGMENT_FLAG_IMAGE); + imageWithFragment = new OverlayIcon(baseImage, fragement, + OverlayIcon.BOTTOM_RIGHT).createImage(); + imageRegistry.put(imageWithFragmentId, imageWithFragment); } - /** - * @return a Image with a flag of the given country - */ - public static Image getLocalIcon(Locale locale) { - String imageName; - Image image = null; - - if (locale != null && !locale.getCountry().equals("")) { - imageName = File.separatorChar + "countries" + File.separatorChar - + locale.getCountry().toLowerCase() + ".gif"; - image = getBaseImage(imageName); - } else { - if (locale != null) { - imageName = File.separatorChar + "countries" - + File.separatorChar + "l_" - + locale.getLanguage().toLowerCase() + ".gif"; - image = getBaseImage(imageName); - } else { - imageName = DEFAULT_LOCALICON.toLowerCase(); // Default locale - // icon - image = getBaseImage(imageName); - } - } - - if (image == null) - image = getBaseImage(LOCATION_WITHOUT_ICON.toLowerCase()); - return image; + return imageWithFragment; + } + + /** + * @return a Image with a flag of the given country + */ + public static Image getLocalIcon(Locale locale) { + String imageName; + Image image = null; + + if (locale != null && !locale.getCountry().equals("")) { + imageName = File.separatorChar + "countries" + File.separatorChar + + locale.getCountry().toLowerCase() + ".gif"; + image = getBaseImage(imageName); + } else { + if (locale != null) { + imageName = File.separatorChar + "countries" + + File.separatorChar + "l_" + + locale.getLanguage().toLowerCase() + ".gif"; + image = getBaseImage(imageName); + } else { + imageName = DEFAULT_LOCALICON.toLowerCase(); // Default locale + // icon + image = getBaseImage(imageName); + } } + if (image == null) + image = getBaseImage(LOCATION_WITHOUT_ICON.toLowerCase()); + return image; + } + } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/RBManagerActivator.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/RBManagerActivator.java index 0b5d62a6..68faf55f 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/RBManagerActivator.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/RBManagerActivator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -18,54 +18,54 @@ * The activator class controls the plug-in life cycle */ public class RBManagerActivator extends AbstractUIPlugin { - // The plug-in ID - public static final String PLUGIN_ID = "org.eclipse.babel.tapiji.tools.rbmanager"; //$NON-NLS-1$ - // The shared instance - private static RBManagerActivator plugin; + // The plug-in ID + public static final String PLUGIN_ID = "org.eclipse.babel.tapiji.tools.rbmanager"; //$NON-NLS-1$ + // The shared instance + private static RBManagerActivator plugin; - /** - * The constructor - */ - public RBManagerActivator() { - } + /** + * The constructor + */ + public RBManagerActivator() { + } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext - * ) - */ - public void start(BundleContext context) throws Exception { - super.start(context); - plugin = this; - } + /* + * (non-Javadoc) + * + * @see + * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext + * ) + */ + public void start(BundleContext context) throws Exception { + super.start(context); + plugin = this; + } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext - * ) - */ - public void stop(BundleContext context) throws Exception { - plugin = null; - super.stop(context); - } + /* + * (non-Javadoc) + * + * @see + * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext + * ) + */ + public void stop(BundleContext context) throws Exception { + plugin = null; + super.stop(context); + } - /** - * Returns the shared instance - * - * @return the shared instance - */ - public static RBManagerActivator getDefault() { - return plugin; - } + /** + * Returns the shared instance + * + * @return the shared instance + */ + public static RBManagerActivator getDefault() { + return plugin; + } - public static ImageDescriptor getImageDescriptor(String name) { - String path = "icons/" + name; + public static ImageDescriptor getImageDescriptor(String name) { + String path = "icons/" + name; - return imageDescriptorFromPlugin(PLUGIN_ID, path); - } + return imageDescriptorFromPlugin(PLUGIN_ID, path); + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java index f80ac230..4d7ed6f7 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/RBLocation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -16,55 +16,55 @@ import org.eclipse.core.resources.IFile; public class RBLocation implements ILocation { - private IFile file; - private int startPos, endPos; - private String language; - private Serializable data; - private ILocation sameValuePartner; + private IFile file; + private int startPos, endPos; + private String language; + private Serializable data; + private ILocation sameValuePartner; - public RBLocation(IFile file, int startPos, int endPos, String language) { - this.file = file; - this.startPos = startPos; - this.endPos = endPos; - this.language = language; - } + public RBLocation(IFile file, int startPos, int endPos, String language) { + this.file = file; + this.startPos = startPos; + this.endPos = endPos; + this.language = language; + } - public RBLocation(IFile file, int startPos, int endPos, String language, - ILocation sameValuePartner) { - this(file, startPos, endPos, language); - this.sameValuePartner = sameValuePartner; - } + public RBLocation(IFile file, int startPos, int endPos, String language, + ILocation sameValuePartner) { + this(file, startPos, endPos, language); + this.sameValuePartner = sameValuePartner; + } - @Override - public IFile getFile() { - return file; - } + @Override + public IFile getFile() { + return file; + } - @Override - public int getStartPos() { - return startPos; - } + @Override + public int getStartPos() { + return startPos; + } - @Override - public int getEndPos() { - return endPos; - } + @Override + public int getEndPos() { + return endPos; + } - @Override - public String getLiteral() { - return language; - } + @Override + public String getLiteral() { + return language; + } - @Override - public Serializable getData() { - return data; - } + @Override + public Serializable getData() { + return data; + } - public void setData(Serializable data) { - this.data = data; - } + public void setData(Serializable data) { + this.data = data; + } - public ILocation getSameValuePartner() { - return sameValuePartner; - } + public ILocation getSameValuePartner() { + return sameValuePartner; + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java index ec32b805..8cf1ea0f 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/ResourceBundleAuditor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -43,221 +43,221 @@ * */ public class ResourceBundleAuditor extends I18nRBAuditor { - private static final String LANGUAGE_ATTRIBUTE = "key"; + private static final String LANGUAGE_ATTRIBUTE = "key"; - private List<ILocation> unspecifiedKeys = new LinkedList<ILocation>(); - private Map<ILocation, ILocation> sameValues = new HashMap<ILocation, ILocation>(); - private List<ILocation> missingLanguages = new LinkedList<ILocation>(); - private List<String> seenRBs = new LinkedList<String>(); + private List<ILocation> unspecifiedKeys = new LinkedList<ILocation>(); + private Map<ILocation, ILocation> sameValues = new HashMap<ILocation, ILocation>(); + private List<ILocation> missingLanguages = new LinkedList<ILocation>(); + private List<String> seenRBs = new LinkedList<String>(); - @Override - public String[] getFileEndings() { - return new String[] { "properties" }; - } + @Override + public String[] getFileEndings() { + return new String[] { "properties" }; + } - @Override - public String getContextId() { - return "resourcebundle"; - } + @Override + public String getContextId() { + return "resourcebundle"; + } - @Override - public List<ILocation> getUnspecifiedKeyReferences() { - return unspecifiedKeys; - } + @Override + public List<ILocation> getUnspecifiedKeyReferences() { + return unspecifiedKeys; + } - @Override - public Map<ILocation, ILocation> getSameValuesReferences() { - return sameValues; - } + @Override + public Map<ILocation, ILocation> getSameValuesReferences() { + return sameValues; + } - @Override - public List<ILocation> getMissingLanguageReferences() { - return missingLanguages; - } + @Override + public List<ILocation> getMissingLanguageReferences() { + return missingLanguages; + } - /* - * Forgets all save rbIds in seenRB and reset all problem-lists - */ - @Override - public void resetProblems() { - unspecifiedKeys = new LinkedList<ILocation>(); - sameValues = new HashMap<ILocation, ILocation>(); - missingLanguages = new LinkedList<ILocation>(); - seenRBs = new LinkedList<String>(); - } + /* + * Forgets all save rbIds in seenRB and reset all problem-lists + */ + @Override + public void resetProblems() { + unspecifiedKeys = new LinkedList<ILocation>(); + sameValues = new HashMap<ILocation, ILocation>(); + missingLanguages = new LinkedList<ILocation>(); + seenRBs = new LinkedList<String>(); + } - /* - * Finds the corresponding ResouceBundle for the resource. Checks if the - * ResourceBundle is already audit and it is not already executed audit the - * hole ResourceBundle and save the rbId in seenRB - */ - @Override - public void audit(IResource resource) { - if (!RBFileUtils.isResourceBundleFile(resource)) { - return; - } + /* + * Finds the corresponding ResouceBundle for the resource. Checks if the + * ResourceBundle is already audit and it is not already executed audit the + * hole ResourceBundle and save the rbId in seenRB + */ + @Override + public void audit(IResource resource) { + if (!RBFileUtils.isResourceBundleFile(resource)) { + return; + } - IFile file = (IFile) resource; - String rbId = RBFileUtils.getCorrespondingResourceBundleId(file); + IFile file = (IFile) resource; + String rbId = RBFileUtils.getCorrespondingResourceBundleId(file); - if (!seenRBs.contains(rbId)) { - ResourceBundleManager rbmanager = ResourceBundleManager - .getManager(file.getProject()); - audit(rbId, rbmanager); - seenRBs.add(rbId); - } else { - return; - } + if (!seenRBs.contains(rbId)) { + ResourceBundleManager rbmanager = ResourceBundleManager + .getManager(file.getProject()); + audit(rbId, rbmanager); + seenRBs.add(rbId); + } else { + return; } + } - /* - * audits all files of a resourcebundle - */ - public void audit(String rbId, ResourceBundleManager rbmanager) { - IConfiguration configuration = ConfigurationManager.getInstance() - .getConfiguration(); - IMessagesBundleGroup bundlegroup = rbmanager.getResourceBundle(rbId); - Collection<IResource> bundlefile = rbmanager.getResourceBundles(rbId); - String[] keys = bundlegroup.getMessageKeys(); + /* + * audits all files of a resourcebundle + */ + public void audit(String rbId, ResourceBundleManager rbmanager) { + IConfiguration configuration = ConfigurationManager.getInstance() + .getConfiguration(); + IMessagesBundleGroup bundlegroup = rbmanager.getResourceBundle(rbId); + Collection<IResource> bundlefile = rbmanager.getResourceBundles(rbId); + String[] keys = bundlegroup.getMessageKeys(); - for (IResource r : bundlefile) { - IFile f1 = (IFile) r; + for (IResource r : bundlefile) { + IFile f1 = (IFile) r; - for (String key : keys) { - // check if all keys have a value + for (String key : keys) { + // check if all keys have a value - if (auditUnspecifiedKey(f1, key, bundlegroup)) { - /* do nothing - all just done */ - } else { - // check if a key has the same value like a key of an other - // properties-file - if (configuration.getAuditSameValue() - && bundlefile.size() > 1) { - for (IResource r2 : bundlefile) { - IFile f2 = (IFile) r2; - auditSameValues(f1, f2, key, bundlegroup); - } - } - } + if (auditUnspecifiedKey(f1, key, bundlegroup)) { + /* do nothing - all just done */ + } else { + // check if a key has the same value like a key of an other + // properties-file + if (configuration.getAuditSameValue() + && bundlefile.size() > 1) { + for (IResource r2 : bundlefile) { + IFile f2 = (IFile) r2; + auditSameValues(f1, f2, key, bundlegroup); } + } } + } + } - if (configuration.getAuditMissingLanguage()) { - // checks if the resourcebundle supports all project-languages - Set<Locale> rbLocales = rbmanager.getProvidedLocales(rbId); - Set<Locale> projectLocales = rbmanager.getProjectProvidedLocales(); + if (configuration.getAuditMissingLanguage()) { + // checks if the resourcebundle supports all project-languages + Set<Locale> rbLocales = rbmanager.getProvidedLocales(rbId); + Set<Locale> projectLocales = rbmanager.getProjectProvidedLocales(); - auditMissingLanguage(rbLocales, projectLocales, rbmanager, rbId); - } + auditMissingLanguage(rbLocales, projectLocales, rbmanager, rbId); } + } - /* - * Audits the file if the key is not specified. If the value is null reports - * a problem. - */ - private boolean auditUnspecifiedKey(IFile f1, String key, - IMessagesBundleGroup bundlegroup) { - if (bundlegroup.getMessage(key, RBFileUtils.getLocale(f1)) == null) { - int pos = calculateKeyLine(key, f1); - unspecifiedKeys.add(new RBLocation(f1, pos, pos + 1, key)); - return true; - } else { - return false; - } + /* + * Audits the file if the key is not specified. If the value is null reports + * a problem. + */ + private boolean auditUnspecifiedKey(IFile f1, String key, + IMessagesBundleGroup bundlegroup) { + if (bundlegroup.getMessage(key, RBFileUtils.getLocale(f1)) == null) { + int pos = calculateKeyLine(key, f1); + unspecifiedKeys.add(new RBLocation(f1, pos, pos + 1, key)); + return true; + } else { + return false; } + } - /* - * Compares a key in different files and reports a problem, if the values - * are same. It doesn't compare the files if one file is the Default-file - */ - private void auditSameValues(IFile f1, IFile f2, String key, - IMessagesBundleGroup bundlegroup) { - Locale l1 = RBFileUtils.getLocale(f1); - Locale l2 = RBFileUtils.getLocale(f2); + /* + * Compares a key in different files and reports a problem, if the values + * are same. It doesn't compare the files if one file is the Default-file + */ + private void auditSameValues(IFile f1, IFile f2, String key, + IMessagesBundleGroup bundlegroup) { + Locale l1 = RBFileUtils.getLocale(f1); + Locale l2 = RBFileUtils.getLocale(f2); - if (!l2.equals(l1) - && !(l1.toString().equals("") || l2.toString().equals(""))) { - IMessage message = bundlegroup.getMessage(key, l2); + if (!l2.equals(l1) + && !(l1.toString().equals("") || l2.toString().equals(""))) { + IMessage message = bundlegroup.getMessage(key, l2); - if (message != null) { - if (bundlegroup.getMessage(key, l1).getValue() - .equals(message.getValue())) { - int pos1 = calculateKeyLine(key, f1); - int pos2 = calculateKeyLine(key, f2); - sameValues.put(new RBLocation(f1, pos1, pos1 + 1, key), - new RBLocation(f2, pos2, pos2 + 1, key)); - } - } + if (message != null) { + if (bundlegroup.getMessage(key, l1).getValue() + .equals(message.getValue())) { + int pos1 = calculateKeyLine(key, f1); + int pos2 = calculateKeyLine(key, f2); + sameValues.put(new RBLocation(f1, pos1, pos1 + 1, key), + new RBLocation(f2, pos2, pos2 + 1, key)); } + } } + } - /* - * Checks if the resourcebundle supports all project-languages and report - * missing languages. - */ - private void auditMissingLanguage(Set<Locale> rbLocales, - Set<Locale> projectLocales, ResourceBundleManager rbmanager, - String rbId) { - for (Locale pLocale : projectLocales) { - if (!rbLocales.contains(pLocale)) { - String language = pLocale != null ? pLocale.toString() - : ResourceBundleManager.defaultLocaleTag; + /* + * Checks if the resourcebundle supports all project-languages and report + * missing languages. + */ + private void auditMissingLanguage(Set<Locale> rbLocales, + Set<Locale> projectLocales, ResourceBundleManager rbmanager, + String rbId) { + for (Locale pLocale : projectLocales) { + if (!rbLocales.contains(pLocale)) { + String language = pLocale != null ? pLocale.toString() + : ResourceBundleManager.defaultLocaleTag; - // Add Warning to default-file or a random chosen file - IResource representative = rbmanager.getResourceBundleFile( - rbId, null); - if (representative == null) { - representative = rbmanager.getRandomFile(rbId); - } - missingLanguages.add(new RBLocation((IFile) representative, 1, - 2, language)); - } + // Add Warning to default-file or a random chosen file + IResource representative = rbmanager.getResourceBundleFile( + rbId, null); + if (representative == null) { + representative = rbmanager.getRandomFile(rbId); } + missingLanguages.add(new RBLocation((IFile) representative, 1, + 2, language)); + } } + } - /* - * Finds a position where the key is located or missing - */ - private int calculateKeyLine(String key, IFile file) { - int linenumber = 1; - try { - // if (!Boolean.valueOf(System.getProperty("dirty"))) { - // System.setProperty("dirty", "true"); - file.refreshLocal(IFile.DEPTH_ZERO, null); - InputStream is = file.getContents(); - BufferedReader bf = new BufferedReader(new InputStreamReader(is)); - String line; - while ((line = bf.readLine()) != null) { - if ((!line.isEmpty()) && (!line.startsWith("#")) - && (line.compareTo(key) > 0)) { - return linenumber; - } - linenumber++; - } - // System.setProperty("dirty", "false"); - // } - } catch (CoreException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); + /* + * Finds a position where the key is located or missing + */ + private int calculateKeyLine(String key, IFile file) { + int linenumber = 1; + try { + // if (!Boolean.valueOf(System.getProperty("dirty"))) { + // System.setProperty("dirty", "true"); + file.refreshLocal(IFile.DEPTH_ZERO, null); + InputStream is = file.getContents(); + BufferedReader bf = new BufferedReader(new InputStreamReader(is)); + String line; + while ((line = bf.readLine()) != null) { + if ((!line.isEmpty()) && (!line.startsWith("#")) + && (line.compareTo(key) > 0)) { + return linenumber; } - return linenumber; + linenumber++; + } + // System.setProperty("dirty", "false"); + // } + } catch (CoreException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); } + return linenumber; + } - @Override - public List<IMarkerResolution> getMarkerResolutions(IMarker marker) { - List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>(); + @Override + public List<IMarkerResolution> getMarkerResolutions(IMarker marker) { + List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>(); - switch (marker.getAttribute("cause", -1)) { - case IMarkerConstants.CAUSE_MISSING_LANGUAGE: - Locale l = new Locale(marker.getAttribute(LANGUAGE_ATTRIBUTE, "")); // TODO - // change - // Name - resolutions.add(new MissingLanguageResolution(l)); - break; - } - - return resolutions; + switch (marker.getAttribute("cause", -1)) { + case IMarkerConstants.CAUSE_MISSING_LANGUAGE: + Locale l = new Locale(marker.getAttribute(LANGUAGE_ATTRIBUTE, "")); // TODO + // change + // Name + resolutions.add(new MissingLanguageResolution(l)); + break; } + return resolutions; + } + } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java index 42a91d0a..912d27e1 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/auditor/quickfix/MissingLanguageResolution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -21,33 +21,33 @@ public class MissingLanguageResolution implements IMarkerResolution2 { - private Locale language; - - public MissingLanguageResolution(Locale language) { - this.language = language; - } - - @Override - public String getLabel() { - return "Add missing language '" + language + "'"; - } - - @Override - public void run(IMarker marker) { - IResource res = marker.getResource(); - String rbId = ResourceBundleManager.getResourceBundleId(res); - LanguageUtils.addLanguageToResourceBundle(res.getProject(), rbId, - language); - } - - @Override - public String getDescription() { - return "Creates a new localized properties-file with the same basename as the resourcebundle"; - } - - @Override - public Image getImage() { - return null; - } + private Locale language; + + public MissingLanguageResolution(Locale language) { + this.language = language; + } + + @Override + public String getLabel() { + return "Add missing language '" + language + "'"; + } + + @Override + public void run(IMarker marker) { + IResource res = marker.getResource(); + String rbId = ResourceBundleManager.getResourceBundleId(res); + LanguageUtils.addLanguageToResourceBundle(res.getProject(), rbId, + language); + } + + @Override + public String getDescription() { + return "Creates a new localized properties-file with the same basename as the resourcebundle"; + } + + @Override + public Image getImage() { + return null; + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContainer.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContainer.java index 22561cdf..fedbd4f1 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContainer.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContainer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -18,58 +18,58 @@ import org.eclipse.core.runtime.jobs.Job; public class VirtualContainer { - protected ResourceBundleManager rbmanager; - protected IContainer container; - protected int rbCount; + protected ResourceBundleManager rbmanager; + protected IContainer container; + protected int rbCount; - public VirtualContainer(IContainer container1, boolean countResourceBundles) { - this.container = container1; - rbmanager = ResourceBundleManager.getManager(container.getProject()); - if (countResourceBundles) { - rbCount = 1; - new Job("count ResourceBundles") { - @Override - protected IStatus run(IProgressMonitor monitor) { - recount(); - return Status.OK_STATUS; - } - }.schedule(); - } else { - rbCount = 0; + public VirtualContainer(IContainer container1, boolean countResourceBundles) { + this.container = container1; + rbmanager = ResourceBundleManager.getManager(container.getProject()); + if (countResourceBundles) { + rbCount = 1; + new Job("count ResourceBundles") { + @Override + protected IStatus run(IProgressMonitor monitor) { + recount(); + return Status.OK_STATUS; } + }.schedule(); + } else { + rbCount = 0; } + } - protected VirtualContainer(IContainer container) { - this.container = container; - } + protected VirtualContainer(IContainer container) { + this.container = container; + } - public VirtualContainer(IContainer container, int rbCount) { - this(container, false); - this.rbCount = rbCount; - } + public VirtualContainer(IContainer container, int rbCount) { + this(container, false); + this.rbCount = rbCount; + } - public ResourceBundleManager getResourceBundleManager() { - if (rbmanager == null) { - rbmanager = ResourceBundleManager - .getManager(container.getProject()); - } - return rbmanager; + public ResourceBundleManager getResourceBundleManager() { + if (rbmanager == null) { + rbmanager = ResourceBundleManager + .getManager(container.getProject()); } + return rbmanager; + } - public IContainer getContainer() { - return container; - } + public IContainer getContainer() { + return container; + } - public void setRbCounter(int rbCount) { - this.rbCount = rbCount; - } + public void setRbCounter(int rbCount) { + this.rbCount = rbCount; + } - public int getRbCount() { - return rbCount; - } + public int getRbCount() { + return rbCount; + } - public void recount() { - rbCount = org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils - .countRecursiveResourceBundle(container); - } + public void recount() { + rbCount = org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils + .countRecursiveResourceBundle(container); + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContentManager.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContentManager.java index fa90a287..a6c1447a 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContentManager.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualContentManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -16,52 +16,52 @@ import org.eclipse.core.resources.IContainer; public class VirtualContentManager { - private Map<IContainer, VirtualContainer> containers = new HashMap<IContainer, VirtualContainer>(); - private Map<String, VirtualResourceBundle> vResourceBundles = new HashMap<String, VirtualResourceBundle>(); + private Map<IContainer, VirtualContainer> containers = new HashMap<IContainer, VirtualContainer>(); + private Map<String, VirtualResourceBundle> vResourceBundles = new HashMap<String, VirtualResourceBundle>(); - static private VirtualContentManager singelton = null; + static private VirtualContentManager singelton = null; - private VirtualContentManager() { - } + private VirtualContentManager() { + } - public static VirtualContentManager getVirtualContentManager() { - if (singelton == null) { - singelton = new VirtualContentManager(); - } - return singelton; + public static VirtualContentManager getVirtualContentManager() { + if (singelton == null) { + singelton = new VirtualContentManager(); } + return singelton; + } - public VirtualContainer getContainer(IContainer container) { - return containers.get(container); - } + public VirtualContainer getContainer(IContainer container) { + return containers.get(container); + } - public void addVContainer(IContainer container, VirtualContainer vContainer) { - containers.put(container, vContainer); - } + public void addVContainer(IContainer container, VirtualContainer vContainer) { + containers.put(container, vContainer); + } - public void removeVContainer(IContainer container) { - vResourceBundles.remove(container); - } + public void removeVContainer(IContainer container) { + vResourceBundles.remove(container); + } - public VirtualResourceBundle getVResourceBundles(String vRbId) { - return vResourceBundles.get(vRbId); - } + public VirtualResourceBundle getVResourceBundles(String vRbId) { + return vResourceBundles.get(vRbId); + } - public void addVResourceBundle(String vRbId, - VirtualResourceBundle vResourceBundle) { - vResourceBundles.put(vRbId, vResourceBundle); - } + public void addVResourceBundle(String vRbId, + VirtualResourceBundle vResourceBundle) { + vResourceBundles.put(vRbId, vResourceBundle); + } - public void removeVResourceBundle(String vRbId) { - vResourceBundles.remove(vRbId); - } + public void removeVResourceBundle(String vRbId) { + vResourceBundles.remove(vRbId); + } - public boolean containsVResourceBundles(String vRbId) { - return vResourceBundles.containsKey(vRbId); - } + public boolean containsVResourceBundles(String vRbId) { + return vResourceBundles.containsKey(vRbId); + } - public void reset() { - vResourceBundles.clear(); - containers.clear(); - } + public void reset() { + vResourceBundles.clear(); + containers.clear(); + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualProject.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualProject.java index 1748928f..44cd4a76 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualProject.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualProject.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -23,52 +23,52 @@ * */ public class VirtualProject extends VirtualContainer { - private boolean isFragment; - private IProject hostProject; - private List<IProject> fragmentProjects = new LinkedList<IProject>(); + private boolean isFragment; + private IProject hostProject; + private List<IProject> fragmentProjects = new LinkedList<IProject>(); - // Slow - public VirtualProject(IProject project, boolean countResourceBundles) { - super(project, countResourceBundles); - isFragment = FragmentProjectUtils.isFragment(project); - if (isFragment) { - hostProject = FragmentProjectUtils.getFragmentHost(project); - } else - fragmentProjects = FragmentProjectUtils.getFragments(project); - } + // Slow + public VirtualProject(IProject project, boolean countResourceBundles) { + super(project, countResourceBundles); + isFragment = FragmentProjectUtils.isFragment(project); + if (isFragment) { + hostProject = FragmentProjectUtils.getFragmentHost(project); + } else + fragmentProjects = FragmentProjectUtils.getFragments(project); + } - /* - * No fragment search - */ - public VirtualProject(final IProject project, boolean isFragment, - boolean countResourceBundles) { - super(project, countResourceBundles); - this.isFragment = isFragment; - // Display.getDefault().asyncExec(new Runnable() { - // @Override - // public void run() { - // hostProject = FragmentProjectUtils.getFragmentHost(project); - // } - // }); - } + /* + * No fragment search + */ + public VirtualProject(final IProject project, boolean isFragment, + boolean countResourceBundles) { + super(project, countResourceBundles); + this.isFragment = isFragment; + // Display.getDefault().asyncExec(new Runnable() { + // @Override + // public void run() { + // hostProject = FragmentProjectUtils.getFragmentHost(project); + // } + // }); + } - public Set<Locale> getProvidedLocales() { - return rbmanager.getProjectProvidedLocales(); - } + public Set<Locale> getProvidedLocales() { + return rbmanager.getProjectProvidedLocales(); + } - public boolean isFragment() { - return isFragment; - } + public boolean isFragment() { + return isFragment; + } - public IProject getHostProject() { - return hostProject; - } + public IProject getHostProject() { + return hostProject; + } - public boolean hasFragments() { - return !fragmentProjects.isEmpty(); - } + public boolean hasFragments() { + return !fragmentProjects.isEmpty(); + } - public List<IProject> getFragmets() { - return fragmentProjects; - } + public List<IProject> getFragmets() { + return fragmentProjects; + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualResourceBundle.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualResourceBundle.java index 6dfc7f76..ce0b96df 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualResourceBundle.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/model/VirtualResourceBundle.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -18,43 +18,43 @@ import org.eclipse.core.runtime.IPath; public class VirtualResourceBundle { - private String resourcebundlename; - private String resourcebundleId; - private ResourceBundleManager rbmanager; - - public VirtualResourceBundle(String rbname, String rbId, - ResourceBundleManager rbmanager) { - this.rbmanager = rbmanager; - resourcebundlename = rbname; - resourcebundleId = rbId; - } - - public ResourceBundleManager getResourceBundleManager() { - return rbmanager; - } - - public String getResourceBundleId() { - return resourcebundleId; - } - - @Override - public String toString() { - return resourcebundleId; - } - - public IPath getFullPath() { - return rbmanager.getRandomFile(resourcebundleId).getFullPath(); - } - - public String getName() { - return resourcebundlename; - } - - public Collection<IResource> getFiles() { - return rbmanager.getResourceBundles(resourcebundleId); - } - - public IFile getRandomFile() { - return rbmanager.getRandomFile(resourcebundleId); - } + private String resourcebundlename; + private String resourcebundleId; + private ResourceBundleManager rbmanager; + + public VirtualResourceBundle(String rbname, String rbId, + ResourceBundleManager rbmanager) { + this.rbmanager = rbmanager; + resourcebundlename = rbname; + resourcebundleId = rbId; + } + + public ResourceBundleManager getResourceBundleManager() { + return rbmanager; + } + + public String getResourceBundleId() { + return resourcebundleId; + } + + @Override + public String toString() { + return resourcebundleId; + } + + public IPath getFullPath() { + return rbmanager.getRandomFile(resourcebundleId).getFullPath(); + } + + public String getName() { + return resourcebundlename; + } + + public Collection<IResource> getFiles() { + return rbmanager.getResourceBundles(resourcebundleId); + } + + public IFile getRandomFile() { + return rbmanager.getRandomFile(resourcebundleId); + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/Hover.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/Hover.java index f59c796e..49d72909 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/Hover.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/Hover.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -28,92 +28,92 @@ import org.eclipse.swt.widgets.Widget; public class Hover { - private Shell hoverShell; - private Point hoverPosition; - private List<HoverInformant> informant; + private Shell hoverShell; + private Point hoverPosition; + private List<HoverInformant> informant; - public Hover(Shell parent, List<HoverInformant> informant) { - this.informant = informant; - hoverShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL); - Display display = hoverShell.getDisplay(); + public Hover(Shell parent, List<HoverInformant> informant) { + this.informant = informant; + hoverShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL); + Display display = hoverShell.getDisplay(); - GridLayout gridLayout = new GridLayout(1, false); - gridLayout.verticalSpacing = 2; - hoverShell.setLayout(gridLayout); + GridLayout gridLayout = new GridLayout(1, false); + gridLayout.verticalSpacing = 2; + hoverShell.setLayout(gridLayout); - hoverShell.setBackground(display - .getSystemColor(SWT.COLOR_INFO_BACKGROUND)); - hoverShell.setForeground(display - .getSystemColor(SWT.COLOR_INFO_FOREGROUND)); - } + hoverShell.setBackground(display + .getSystemColor(SWT.COLOR_INFO_BACKGROUND)); + hoverShell.setForeground(display + .getSystemColor(SWT.COLOR_INFO_FOREGROUND)); + } - private void setHoverLocation(Shell shell, Point position) { - Rectangle displayBounds = shell.getDisplay().getBounds(); - Rectangle shellBounds = shell.getBounds(); - shellBounds.x = Math.max( - Math.min(position.x + 1, displayBounds.width - - shellBounds.width), 0); - shellBounds.y = Math.max( - Math.min(position.y + 16, displayBounds.height - - (shellBounds.height + 1)), 0); - shell.setBounds(shellBounds); - } + private void setHoverLocation(Shell shell, Point position) { + Rectangle displayBounds = shell.getDisplay().getBounds(); + Rectangle shellBounds = shell.getBounds(); + shellBounds.x = Math.max( + Math.min(position.x + 1, displayBounds.width + - shellBounds.width), 0); + shellBounds.y = Math.max( + Math.min(position.y + 16, displayBounds.height + - (shellBounds.height + 1)), 0); + shell.setBounds(shellBounds); + } - public void activateHoverHelp(final Control control) { + public void activateHoverHelp(final Control control) { - control.addMouseListener(new MouseAdapter() { - public void mouseDown(MouseEvent e) { - if (hoverShell != null && hoverShell.isVisible()) { - hoverShell.setVisible(false); - } - } - }); + control.addMouseListener(new MouseAdapter() { + public void mouseDown(MouseEvent e) { + if (hoverShell != null && hoverShell.isVisible()) { + hoverShell.setVisible(false); + } + } + }); - control.addMouseTrackListener(new MouseTrackAdapter() { - public void mouseExit(MouseEvent e) { - if (hoverShell != null && hoverShell.isVisible()) - hoverShell.setVisible(false); - } + control.addMouseTrackListener(new MouseTrackAdapter() { + public void mouseExit(MouseEvent e) { + if (hoverShell != null && hoverShell.isVisible()) + hoverShell.setVisible(false); + } - public void mouseHover(MouseEvent event) { - Point pt = new Point(event.x, event.y); - Widget widget = event.widget; - if (widget instanceof ToolBar) { - ToolBar w = (ToolBar) widget; - widget = w.getItem(pt); - } - if (widget instanceof Table) { - Table w = (Table) widget; - widget = w.getItem(pt); - } - if (widget instanceof Tree) { - Tree w = (Tree) widget; - widget = w.getItem(pt); - } - if (widget == null) { - hoverShell.setVisible(false); - return; - } - hoverPosition = control.toDisplay(pt); + public void mouseHover(MouseEvent event) { + Point pt = new Point(event.x, event.y); + Widget widget = event.widget; + if (widget instanceof ToolBar) { + ToolBar w = (ToolBar) widget; + widget = w.getItem(pt); + } + if (widget instanceof Table) { + Table w = (Table) widget; + widget = w.getItem(pt); + } + if (widget instanceof Tree) { + Tree w = (Tree) widget; + widget = w.getItem(pt); + } + if (widget == null) { + hoverShell.setVisible(false); + return; + } + hoverPosition = control.toDisplay(pt); - boolean show = false; - Object data = widget.getData(); + boolean show = false; + Object data = widget.getData(); - for (HoverInformant hi : informant) { - hi.getInfoComposite(data, hoverShell); - if (hi.show()) - show = true; - } + for (HoverInformant hi : informant) { + hi.getInfoComposite(data, hoverShell); + if (hi.show()) + show = true; + } - if (show) { - hoverShell.pack(); - hoverShell.layout(); - setHoverLocation(hoverShell, hoverPosition); - hoverShell.setVisible(true); - } else - hoverShell.setVisible(false); + if (show) { + hoverShell.pack(); + hoverShell.layout(); + setHoverLocation(hoverShell, hoverPosition); + hoverShell.setVisible(true); + } else + hoverShell.setVisible(false); - } - }); - } + } + }); + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/HoverInformant.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/HoverInformant.java index 71a3cd1e..88c6cddf 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/HoverInformant.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/hover/HoverInformant.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -14,7 +14,7 @@ public interface HoverInformant { - public Composite getInfoComposite(Object data, Composite parent); + public Composite getInfoComposite(Object data, Composite parent); - public boolean show(); + public boolean show(); } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java index f8780b9c..18b99cac 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ExpandAllActionDelegate.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -25,33 +25,33 @@ import org.eclipse.ui.progress.UIJob; public class ExpandAllActionDelegate implements IViewActionDelegate { - private CommonViewer viewer; - - @Override - public void run(IAction action) { - Object data = viewer.getControl().getData(); - - for (final IProject p : ((IWorkspaceRoot) data).getProjects()) { - UIJob job = new UIJob("expand Projects") { - @Override - public IStatus runInUIThread(IProgressMonitor monitor) { - viewer.expandToLevel(p, AbstractTreeViewer.ALL_LEVELS); - return Status.OK_STATUS; - } - }; - - job.schedule(); + private CommonViewer viewer; + + @Override + public void run(IAction action) { + Object data = viewer.getControl().getData(); + + for (final IProject p : ((IWorkspaceRoot) data).getProjects()) { + UIJob job = new UIJob("expand Projects") { + @Override + public IStatus runInUIThread(IProgressMonitor monitor) { + viewer.expandToLevel(p, AbstractTreeViewer.ALL_LEVELS); + return Status.OK_STATUS; } - } + }; - @Override - public void selectionChanged(IAction action, ISelection selection) { - // TODO Auto-generated method stub + job.schedule(); } + } - @Override - public void init(IViewPart view) { - viewer = ((CommonNavigator) view).getCommonViewer(); - } + @Override + public void selectionChanged(IAction action, ISelection selection) { + // TODO Auto-generated method stub + } + + @Override + public void init(IViewPart view) { + viewer = ((CommonNavigator) view).getCommonViewer(); + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java index f0ee4d9c..b5f40936 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/ui/view/toolbarItems/ToggleFilterActionDelegate.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -21,47 +21,47 @@ import org.eclipse.ui.navigator.INavigatorFilterService; public class ToggleFilterActionDelegate implements IViewActionDelegate { - private INavigatorFilterService filterService; - private boolean active; - private static final String[] FILTER = { RBManagerActivator.PLUGIN_ID - + ".filter.ProblematicResourceBundleFiles" }; + private INavigatorFilterService filterService; + private boolean active; + private static final String[] FILTER = { RBManagerActivator.PLUGIN_ID + + ".filter.ProblematicResourceBundleFiles" }; - @Override - public void run(IAction action) { - if (active == true) { - filterService.activateFilterIdsAndUpdateViewer(new String[0]); - active = false; - } else { - filterService.activateFilterIdsAndUpdateViewer(FILTER); - active = true; - } + @Override + public void run(IAction action) { + if (active == true) { + filterService.activateFilterIdsAndUpdateViewer(new String[0]); + active = false; + } else { + filterService.activateFilterIdsAndUpdateViewer(FILTER); + active = true; } + } - @Override - public void selectionChanged(IAction action, ISelection selection) { - // Active when content change - } + @Override + public void selectionChanged(IAction action, ISelection selection) { + // Active when content change + } - @Override - public void init(IViewPart view) { - INavigatorContentService contentService = ((CommonNavigator) view) - .getCommonViewer().getNavigatorContentService(); + @Override + public void init(IViewPart view) { + INavigatorContentService contentService = ((CommonNavigator) view) + .getCommonViewer().getNavigatorContentService(); - filterService = contentService.getFilterService(); - filterService.activateFilterIdsAndUpdateViewer(new String[0]); - active = false; - } + filterService = contentService.getFilterService(); + filterService.activateFilterIdsAndUpdateViewer(new String[0]); + active = false; + } - @SuppressWarnings("unused") - private String[] getActiveFilterIds() { - ICommonFilterDescriptor[] fds = filterService - .getVisibleFilterDescriptors(); - String activeFilterIds[] = new String[fds.length]; + @SuppressWarnings("unused") + private String[] getActiveFilterIds() { + ICommonFilterDescriptor[] fds = filterService + .getVisibleFilterDescriptors(); + String activeFilterIds[] = new String[fds.length]; - for (int i = 0; i < fds.length; i++) - activeFilterIds[i] = fds[i].getId(); + for (int i = 0; i < fds.length; i++) + activeFilterIds[i] = fds[i].getId(); - return activeFilterIds; - } + return activeFilterIds; + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java index 722c548d..1b98016a 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/LinkHelper.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -25,25 +25,25 @@ */ public class LinkHelper implements ILinkHelper { - public static IStructuredSelection viewer; + public static IStructuredSelection viewer; - @Override - public IStructuredSelection findSelection(IEditorInput anInput) { - IFile file = ResourceUtil.getFile(anInput); - if (file != null) { - return new StructuredSelection(file); - } - return StructuredSelection.EMPTY; + @Override + public IStructuredSelection findSelection(IEditorInput anInput) { + IFile file = ResourceUtil.getFile(anInput); + if (file != null) { + return new StructuredSelection(file); } + return StructuredSelection.EMPTY; + } - @Override - public void activateEditor(IWorkbenchPage aPage, - IStructuredSelection aSelection) { - if (aSelection.getFirstElement() instanceof IFile) - try { - IDE.openEditor(aPage, (IFile) aSelection.getFirstElement()); - } catch (PartInitException e) {/**/ - } - } + @Override + public void activateEditor(IWorkbenchPage aPage, + IStructuredSelection aSelection) { + if (aSelection.getFirstElement() instanceof IFile) + try { + IDE.openEditor(aPage, (IFile) aSelection.getFirstElement()); + } catch (PartInitException e) {/**/ + } + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java index 8867b320..50ae03ab 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleContentProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -57,410 +57,410 @@ * */ public class ResourceBundleContentProvider implements ITreeContentProvider, - IResourceChangeListener, IPropertyChangeListener, - IResourceBundleChangedListener { - private static final boolean FRAGMENT_PROJECTS_IN_CONTENT = false; - private static final boolean SHOW_ONLY_PROJECTS_WITH_RBS = true; - private StructuredViewer viewer; - private VirtualContentManager vcManager; - private UIJob refresh; - private IWorkspaceRoot root; - - private List<IProject> listenedProjects; - - /** + IResourceChangeListener, IPropertyChangeListener, + IResourceBundleChangedListener { + private static final boolean FRAGMENT_PROJECTS_IN_CONTENT = false; + private static final boolean SHOW_ONLY_PROJECTS_WITH_RBS = true; + private StructuredViewer viewer; + private VirtualContentManager vcManager; + private UIJob refresh; + private IWorkspaceRoot root; + + private List<IProject> listenedProjects; + + /** * */ - public ResourceBundleContentProvider() { - ResourcesPlugin.getWorkspace().addResourceChangeListener(this, - IResourceChangeEvent.POST_CHANGE); - TapiJIPreferences.addPropertyChangeListener(this); - vcManager = VirtualContentManager.getVirtualContentManager(); - listenedProjects = new LinkedList<IProject>(); - } - - @Override - public Object[] getElements(Object inputElement) { - return getChildren(inputElement); - } - - @Override - public Object[] getChildren(final Object parentElement) { - Object[] children = null; - - if (parentElement instanceof IWorkspaceRoot) { - root = (IWorkspaceRoot) parentElement; - try { - IResource[] members = ((IWorkspaceRoot) parentElement) - .members(); - - List<Object> displayedProjects = new ArrayList<Object>(); - for (IResource r : members) { - if (r instanceof IProject) { - IProject p = (IProject) r; - if (FragmentProjectUtils.isFragment(r.getProject())) { - if (vcManager.getContainer(p) == null) { - vcManager.addVContainer(p, new VirtualProject( - p, true, false)); - } - if (FRAGMENT_PROJECTS_IN_CONTENT) { - displayedProjects.add(r); - } - } else { - if (SHOW_ONLY_PROJECTS_WITH_RBS) { - VirtualProject vP; - if ((vP = (VirtualProject) vcManager - .getContainer(p)) == null) { - vP = new VirtualProject(p, false, true); - vcManager.addVContainer(p, vP); - registerResourceBundleListner(p); - } - - if (vP.getRbCount() > 0) { - displayedProjects.add(p); - } - } else { - displayedProjects.add(p); - } - } - } + public ResourceBundleContentProvider() { + ResourcesPlugin.getWorkspace().addResourceChangeListener(this, + IResourceChangeEvent.POST_CHANGE); + TapiJIPreferences.addPropertyChangeListener(this); + vcManager = VirtualContentManager.getVirtualContentManager(); + listenedProjects = new LinkedList<IProject>(); + } + + @Override + public Object[] getElements(Object inputElement) { + return getChildren(inputElement); + } + + @Override + public Object[] getChildren(final Object parentElement) { + Object[] children = null; + + if (parentElement instanceof IWorkspaceRoot) { + root = (IWorkspaceRoot) parentElement; + try { + IResource[] members = ((IWorkspaceRoot) parentElement) + .members(); + + List<Object> displayedProjects = new ArrayList<Object>(); + for (IResource r : members) { + if (r instanceof IProject) { + IProject p = (IProject) r; + if (FragmentProjectUtils.isFragment(r.getProject())) { + if (vcManager.getContainer(p) == null) { + vcManager.addVContainer(p, new VirtualProject( + p, true, false)); + } + if (FRAGMENT_PROJECTS_IN_CONTENT) { + displayedProjects.add(r); + } + } else { + if (SHOW_ONLY_PROJECTS_WITH_RBS) { + VirtualProject vP; + if ((vP = (VirtualProject) vcManager + .getContainer(p)) == null) { + vP = new VirtualProject(p, false, true); + vcManager.addVContainer(p, vP); + registerResourceBundleListner(p); } - children = displayedProjects.toArray(); - return children; - } catch (CoreException e) { - } - } - - // if (parentElement instanceof IProject) { - // final IProject iproject = (IProject) parentElement; - // VirtualContainer vproject = vcManager.getContainer(iproject); - // if (vproject == null){ - // vproject = new VirtualProject(iproject, true); - // vcManager.addVContainer(iproject, vproject); - // } - // } - - if (parentElement instanceof IContainer) { - IContainer container = (IContainer) parentElement; - if (!((VirtualProject) vcManager - .getContainer(((IResource) parentElement).getProject())) - .isFragment()) { - try { - children = addChildren(container); - } catch (CoreException e) {/**/ + if (vP.getRbCount() > 0) { + displayedProjects.add(p); } + } else { + displayedProjects.add(p); + } } + } } - if (parentElement instanceof VirtualResourceBundle) { - VirtualResourceBundle virtualrb = (VirtualResourceBundle) parentElement; - ResourceBundleManager rbmanager = virtualrb - .getResourceBundleManager(); - children = rbmanager.getResourceBundles( - virtualrb.getResourceBundleId()).toArray(); - } - - return children != null ? children : new Object[0]; + children = displayedProjects.toArray(); + return children; + } catch (CoreException e) { + } } - /* - * Returns all ResourceBundles and sub-containers (with ResourceBundles in - * their subtree) of a Container - */ - private Object[] addChildren(IContainer container) throws CoreException { - Map<String, Object> children = new HashMap<String, Object>(); - - VirtualProject p = (VirtualProject) vcManager.getContainer(container - .getProject()); - List<IResource> members = new ArrayList<IResource>( - Arrays.asList(container.members())); - - // finds files in the corresponding fragment-projects folder - if (p.hasFragments()) { - List<IContainer> folders = ResourceUtils.getCorrespondingFolders( - container, p.getFragmets()); - for (IContainer f : folders) { - for (IResource r : f.members()) { - if (r instanceof IFile) { - members.add(r); - } - } - } + // if (parentElement instanceof IProject) { + // final IProject iproject = (IProject) parentElement; + // VirtualContainer vproject = vcManager.getContainer(iproject); + // if (vproject == null){ + // vproject = new VirtualProject(iproject, true); + // vcManager.addVContainer(iproject, vproject); + // } + // } + + if (parentElement instanceof IContainer) { + IContainer container = (IContainer) parentElement; + if (!((VirtualProject) vcManager + .getContainer(((IResource) parentElement).getProject())) + .isFragment()) { + try { + children = addChildren(container); + } catch (CoreException e) {/**/ } + } + } - for (IResource r : members) { + if (parentElement instanceof VirtualResourceBundle) { + VirtualResourceBundle virtualrb = (VirtualResourceBundle) parentElement; + ResourceBundleManager rbmanager = virtualrb + .getResourceBundleManager(); + children = rbmanager.getResourceBundles( + virtualrb.getResourceBundleId()).toArray(); + } - if (r instanceof IFile) { - String resourcebundleId = RBFileUtils - .getCorrespondingResourceBundleId((IFile) r); - if (resourcebundleId != null - && (!children.containsKey(resourcebundleId))) { - VirtualResourceBundle vrb; - - String vRBId; - - if (!p.isFragment()) { - vRBId = r.getProject() + "." + resourcebundleId; - } else { - vRBId = p.getHostProject() + "." + resourcebundleId; - } - - VirtualResourceBundle vResourceBundle = vcManager - .getVResourceBundles(vRBId); - if (vResourceBundle == null) { - String resourcebundleName = ResourceBundleManager - .getResourceBundleName(r); - vrb = new VirtualResourceBundle( - resourcebundleName, - resourcebundleId, - ResourceBundleManager.getManager(r.getProject())); - vcManager.addVResourceBundle(vRBId, vrb); - - } else { - vrb = vcManager.getVResourceBundles(vRBId); - } - - children.put(resourcebundleId, vrb); - } - } - if (r instanceof IContainer) { - if (!r.isDerived()) { // Don't show the 'bin' folder - VirtualContainer vContainer = vcManager - .getContainer((IContainer) r); - - if (vContainer == null) { - int count = RBFileUtils - .countRecursiveResourceBundle((IContainer) r); - vContainer = new VirtualContainer(container, count); - vcManager.addVContainer((IContainer) r, vContainer); - } - - if (vContainer.getRbCount() != 0) { - // without resourcebundles - children.put("" + children.size(), r); - } - } - } + return children != null ? children : new Object[0]; + } + + /* + * Returns all ResourceBundles and sub-containers (with ResourceBundles in + * their subtree) of a Container + */ + private Object[] addChildren(IContainer container) throws CoreException { + Map<String, Object> children = new HashMap<String, Object>(); + + VirtualProject p = (VirtualProject) vcManager.getContainer(container + .getProject()); + List<IResource> members = new ArrayList<IResource>( + Arrays.asList(container.members())); + + // finds files in the corresponding fragment-projects folder + if (p.hasFragments()) { + List<IContainer> folders = ResourceUtils.getCorrespondingFolders( + container, p.getFragmets()); + for (IContainer f : folders) { + for (IResource r : f.members()) { + if (r instanceof IFile) { + members.add(r); + } } - return children.values().toArray(); + } } - @Override - public Object getParent(Object element) { - if (element instanceof IContainer) { - return ((IContainer) element).getParent(); + for (IResource r : members) { + + if (r instanceof IFile) { + String resourcebundleId = RBFileUtils + .getCorrespondingResourceBundleId((IFile) r); + if (resourcebundleId != null + && (!children.containsKey(resourcebundleId))) { + VirtualResourceBundle vrb; + + String vRBId; + + if (!p.isFragment()) { + vRBId = r.getProject() + "." + resourcebundleId; + } else { + vRBId = p.getHostProject() + "." + resourcebundleId; + } + + VirtualResourceBundle vResourceBundle = vcManager + .getVResourceBundles(vRBId); + if (vResourceBundle == null) { + String resourcebundleName = ResourceBundleManager + .getResourceBundleName(r); + vrb = new VirtualResourceBundle( + resourcebundleName, + resourcebundleId, + ResourceBundleManager.getManager(r.getProject())); + vcManager.addVResourceBundle(vRBId, vrb); + + } else { + vrb = vcManager.getVResourceBundles(vRBId); + } + + children.put(resourcebundleId, vrb); } - if (element instanceof IFile) { - String rbId = RBFileUtils - .getCorrespondingResourceBundleId((IFile) element); - return vcManager.getVResourceBundles(rbId); + } + if (r instanceof IContainer) { + if (!r.isDerived()) { // Don't show the 'bin' folder + VirtualContainer vContainer = vcManager + .getContainer((IContainer) r); + + if (vContainer == null) { + int count = RBFileUtils + .countRecursiveResourceBundle((IContainer) r); + vContainer = new VirtualContainer(container, count); + vcManager.addVContainer((IContainer) r, vContainer); + } + + if (vContainer.getRbCount() != 0) { + // without resourcebundles + children.put("" + children.size(), r); + } } - if (element instanceof VirtualResourceBundle) { - Iterator<IResource> i = new HashSet<IResource>( - ((VirtualResourceBundle) element).getFiles()).iterator(); - if (i.hasNext()) { - return i.next().getParent(); - } - } - return null; + } } + return children.values().toArray(); + } - @Override - public boolean hasChildren(Object element) { - if (element instanceof IWorkspaceRoot) { - try { - if (((IWorkspaceRoot) element).members().length > 0) { - return true; - } - } catch (CoreException e) { - } - } - if (element instanceof IProject) { - VirtualProject vProject = (VirtualProject) vcManager - .getContainer((IProject) element); - if (vProject != null && vProject.isFragment()) { - return false; - } - } - if (element instanceof IContainer) { - try { - VirtualContainer vContainer = vcManager - .getContainer((IContainer) element); - if (vContainer != null) { - return vContainer.getRbCount() > 0 ? true : false; - } else if (((IContainer) element).members().length > 0) { - return true; - } - } catch (CoreException e) { - } - } - if (element instanceof VirtualResourceBundle) { - return true; + @Override + public Object getParent(Object element) { + if (element instanceof IContainer) { + return ((IContainer) element).getParent(); + } + if (element instanceof IFile) { + String rbId = RBFileUtils + .getCorrespondingResourceBundleId((IFile) element); + return vcManager.getVResourceBundles(rbId); + } + if (element instanceof VirtualResourceBundle) { + Iterator<IResource> i = new HashSet<IResource>( + ((VirtualResourceBundle) element).getFiles()).iterator(); + if (i.hasNext()) { + return i.next().getParent(); + } + } + return null; + } + + @Override + public boolean hasChildren(Object element) { + if (element instanceof IWorkspaceRoot) { + try { + if (((IWorkspaceRoot) element).members().length > 0) { + return true; } + } catch (CoreException e) { + } + } + if (element instanceof IProject) { + VirtualProject vProject = (VirtualProject) vcManager + .getContainer((IProject) element); + if (vProject != null && vProject.isFragment()) { return false; + } } - - @Override - public void dispose() { - ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); - TapiJIPreferences.removePropertyChangeListener(this); - vcManager.reset(); - unregisterAllResourceBundleListner(); + if (element instanceof IContainer) { + try { + VirtualContainer vContainer = vcManager + .getContainer((IContainer) element); + if (vContainer != null) { + return vContainer.getRbCount() > 0 ? true : false; + } else if (((IContainer) element).members().length > 0) { + return true; + } + } catch (CoreException e) { + } } - - @Override - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - this.viewer = (StructuredViewer) viewer; + if (element instanceof VirtualResourceBundle) { + return true; } + return false; + } + + @Override + public void dispose() { + ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); + TapiJIPreferences.removePropertyChangeListener(this); + vcManager.reset(); + unregisterAllResourceBundleListner(); + } + + @Override + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + this.viewer = (StructuredViewer) viewer; + } + + @Override + // TODO remove ResourceChangelistner and add ResourceBundleChangelistner + public void resourceChanged(final IResourceChangeEvent event) { + + final IResourceDeltaVisitor visitor = new IResourceDeltaVisitor() { + @Override + public boolean visit(IResourceDelta delta) throws CoreException { + final IResource res = delta.getResource(); + + if (!RBFileUtils.isResourceBundleFile(res)) { + return true; + } - @Override - // TODO remove ResourceChangelistner and add ResourceBundleChangelistner - public void resourceChanged(final IResourceChangeEvent event) { + switch (delta.getKind()) { + case IResourceDelta.REMOVED: + recountParenthierarchy(res.getParent()); + break; + // TODO remove unused VirtualResourceBundles and + // VirtualContainer from vcManager + case IResourceDelta.ADDED: + checkListner(res); + break; + case IResourceDelta.CHANGED: + if (delta.getFlags() != IResourceDelta.MARKERS) { + return true; + } + break; + } - final IResourceDeltaVisitor visitor = new IResourceDeltaVisitor() { - @Override - public boolean visit(IResourceDelta delta) throws CoreException { - final IResource res = delta.getResource(); + refresh(res); - if (!RBFileUtils.isResourceBundleFile(res)) { - return true; - } + return true; + } + }; - switch (delta.getKind()) { - case IResourceDelta.REMOVED: - recountParenthierarchy(res.getParent()); - break; - // TODO remove unused VirtualResourceBundles and - // VirtualContainer from vcManager - case IResourceDelta.ADDED: - checkListner(res); - break; - case IResourceDelta.CHANGED: - if (delta.getFlags() != IResourceDelta.MARKERS) { - return true; - } - break; - } + try { + event.getDelta().accept(visitor); + } catch (Exception e) { + e.printStackTrace(); + } + } - refresh(res); + @Override + public void resourceBundleChanged(ResourceBundleChangedEvent event) { + ResourceBundleManager rbmanager = ResourceBundleManager + .getManager(event.getProject()); - return true; - } - }; + switch (event.getType()) { + case ResourceBundleChangedEvent.ADDED: + case ResourceBundleChangedEvent.DELETED: + IResource res = rbmanager.getRandomFile(event.getBundle()); + IContainer hostContainer; + if (res == null) { try { - event.getDelta().accept(visitor); + hostContainer = event.getProject() + .getFile(event.getBundle()).getParent(); } catch (Exception e) { - e.printStackTrace(); + refresh(null); + return; } - } - - @Override - public void resourceBundleChanged(ResourceBundleChangedEvent event) { - ResourceBundleManager rbmanager = ResourceBundleManager - .getManager(event.getProject()); - - switch (event.getType()) { - case ResourceBundleChangedEvent.ADDED: - case ResourceBundleChangedEvent.DELETED: - IResource res = rbmanager.getRandomFile(event.getBundle()); - IContainer hostContainer; - - if (res == null) { - try { - hostContainer = event.getProject() - .getFile(event.getBundle()).getParent(); - } catch (Exception e) { - refresh(null); - return; - } - } else { - VirtualProject vProject = (VirtualProject) vcManager - .getContainer(res.getProject()); - if (vProject != null && vProject.isFragment()) { - IProject hostProject = vProject.getHostProject(); - hostContainer = ResourceUtils.getCorrespondingFolders( - res.getParent(), hostProject); - } else { - hostContainer = res.getParent(); - } - } - - recountParenthierarchy(hostContainer); - refresh(null); - break; + } else { + VirtualProject vProject = (VirtualProject) vcManager + .getContainer(res.getProject()); + if (vProject != null && vProject.isFragment()) { + IProject hostProject = vProject.getHostProject(); + hostContainer = ResourceUtils.getCorrespondingFolders( + res.getParent(), hostProject); + } else { + hostContainer = res.getParent(); } + } + recountParenthierarchy(hostContainer); + refresh(null); + break; } - @Override - public void propertyChange(PropertyChangeEvent event) { - if (event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN)) { - vcManager.reset(); + } - refresh(root); - } - } - - // TODO problems with remove a hole ResourceBundle - private void recountParenthierarchy(IContainer parent) { - if (parent.isDerived()) { - return; // Don't recount the 'bin' folder - } + @Override + public void propertyChange(PropertyChangeEvent event) { + if (event.getProperty().equals(TapiJIPreferences.NON_RB_PATTERN)) { + vcManager.reset(); - VirtualContainer vContainer = vcManager.getContainer(parent); - if (vContainer != null) { - vContainer.recount(); - } - - if ((parent instanceof IFolder)) { - recountParenthierarchy(parent.getParent()); - } + refresh(root); } + } - private void refresh(final IResource res) { - if (refresh == null || refresh.getResult() != null) { - refresh = new UIJob("refresh viewer") { - @Override - public IStatus runInUIThread(IProgressMonitor monitor) { - if (viewer != null && !viewer.getControl().isDisposed()) { - if (res != null) { - viewer.refresh(res.getProject(), true); // refresh(res); - } else { - viewer.refresh(); - } - } - return Status.OK_STATUS; - } - }; - } - refresh.schedule(); + // TODO problems with remove a hole ResourceBundle + private void recountParenthierarchy(IContainer parent) { + if (parent.isDerived()) { + return; // Don't recount the 'bin' folder } - private void registerResourceBundleListner(IProject p) { - listenedProjects.add(p); - - ResourceBundleManager rbmanager = ResourceBundleManager.getManager(p); - for (String rbId : rbmanager.getResourceBundleIdentifiers()) { - rbmanager.registerResourceBundleChangeListener(rbId, this); - } + VirtualContainer vContainer = vcManager.getContainer(parent); + if (vContainer != null) { + vContainer.recount(); } - private void unregisterAllResourceBundleListner() { - for (IProject p : listenedProjects) { - ResourceBundleManager rbmanager = ResourceBundleManager - .getManager(p); - for (String rbId : rbmanager.getResourceBundleIdentifiers()) { - rbmanager.unregisterResourceBundleChangeListener(rbId, this); + if ((parent instanceof IFolder)) { + recountParenthierarchy(parent.getParent()); + } + } + + private void refresh(final IResource res) { + if (refresh == null || refresh.getResult() != null) { + refresh = new UIJob("refresh viewer") { + @Override + public IStatus runInUIThread(IProgressMonitor monitor) { + if (viewer != null && !viewer.getControl().isDisposed()) { + if (res != null) { + viewer.refresh(res.getProject(), true); // refresh(res); + } else { + viewer.refresh(); } + } + return Status.OK_STATUS; } + }; } + refresh.schedule(); + } - private void checkListner(IResource res) { - ResourceBundleManager rbmanager = ResourceBundleManager.getManager(res - .getProject()); - String rbId = ResourceBundleManager.getResourceBundleId(res); - rbmanager.registerResourceBundleChangeListener(rbId, this); + private void registerResourceBundleListner(IProject p) { + listenedProjects.add(p); + + ResourceBundleManager rbmanager = ResourceBundleManager.getManager(p); + for (String rbId : rbmanager.getResourceBundleIdentifiers()) { + rbmanager.registerResourceBundleChangeListener(rbId, this); + } + } + + private void unregisterAllResourceBundleListner() { + for (IProject p : listenedProjects) { + ResourceBundleManager rbmanager = ResourceBundleManager + .getManager(p); + for (String rbId : rbmanager.getResourceBundleIdentifiers()) { + rbmanager.unregisterResourceBundleChangeListener(rbId, this); + } } + } + + private void checkListner(IResource res) { + ResourceBundleManager rbmanager = ResourceBundleManager.getManager(res + .getProject()); + String rbId = ResourceBundleManager.getResourceBundleId(res); + rbmanager.registerResourceBundleChangeListener(rbId, this); + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java index 97fb1372..fc147942 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/ResourceBundleLabelProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -36,172 +36,172 @@ import org.eclipse.ui.navigator.IDescriptionProvider; public class ResourceBundleLabelProvider extends LabelProvider implements - ILabelProvider, IDescriptionProvider { - VirtualContentManager vcManager; - - public ResourceBundleLabelProvider() { - super(); - vcManager = VirtualContentManager.getVirtualContentManager(); + ILabelProvider, IDescriptionProvider { + VirtualContentManager vcManager; + + public ResourceBundleLabelProvider() { + super(); + vcManager = VirtualContentManager.getVirtualContentManager(); + } + + @Override + public Image getImage(Object element) { + Image returnImage = null; + if (element instanceof IProject) { + VirtualProject p = (VirtualProject) vcManager + .getContainer((IProject) element); + if (p != null && p.isFragment()) { + return returnImage = ImageUtils + .getBaseImage(ImageUtils.FRAGMENT_PROJECT_IMAGE); + } else { + returnImage = PlatformUI.getWorkbench().getSharedImages() + .getImage(ISharedImages.IMG_OBJ_PROJECT); + } } - - @Override - public Image getImage(Object element) { - Image returnImage = null; - if (element instanceof IProject) { - VirtualProject p = (VirtualProject) vcManager - .getContainer((IProject) element); - if (p != null && p.isFragment()) { - return returnImage = ImageUtils - .getBaseImage(ImageUtils.FRAGMENT_PROJECT_IMAGE); - } else { - returnImage = PlatformUI.getWorkbench().getSharedImages() - .getImage(ISharedImages.IMG_OBJ_PROJECT); - } - } - if ((element instanceof IContainer) && (returnImage == null)) { - returnImage = PlatformUI.getWorkbench().getSharedImages() - .getImage(ISharedImages.IMG_OBJ_FOLDER); - } - if (element instanceof VirtualResourceBundle) { - returnImage = ImageUtils - .getBaseImage(ImageUtils.RESOURCEBUNDLE_IMAGE); - } - if (element instanceof IFile) { - if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils - .isResourceBundleFile((IFile) element)) { - Locale l = org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils - .getLocale((IFile) element); - returnImage = ImageUtils.getLocalIcon(l); - - VirtualProject p = ((VirtualProject) vcManager - .getContainer(((IFile) element).getProject())); - if (p != null && p.isFragment()) { - returnImage = ImageUtils.getImageWithFragment(returnImage); - } - } + if ((element instanceof IContainer) && (returnImage == null)) { + returnImage = PlatformUI.getWorkbench().getSharedImages() + .getImage(ISharedImages.IMG_OBJ_FOLDER); + } + if (element instanceof VirtualResourceBundle) { + returnImage = ImageUtils + .getBaseImage(ImageUtils.RESOURCEBUNDLE_IMAGE); + } + if (element instanceof IFile) { + if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils + .isResourceBundleFile((IFile) element)) { + Locale l = org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils + .getLocale((IFile) element); + returnImage = ImageUtils.getLocalIcon(l); + + VirtualProject p = ((VirtualProject) vcManager + .getContainer(((IFile) element).getProject())); + if (p != null && p.isFragment()) { + returnImage = ImageUtils.getImageWithFragment(returnImage); } + } + } - if (returnImage != null) { - if (checkMarkers(element)) { - // Add a Warning Image - returnImage = ImageUtils.getImageWithWarning(returnImage); - } - } - return returnImage; + if (returnImage != null) { + if (checkMarkers(element)) { + // Add a Warning Image + returnImage = ImageUtils.getImageWithWarning(returnImage); + } } + return returnImage; + } - @Override - public String getText(Object element) { + @Override + public String getText(Object element) { - StringBuilder text = new StringBuilder(); - if (element instanceof IContainer) { - IContainer container = (IContainer) element; - text.append(container.getName()); - - if (element instanceof IProject) { - VirtualContainer vproject = vcManager - .getContainer((IProject) element); - // if (vproject != null && vproject instanceof VirtualFragment) - // text.append("�"); - } + StringBuilder text = new StringBuilder(); + if (element instanceof IContainer) { + IContainer container = (IContainer) element; + text.append(container.getName()); - VirtualContainer vContainer = vcManager.getContainer(container); - if (vContainer != null && vContainer.getRbCount() != 0) { - text.append(" [" + vContainer.getRbCount() + "]"); - } + if (element instanceof IProject) { + VirtualContainer vproject = vcManager + .getContainer((IProject) element); + // if (vproject != null && vproject instanceof VirtualFragment) + // text.append("�"); + } + VirtualContainer vContainer = vcManager.getContainer(container); + if (vContainer != null && vContainer.getRbCount() != 0) { + text.append(" [" + vContainer.getRbCount() + "]"); + } + + } + if (element instanceof VirtualResourceBundle) { + text.append(((VirtualResourceBundle) element).getName()); + } + if (element instanceof IFile) { + if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils + .isResourceBundleFile((IFile) element)) { + Locale locale = org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils + .getLocale((IFile) element); + text.append(" "); + if (locale != null) { + text.append(locale); + } else { + text.append("default"); } - if (element instanceof VirtualResourceBundle) { - text.append(((VirtualResourceBundle) element).getName()); - } - if (element instanceof IFile) { - if (org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils - .isResourceBundleFile((IFile) element)) { - Locale locale = org.eclipse.babel.tapiji.tools.core.ui.utils.RBFileUtils - .getLocale((IFile) element); - text.append(" "); - if (locale != null) { - text.append(locale); - } else { - text.append("default"); - } - - VirtualProject vproject = (VirtualProject) vcManager - .getContainer(((IFile) element).getProject()); - if (vproject != null && vproject.isFragment()) { - text.append("�"); - } - } - } - if (element instanceof String) { - text.append(element); + + VirtualProject vproject = (VirtualProject) vcManager + .getContainer(((IFile) element).getProject()); + if (vproject != null && vproject.isFragment()) { + text.append("�"); } - return text.toString(); + } } + if (element instanceof String) { + text.append(element); + } + return text.toString(); + } - @Override - public String getDescription(Object anElement) { - if (anElement instanceof IResource) { - return ((IResource) anElement).getName(); - } - if (anElement instanceof VirtualResourceBundle) { - return ((VirtualResourceBundle) anElement).getName(); - } - return null; + @Override + public String getDescription(Object anElement) { + if (anElement instanceof IResource) { + return ((IResource) anElement).getName(); + } + if (anElement instanceof VirtualResourceBundle) { + return ((VirtualResourceBundle) anElement).getName(); } + return null; + } + + private boolean checkMarkers(Object element) { + if (element instanceof IResource) { + IMarker[] ms = null; + try { + if ((ms = ((IResource) element).findMarkers( + EditorUtils.RB_MARKER_ID, true, + IResource.DEPTH_INFINITE)).length > 0) { + return true; + } - private boolean checkMarkers(Object element) { - if (element instanceof IResource) { - IMarker[] ms = null; + if (element instanceof IContainer) { + List<IContainer> fragmentContainer = ResourceUtils + .getCorrespondingFolders( + (IContainer) element, + FragmentProjectUtils + .getFragments(((IContainer) element) + .getProject())); + + IMarker[] fragment_ms; + for (IContainer c : fragmentContainer) { try { - if ((ms = ((IResource) element).findMarkers( - EditorUtils.RB_MARKER_ID, true, - IResource.DEPTH_INFINITE)).length > 0) { - return true; - } - - if (element instanceof IContainer) { - List<IContainer> fragmentContainer = ResourceUtils - .getCorrespondingFolders( - (IContainer) element, - FragmentProjectUtils - .getFragments(((IContainer) element) - .getProject())); - - IMarker[] fragment_ms; - for (IContainer c : fragmentContainer) { - try { - if (c.exists()) { - fragment_ms = c.findMarkers( - EditorUtils.RB_MARKER_ID, false, - IResource.DEPTH_INFINITE); - ms = org.eclipse.babel.tapiji.tools.core.util.EditorUtils - .concatMarkerArray(ms, fragment_ms); - } - } catch (CoreException e) { - e.printStackTrace(); - } - } - if (ms.length > 0) { - return true; - } - } + if (c.exists()) { + fragment_ms = c.findMarkers( + EditorUtils.RB_MARKER_ID, false, + IResource.DEPTH_INFINITE); + ms = org.eclipse.babel.tapiji.tools.core.util.EditorUtils + .concatMarkerArray(ms, fragment_ms); + } } catch (CoreException e) { + e.printStackTrace(); } + } + if (ms.length > 0) { + return true; + } } - if (element instanceof VirtualResourceBundle) { - ResourceBundleManager rbmanager = ((VirtualResourceBundle) element) - .getResourceBundleManager(); - String id = ((VirtualResourceBundle) element).getResourceBundleId(); - for (IResource r : rbmanager.getResourceBundles(id)) { - if (org.eclipse.babel.tapiji.tools.core.util.RBFileUtils - .hasResourceBundleMarker(r)) { - return true; - } - } + } catch (CoreException e) { + } + } + if (element instanceof VirtualResourceBundle) { + ResourceBundleManager rbmanager = ((VirtualResourceBundle) element) + .getResourceBundleManager(); + String id = ((VirtualResourceBundle) element).getResourceBundleId(); + for (IResource r : rbmanager.getResourceBundles(id)) { + if (org.eclipse.babel.tapiji.tools.core.util.RBFileUtils + .hasResourceBundleMarker(r)) { + return true; } - - return false; + } } + return false; + } + } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java index ca261701..b919658f 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/ExpandAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -21,34 +21,34 @@ import org.eclipse.ui.navigator.CommonViewer; public class ExpandAction extends Action implements IAction { - private CommonViewer viewer; + private CommonViewer viewer; - public ExpandAction(CommonViewer viewer) { - this.viewer = viewer; - setText("Expand Node"); - setToolTipText("expand node"); - setImageDescriptor(RBManagerActivator - .getImageDescriptor(ImageUtils.EXPAND)); - } - - @Override - public boolean isEnabled() { - IStructuredSelection sSelection = (IStructuredSelection) viewer - .getSelection(); - if (sSelection.size() >= 1) - return true; - else - return false; - } + public ExpandAction(CommonViewer viewer) { + this.viewer = viewer; + setText("Expand Node"); + setToolTipText("expand node"); + setImageDescriptor(RBManagerActivator + .getImageDescriptor(ImageUtils.EXPAND)); + } - @Override - public void run() { - IStructuredSelection sSelection = (IStructuredSelection) viewer - .getSelection(); - Iterator<?> it = sSelection.iterator(); - while (it.hasNext()) { - viewer.expandToLevel(it.next(), AbstractTreeViewer.ALL_LEVELS); - } + @Override + public boolean isEnabled() { + IStructuredSelection sSelection = (IStructuredSelection) viewer + .getSelection(); + if (sSelection.size() >= 1) + return true; + else + return false; + } + @Override + public void run() { + IStructuredSelection sSelection = (IStructuredSelection) viewer + .getSelection(); + Iterator<?> it = sSelection.iterator(); + while (it.hasNext()) { + viewer.expandToLevel(it.next(), AbstractTreeViewer.ALL_LEVELS); } + + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java index 32951bf8..4bb15f1e 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/GeneralActionProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -25,32 +25,32 @@ import org.eclipse.ui.navigator.ICommonActionExtensionSite; public class GeneralActionProvider extends CommonActionProvider { - private IAction expandAction; - - public GeneralActionProvider() { - // TODO Auto-generated constructor stub - } - - @Override - public void init(ICommonActionExtensionSite aSite) { - super.init(aSite); - // init Expand-Action - expandAction = new ExpandAction( - (CommonViewer) aSite.getStructuredViewer()); - - // activate View-Hover - List<HoverInformant> informants = new ArrayList<HoverInformant>(); - informants.add(new I18NProjectInformant()); - informants.add(new RBMarkerInformant()); - - Hover hover = new Hover(Display.getCurrent().getActiveShell(), - informants); - hover.activateHoverHelp(((CommonViewer) aSite.getStructuredViewer()) - .getTree()); - } - - @Override - public void fillContextMenu(IMenuManager menu) { - menu.appendToGroup("expand", expandAction); - } + private IAction expandAction; + + public GeneralActionProvider() { + // TODO Auto-generated constructor stub + } + + @Override + public void init(ICommonActionExtensionSite aSite) { + super.init(aSite); + // init Expand-Action + expandAction = new ExpandAction( + (CommonViewer) aSite.getStructuredViewer()); + + // activate View-Hover + List<HoverInformant> informants = new ArrayList<HoverInformant>(); + informants.add(new I18NProjectInformant()); + informants.add(new RBMarkerInformant()); + + Hover hover = new Hover(Display.getCurrent().getActiveShell(), + informants); + hover.activateHoverHelp(((CommonViewer) aSite.getStructuredViewer()) + .getTree()); + } + + @Override + public void fillContextMenu(IMenuManager menu) { + menu.appendToGroup("expand", expandAction); + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java index 59d24916..2b8b9587 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/OpenVRBAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -19,35 +19,35 @@ import org.eclipse.ui.IWorkbenchPage; public class OpenVRBAction extends Action { - private ISelectionProvider selectionProvider; + private ISelectionProvider selectionProvider; - public OpenVRBAction(ISelectionProvider selectionProvider) { - this.selectionProvider = selectionProvider; - } + public OpenVRBAction(ISelectionProvider selectionProvider) { + this.selectionProvider = selectionProvider; + } - @Override - public boolean isEnabled() { - IStructuredSelection sSelection = (IStructuredSelection) selectionProvider - .getSelection(); - if (sSelection.size() == 1) - return true; - else - return false; - } + @Override + public boolean isEnabled() { + IStructuredSelection sSelection = (IStructuredSelection) selectionProvider + .getSelection(); + if (sSelection.size() == 1) + return true; + else + return false; + } - @Override - public void run() { - IStructuredSelection sSelection = (IStructuredSelection) selectionProvider - .getSelection(); - if (sSelection.size() == 1 - && sSelection.getFirstElement() instanceof VirtualResourceBundle) { - VirtualResourceBundle vRB = (VirtualResourceBundle) sSelection - .getFirstElement(); - IWorkbenchPage wp = RBManagerActivator.getDefault().getWorkbench() - .getActiveWorkbenchWindow().getActivePage(); + @Override + public void run() { + IStructuredSelection sSelection = (IStructuredSelection) selectionProvider + .getSelection(); + if (sSelection.size() == 1 + && sSelection.getFirstElement() instanceof VirtualResourceBundle) { + VirtualResourceBundle vRB = (VirtualResourceBundle) sSelection + .getFirstElement(); + IWorkbenchPage wp = RBManagerActivator.getDefault().getWorkbench() + .getActiveWorkbenchWindow().getActivePage(); - EditorUtils.openEditor(wp, vRB.getRandomFile(), - EditorUtils.RESOURCE_BUNDLE_EDITOR); - } + EditorUtils.openEditor(wp, vRB.getRandomFile(), + EditorUtils.RESOURCE_BUNDLE_EDITOR); } + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java index 94286918..f1972fc0 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/VirtualRBActionProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -20,22 +20,22 @@ * Will be only active for VirtualResourceBundeles */ public class VirtualRBActionProvider extends CommonActionProvider { - private IAction openAction; + private IAction openAction; - public VirtualRBActionProvider() { - // TODO Auto-generated constructor stub - } + public VirtualRBActionProvider() { + // TODO Auto-generated constructor stub + } - @Override - public void init(ICommonActionExtensionSite aSite) { - super.init(aSite); - openAction = new OpenVRBAction(aSite.getViewSite() - .getSelectionProvider()); - } + @Override + public void init(ICommonActionExtensionSite aSite) { + super.init(aSite); + openAction = new OpenVRBAction(aSite.getViewSite() + .getSelectionProvider()); + } - @Override - public void fillActionBars(IActionBars actionBars) { - actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN, - openAction); - } + @Override + public void fillActionBars(IActionBars actionBars) { + actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN, + openAction); + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java index daba43ec..ae330da6 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/I18NProjectInformant.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -28,205 +28,205 @@ import org.eclipse.swt.widgets.Label; public class I18NProjectInformant implements HoverInformant { - private String locales; - private String fragments; - private boolean show = false; - - private Composite infoComposite; - private Label localeLabel; - private Composite localeGroup; - private Label fragmentsLabel; - private Composite fragmentsGroup; - - private GridData infoData; - private GridData showLocalesData; - private GridData showFragmentsData; - - @Override - public Composite getInfoComposite(Object data, Composite parent) { - show = false; - - if (infoComposite == null) { - infoComposite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(1, false); - layout.verticalSpacing = 1; - layout.horizontalSpacing = 0; - infoComposite.setLayout(layout); - - infoData = new GridData(SWT.LEFT, SWT.TOP, true, true); - infoComposite.setLayoutData(infoData); - } - - if (data instanceof IProject) { - addLocale(infoComposite, data); - addFragments(infoComposite, data); - } - - if (show) { - infoData.heightHint = -1; - infoData.widthHint = -1; - } else { - infoData.heightHint = 0; - infoData.widthHint = 0; - } - - infoComposite.layout(); - infoComposite.pack(); - sinkColor(infoComposite); + private String locales; + private String fragments; + private boolean show = false; + + private Composite infoComposite; + private Label localeLabel; + private Composite localeGroup; + private Label fragmentsLabel; + private Composite fragmentsGroup; + + private GridData infoData; + private GridData showLocalesData; + private GridData showFragmentsData; + + @Override + public Composite getInfoComposite(Object data, Composite parent) { + show = false; + + if (infoComposite == null) { + infoComposite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(1, false); + layout.verticalSpacing = 1; + layout.horizontalSpacing = 0; + infoComposite.setLayout(layout); + + infoData = new GridData(SWT.LEFT, SWT.TOP, true, true); + infoComposite.setLayoutData(infoData); + } - return infoComposite; + if (data instanceof IProject) { + addLocale(infoComposite, data); + addFragments(infoComposite, data); } - @Override - public boolean show() { - return show; + if (show) { + infoData.heightHint = -1; + infoData.widthHint = -1; + } else { + infoData.heightHint = 0; + infoData.widthHint = 0; } - private void setColor(Control control) { - Display display = control.getParent().getDisplay(); + infoComposite.layout(); + infoComposite.pack(); + sinkColor(infoComposite); - control.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); - control.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); - } + return infoComposite; + } - private void sinkColor(Composite composite) { - setColor(composite); + @Override + public boolean show() { + return show; + } - for (Control c : composite.getChildren()) { - setColor(c); - if (c instanceof Composite) { - sinkColor((Composite) c); - } - } - } + private void setColor(Control control) { + Display display = control.getParent().getDisplay(); - private void addLocale(Composite parent, Object data) { - if (localeGroup == null) { - localeGroup = new Composite(parent, SWT.NONE); - localeLabel = new Label(localeGroup, SWT.SINGLE); + control.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); + control.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); + } - showLocalesData = new GridData(SWT.LEFT, SWT.TOP, true, true); - localeGroup.setLayoutData(showLocalesData); - } + private void sinkColor(Composite composite) { + setColor(composite); - locales = getProvidedLocales(data); - - if (locales.length() != 0) { - localeLabel.setText(locales); - localeLabel.pack(); - show = true; - // showLocalesData.heightHint = -1; - // showLocalesData.widthHint=-1; - } else { - localeLabel.setText("No Language Provided"); - localeLabel.pack(); - show = true; - // showLocalesData.heightHint = 0; - // showLocalesData.widthHint = 0; - } + for (Control c : composite.getChildren()) { + setColor(c); + if (c instanceof Composite) { + sinkColor((Composite) c); + } + } + } - // localeGroup.layout(); - localeGroup.pack(); + private void addLocale(Composite parent, Object data) { + if (localeGroup == null) { + localeGroup = new Composite(parent, SWT.NONE); + localeLabel = new Label(localeGroup, SWT.SINGLE); + + showLocalesData = new GridData(SWT.LEFT, SWT.TOP, true, true); + localeGroup.setLayoutData(showLocalesData); } - private void addFragments(Composite parent, Object data) { - if (fragmentsGroup == null) { - fragmentsGroup = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(1, false); - layout.verticalSpacing = 0; - layout.horizontalSpacing = 0; - fragmentsGroup.setLayout(layout); - - showFragmentsData = new GridData(SWT.LEFT, SWT.TOP, true, true); - fragmentsGroup.setLayoutData(showFragmentsData); - - Composite fragmentTitleGroup = new Composite(fragmentsGroup, - SWT.NONE); - layout = new GridLayout(2, false); - layout.verticalSpacing = 0; - layout.horizontalSpacing = 5; - fragmentTitleGroup.setLayout(layout); - - Label fragmentImageLabel = new Label(fragmentTitleGroup, SWT.NONE); - fragmentImageLabel.setImage(ImageUtils - .getBaseImage(ImageUtils.FRAGMENT_PROJECT_IMAGE)); - fragmentImageLabel.pack(); - - Label fragementTitleLabel = new Label(fragmentTitleGroup, SWT.NONE); - fragementTitleLabel.setText("Project Fragments:"); - fragementTitleLabel.pack(); - fragmentsLabel = new Label(fragmentsGroup, SWT.SINGLE); - } + locales = getProvidedLocales(data); + + if (locales.length() != 0) { + localeLabel.setText(locales); + localeLabel.pack(); + show = true; + // showLocalesData.heightHint = -1; + // showLocalesData.widthHint=-1; + } else { + localeLabel.setText("No Language Provided"); + localeLabel.pack(); + show = true; + // showLocalesData.heightHint = 0; + // showLocalesData.widthHint = 0; + } - fragments = getFragmentProjects(data); - - if (fragments.length() != 0) { - fragmentsLabel.setText(fragments); - show = true; - showFragmentsData.heightHint = -1; - showFragmentsData.widthHint = -1; - fragmentsLabel.pack(); - } else { - showFragmentsData.heightHint = 0; - showFragmentsData.widthHint = 0; - } + // localeGroup.layout(); + localeGroup.pack(); + } + + private void addFragments(Composite parent, Object data) { + if (fragmentsGroup == null) { + fragmentsGroup = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(1, false); + layout.verticalSpacing = 0; + layout.horizontalSpacing = 0; + fragmentsGroup.setLayout(layout); + + showFragmentsData = new GridData(SWT.LEFT, SWT.TOP, true, true); + fragmentsGroup.setLayoutData(showFragmentsData); + + Composite fragmentTitleGroup = new Composite(fragmentsGroup, + SWT.NONE); + layout = new GridLayout(2, false); + layout.verticalSpacing = 0; + layout.horizontalSpacing = 5; + fragmentTitleGroup.setLayout(layout); + + Label fragmentImageLabel = new Label(fragmentTitleGroup, SWT.NONE); + fragmentImageLabel.setImage(ImageUtils + .getBaseImage(ImageUtils.FRAGMENT_PROJECT_IMAGE)); + fragmentImageLabel.pack(); + + Label fragementTitleLabel = new Label(fragmentTitleGroup, SWT.NONE); + fragementTitleLabel.setText("Project Fragments:"); + fragementTitleLabel.pack(); + fragmentsLabel = new Label(fragmentsGroup, SWT.SINGLE); + } - fragmentsGroup.layout(); - fragmentsGroup.pack(); + fragments = getFragmentProjects(data); + + if (fragments.length() != 0) { + fragmentsLabel.setText(fragments); + show = true; + showFragmentsData.heightHint = -1; + showFragmentsData.widthHint = -1; + fragmentsLabel.pack(); + } else { + showFragmentsData.heightHint = 0; + showFragmentsData.widthHint = 0; } - private String getProvidedLocales(Object data) { - if (data instanceof IProject) { - ResourceBundleManager rbmanger = ResourceBundleManager - .getManager((IProject) data); - Set<Locale> ls = rbmanger.getProjectProvidedLocales(); - - if (ls.size() > 0) { - StringBuilder sb = new StringBuilder(); - sb.append("Provided Languages:\n"); - - int i = 0; - for (Locale l : ls) { - if (l != null && !l.toString().equals("")) { - sb.append(l.getDisplayName()); - } else { - sb.append("[Default]"); - } - - if (++i != ls.size()) { - sb.append(","); - if (i % 5 == 0) { - sb.append("\n"); - } else { - sb.append(" "); - } - } - - } - return sb.toString(); + fragmentsGroup.layout(); + fragmentsGroup.pack(); + } + + private String getProvidedLocales(Object data) { + if (data instanceof IProject) { + ResourceBundleManager rbmanger = ResourceBundleManager + .getManager((IProject) data); + Set<Locale> ls = rbmanger.getProjectProvidedLocales(); + + if (ls.size() > 0) { + StringBuilder sb = new StringBuilder(); + sb.append("Provided Languages:\n"); + + int i = 0; + for (Locale l : ls) { + if (l != null && !l.toString().equals("")) { + sb.append(l.getDisplayName()); + } else { + sb.append("[Default]"); + } + + if (++i != ls.size()) { + sb.append(","); + if (i % 5 == 0) { + sb.append("\n"); + } else { + sb.append(" "); } - } + } - return ""; + } + return sb.toString(); + } } - private String getFragmentProjects(Object data) { - if (data instanceof IProject) { - List<IProject> fragments = FragmentProjectUtils - .getFragments((IProject) data); - if (fragments.size() > 0) { - StringBuilder sb = new StringBuilder(); - - int i = 0; - for (IProject f : fragments) { - sb.append(f.getName()); - if (++i != fragments.size()) { - sb.append("\n"); - } - } - return sb.toString(); - } + return ""; + } + + private String getFragmentProjects(Object data) { + if (data instanceof IProject) { + List<IProject> fragments = FragmentProjectUtils + .getFragments((IProject) data); + if (fragments.size() > 0) { + StringBuilder sb = new StringBuilder(); + + int i = 0; + for (IProject f : fragments) { + sb.append(f.getName()); + if (++i != fragments.size()) { + sb.append("\n"); + } } - return ""; + return sb.toString(); + } } + return ""; + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java index 8e2284e9..32169845 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/actions/hoverinformants/RBMarkerInformant.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -34,248 +34,248 @@ import org.eclipse.swt.widgets.Label; public class RBMarkerInformant implements HoverInformant { - private int MAX_PROBLEMS = 20; - private boolean show = false; - - private String title; - private String problems; - - private Composite infoComposite; - private Composite titleGroup; - private Label titleLabel; - private Composite problemGroup; - private Label problemLabel; - - private GridData infoData; - private GridData showTitleData; - private GridData showProblemsData; - - @Override - public Composite getInfoComposite(Object data, Composite parent) { - show = false; - - if (infoComposite == null) { - infoComposite = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(1, false); - layout.verticalSpacing = 0; - layout.horizontalSpacing = 0; - infoComposite.setLayout(layout); - - infoData = new GridData(SWT.LEFT, SWT.TOP, true, true); - infoComposite.setLayoutData(infoData); - } - - if (data instanceof VirtualResourceBundle || data instanceof IResource) { - addTitle(infoComposite, data); - addProblems(infoComposite, data); - } - - if (show) { - infoData.heightHint = -1; - infoData.widthHint = -1; - } else { - infoData.heightHint = 0; - infoData.widthHint = 0; - } - - infoComposite.layout(); - sinkColor(infoComposite); - infoComposite.pack(); + private int MAX_PROBLEMS = 20; + private boolean show = false; + + private String title; + private String problems; + + private Composite infoComposite; + private Composite titleGroup; + private Label titleLabel; + private Composite problemGroup; + private Label problemLabel; + + private GridData infoData; + private GridData showTitleData; + private GridData showProblemsData; + + @Override + public Composite getInfoComposite(Object data, Composite parent) { + show = false; + + if (infoComposite == null) { + infoComposite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(1, false); + layout.verticalSpacing = 0; + layout.horizontalSpacing = 0; + infoComposite.setLayout(layout); + + infoData = new GridData(SWT.LEFT, SWT.TOP, true, true); + infoComposite.setLayoutData(infoData); + } - return infoComposite; + if (data instanceof VirtualResourceBundle || data instanceof IResource) { + addTitle(infoComposite, data); + addProblems(infoComposite, data); } - @Override - public boolean show() { - return show; + if (show) { + infoData.heightHint = -1; + infoData.widthHint = -1; + } else { + infoData.heightHint = 0; + infoData.widthHint = 0; } - private void setColor(Control control) { - Display display = control.getParent().getDisplay(); + infoComposite.layout(); + sinkColor(infoComposite); + infoComposite.pack(); - control.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); - control.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); - } + return infoComposite; + } - private void sinkColor(Composite composite) { - setColor(composite); + @Override + public boolean show() { + return show; + } - for (Control c : composite.getChildren()) { - setColor(c); - if (c instanceof Composite) { - sinkColor((Composite) c); - } - } - } + private void setColor(Control control) { + Display display = control.getParent().getDisplay(); - private void addTitle(Composite parent, Object data) { - if (titleGroup == null) { - titleGroup = new Composite(parent, SWT.NONE); - titleLabel = new Label(titleGroup, SWT.SINGLE); + control.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); + control.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); + } - showTitleData = new GridData(SWT.LEFT, SWT.TOP, true, true); - titleGroup.setLayoutData(showTitleData); - } - title = getTitel(data); - - if (title.length() != 0) { - titleLabel.setText(title); - show = true; - showTitleData.heightHint = -1; - showTitleData.widthHint = -1; - titleLabel.pack(); - } else { - showTitleData.heightHint = 0; - showTitleData.widthHint = 0; - } + private void sinkColor(Composite composite) { + setColor(composite); - titleGroup.layout(); - titleGroup.pack(); + for (Control c : composite.getChildren()) { + setColor(c); + if (c instanceof Composite) { + sinkColor((Composite) c); + } } + } - private void addProblems(Composite parent, Object data) { - if (problemGroup == null) { - problemGroup = new Composite(parent, SWT.NONE); - GridLayout layout = new GridLayout(1, false); - layout.verticalSpacing = 0; - layout.horizontalSpacing = 0; - problemGroup.setLayout(layout); - - showProblemsData = new GridData(SWT.LEFT, SWT.TOP, true, true); - problemGroup.setLayoutData(showProblemsData); - - Composite problemTitleGroup = new Composite(problemGroup, SWT.NONE); - layout = new GridLayout(2, false); - layout.verticalSpacing = 0; - layout.horizontalSpacing = 5; - problemTitleGroup.setLayout(layout); - - Label warningImageLabel = new Label(problemTitleGroup, SWT.NONE); - warningImageLabel.setImage(ImageUtils - .getBaseImage(ImageUtils.WARNING_IMAGE)); - warningImageLabel.pack(); - - Label waringTitleLabel = new Label(problemTitleGroup, SWT.NONE); - waringTitleLabel.setText("ResourceBundle-Problems:"); - waringTitleLabel.pack(); - - problemLabel = new Label(problemGroup, SWT.SINGLE); - } + private void addTitle(Composite parent, Object data) { + if (titleGroup == null) { + titleGroup = new Composite(parent, SWT.NONE); + titleLabel = new Label(titleGroup, SWT.SINGLE); - problems = getProblems(data); + showTitleData = new GridData(SWT.LEFT, SWT.TOP, true, true); + titleGroup.setLayoutData(showTitleData); + } + title = getTitel(data); + + if (title.length() != 0) { + titleLabel.setText(title); + show = true; + showTitleData.heightHint = -1; + showTitleData.widthHint = -1; + titleLabel.pack(); + } else { + showTitleData.heightHint = 0; + showTitleData.widthHint = 0; + } - if (problems.length() != 0) { - problemLabel.setText(problems); - show = true; - showProblemsData.heightHint = -1; - showProblemsData.widthHint = -1; - problemLabel.pack(); - } else { - showProblemsData.heightHint = 0; - showProblemsData.widthHint = 0; - } + titleGroup.layout(); + titleGroup.pack(); + } + + private void addProblems(Composite parent, Object data) { + if (problemGroup == null) { + problemGroup = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(1, false); + layout.verticalSpacing = 0; + layout.horizontalSpacing = 0; + problemGroup.setLayout(layout); + + showProblemsData = new GridData(SWT.LEFT, SWT.TOP, true, true); + problemGroup.setLayoutData(showProblemsData); + + Composite problemTitleGroup = new Composite(problemGroup, SWT.NONE); + layout = new GridLayout(2, false); + layout.verticalSpacing = 0; + layout.horizontalSpacing = 5; + problemTitleGroup.setLayout(layout); + + Label warningImageLabel = new Label(problemTitleGroup, SWT.NONE); + warningImageLabel.setImage(ImageUtils + .getBaseImage(ImageUtils.WARNING_IMAGE)); + warningImageLabel.pack(); + + Label waringTitleLabel = new Label(problemTitleGroup, SWT.NONE); + waringTitleLabel.setText("ResourceBundle-Problems:"); + waringTitleLabel.pack(); + + problemLabel = new Label(problemGroup, SWT.SINGLE); + } - problemGroup.layout(); - problemGroup.pack(); + problems = getProblems(data); + + if (problems.length() != 0) { + problemLabel.setText(problems); + show = true; + showProblemsData.heightHint = -1; + showProblemsData.widthHint = -1; + problemLabel.pack(); + } else { + showProblemsData.heightHint = 0; + showProblemsData.widthHint = 0; } - private String getTitel(Object data) { - if (data instanceof IFile) { - return ((IResource) data).getFullPath().toString(); - } - if (data instanceof VirtualResourceBundle) { - return ((VirtualResourceBundle) data).getResourceBundleId(); - } + problemGroup.layout(); + problemGroup.pack(); + } - return ""; + private String getTitel(Object data) { + if (data instanceof IFile) { + return ((IResource) data).getFullPath().toString(); + } + if (data instanceof VirtualResourceBundle) { + return ((VirtualResourceBundle) data).getResourceBundleId(); } - private String getProblems(Object data) { - IMarker[] ms = null; - - if (data instanceof IResource) { - IResource res = (IResource) data; - try { - if (res.exists()) { - ms = res.findMarkers(EditorUtils.RB_MARKER_ID, false, - IResource.DEPTH_INFINITE); - } else { - ms = new IMarker[0]; - } - } catch (CoreException e) { - e.printStackTrace(); - } - if (data instanceof IContainer) { - // add problem of same folder in the fragment-project - List<IContainer> fragmentContainer = ResourceUtils - .getCorrespondingFolders((IContainer) res, - FragmentProjectUtils.getFragments(res - .getProject())); - - IMarker[] fragment_ms; - for (IContainer c : fragmentContainer) { - try { - if (c.exists()) { - fragment_ms = c.findMarkers( - EditorUtils.RB_MARKER_ID, false, - IResource.DEPTH_INFINITE); - - ms = org.eclipse.babel.tapiji.tools.core.util.EditorUtils - .concatMarkerArray(ms, fragment_ms); - } - } catch (CoreException e) { - } - } - } - } + return ""; + } + + private String getProblems(Object data) { + IMarker[] ms = null; - if (data instanceof VirtualResourceBundle) { - VirtualResourceBundle vRB = (VirtualResourceBundle) data; - - ResourceBundleManager rbmanager = vRB.getResourceBundleManager(); - IMarker[] file_ms; - - Collection<IResource> rBundles = rbmanager.getResourceBundles(vRB - .getResourceBundleId()); - if (!rBundles.isEmpty()) { - for (IResource r : rBundles) { - try { - file_ms = r.findMarkers(EditorUtils.RB_MARKER_ID, - false, IResource.DEPTH_INFINITE); - if (ms != null) { - ms = org.eclipse.babel.tapiji.tools.core.util.EditorUtils - .concatMarkerArray(ms, file_ms); - } else { - ms = file_ms; - } - } catch (Exception e) { - } - } + if (data instanceof IResource) { + IResource res = (IResource) data; + try { + if (res.exists()) { + ms = res.findMarkers(EditorUtils.RB_MARKER_ID, false, + IResource.DEPTH_INFINITE); + } else { + ms = new IMarker[0]; + } + } catch (CoreException e) { + e.printStackTrace(); + } + if (data instanceof IContainer) { + // add problem of same folder in the fragment-project + List<IContainer> fragmentContainer = ResourceUtils + .getCorrespondingFolders((IContainer) res, + FragmentProjectUtils.getFragments(res + .getProject())); + + IMarker[] fragment_ms; + for (IContainer c : fragmentContainer) { + try { + if (c.exists()) { + fragment_ms = c.findMarkers( + EditorUtils.RB_MARKER_ID, false, + IResource.DEPTH_INFINITE); + + ms = org.eclipse.babel.tapiji.tools.core.util.EditorUtils + .concatMarkerArray(ms, fragment_ms); } + } catch (CoreException e) { + } } + } + } - StringBuilder sb = new StringBuilder(); - int count = 0; - - if (ms != null && ms.length != 0) { - for (IMarker m : ms) { - try { - sb.append(m.getAttribute(IMarker.MESSAGE)); - sb.append("\n"); - count++; - if (count == MAX_PROBLEMS && ms.length - count != 0) { - sb.append(" ... and "); - sb.append(ms.length - count); - sb.append(" other problems"); - break; - } - } catch (CoreException e) { - } - ; + if (data instanceof VirtualResourceBundle) { + VirtualResourceBundle vRB = (VirtualResourceBundle) data; + + ResourceBundleManager rbmanager = vRB.getResourceBundleManager(); + IMarker[] file_ms; + + Collection<IResource> rBundles = rbmanager.getResourceBundles(vRB + .getResourceBundleId()); + if (!rBundles.isEmpty()) { + for (IResource r : rBundles) { + try { + file_ms = r.findMarkers(EditorUtils.RB_MARKER_ID, + false, IResource.DEPTH_INFINITE); + if (ms != null) { + ms = org.eclipse.babel.tapiji.tools.core.util.EditorUtils + .concatMarkerArray(ms, file_ms); + } else { + ms = file_ms; } - return sb.toString(); + } catch (Exception e) { + } } + } + } - return ""; + StringBuilder sb = new StringBuilder(); + int count = 0; + + if (ms != null && ms.length != 0) { + for (IMarker m : ms) { + try { + sb.append(m.getAttribute(IMarker.MESSAGE)); + sb.append("\n"); + count++; + if (count == MAX_PROBLEMS && ms.length - count != 0) { + sb.append(" ... and "); + sb.append(ms.length - count); + sb.append(" other problems"); + break; + } + } catch (CoreException e) { + } + ; + } + return sb.toString(); } + + return ""; + } } diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java index efb8810b..fa7a44eb 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java +++ b/org.eclipse.babel.tapiji.tools.rbmanager/src/org/eclipse/babel/tapiji/tools/rbmanager/viewer/filters/ProblematicResourceBundleFilter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Michael Gasser. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -27,58 +27,58 @@ public class ProblematicResourceBundleFilter extends ViewerFilter { - /** - * Shows only IContainer and VirtualResourcebundles with all his - * properties-files, which have RB_Marker. - */ - @Override - public boolean select(Viewer viewer, Object parentElement, Object element) { - if (element instanceof IFile) { - return true; + /** + * Shows only IContainer and VirtualResourcebundles with all his + * properties-files, which have RB_Marker. + */ + @Override + public boolean select(Viewer viewer, Object parentElement, Object element) { + if (element instanceof IFile) { + return true; + } + if (element instanceof VirtualResourceBundle) { + for (IResource f : ((VirtualResourceBundle) element).getFiles()) { + if (RBFileUtils.hasResourceBundleMarker(f)) { + return true; } - if (element instanceof VirtualResourceBundle) { - for (IResource f : ((VirtualResourceBundle) element).getFiles()) { - if (RBFileUtils.hasResourceBundleMarker(f)) { - return true; - } - } + } + } + if (element instanceof IContainer) { + try { + IMarker[] ms = null; + if ((ms = ((IContainer) element).findMarkers( + EditorUtils.RB_MARKER_ID, true, + IResource.DEPTH_INFINITE)).length > 0) { + return true; } - if (element instanceof IContainer) { - try { - IMarker[] ms = null; - if ((ms = ((IContainer) element).findMarkers( - EditorUtils.RB_MARKER_ID, true, - IResource.DEPTH_INFINITE)).length > 0) { - return true; - } - List<IContainer> fragmentContainer = ResourceUtils - .getCorrespondingFolders((IContainer) element, - FragmentProjectUtils - .getFragments(((IContainer) element) - .getProject())); + List<IContainer> fragmentContainer = ResourceUtils + .getCorrespondingFolders((IContainer) element, + FragmentProjectUtils + .getFragments(((IContainer) element) + .getProject())); - IMarker[] fragment_ms; - for (IContainer c : fragmentContainer) { - try { - if (c.exists()) { - fragment_ms = c.findMarkers( - EditorUtils.RB_MARKER_ID, false, - IResource.DEPTH_INFINITE); - ms = org.eclipse.babel.tapiji.tools.core.util.EditorUtils - .concatMarkerArray(ms, fragment_ms); - } - } catch (CoreException e) { - e.printStackTrace(); - } - } - if (ms.length > 0) { - return true; - } - - } catch (CoreException e) { + IMarker[] fragment_ms; + for (IContainer c : fragmentContainer) { + try { + if (c.exists()) { + fragment_ms = c.findMarkers( + EditorUtils.RB_MARKER_ID, false, + IResource.DEPTH_INFINITE); + ms = org.eclipse.babel.tapiji.tools.core.util.EditorUtils + .concatMarkerArray(ms, fragment_ms); } + } catch (CoreException e) { + e.printStackTrace(); + } + } + if (ms.length > 0) { + return true; } - return false; + + } catch (CoreException e) { + } } + return false; + } } diff --git a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesEditor.java b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesEditor.java index cdf73236..0c549d11 100644 --- a/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesEditor.java +++ b/org.eclipse.babel.tapiji.translator.rbe/src/org/eclipse/babel/tapiji/translator/rbe/babel/bundle/IMessagesEditor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Matthias Lettmayer. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -11,7 +11,7 @@ package org.eclipse.babel.tapiji.translator.rbe.babel.bundle; public interface IMessagesEditor { - String getSelectedKey(); + String getSelectedKey(); - void setSelectedKey(String key); + void setSelectedKey(String key); } diff --git a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java b/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java index 6eca3de2..30eac317 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceAuditor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -32,104 +32,104 @@ public class JSFResourceAuditor extends I18nResourceAuditor { - public String[] getFileEndings() { - return new String[] { "xhtml", "jsp" }; + public String[] getFileEndings() { + return new String[] { "xhtml", "jsp" }; + } + + public void audit(IResource resource) { + parse(resource); + } + + private void parse(IResource resource) { + + } + + @Override + public List<ILocation> getConstantStringLiterals() { + return new ArrayList<ILocation>(); + } + + @Override + public List<ILocation> getBrokenResourceReferences() { + return new ArrayList<ILocation>(); + } + + @Override + public List<ILocation> getBrokenBundleReferences() { + return new ArrayList<ILocation>(); + } + + @Override + public String getContextId() { + return "jsf"; + } + + @Override + public List<IMarkerResolution> getMarkerResolutions(IMarker marker) { + List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>(); + int cause = marker.getAttribute("cause", -1); + + switch (cause) { + case IMarkerConstants.CAUSE_CONSTANT_LITERAL: + resolutions.add(new ExportToResourceBundleResolution()); + break; + case IMarkerConstants.CAUSE_BROKEN_REFERENCE: + String dataName = marker.getAttribute("bundleName", ""); + int dataStart = marker.getAttribute("bundleStart", 0); + int dataEnd = marker.getAttribute("bundleEnd", 0); + + IProject project = marker.getResource().getProject(); + ResourceBundleManager manager = ResourceBundleManager + .getManager(project); + + if (manager.getResourceBundle(dataName) != null) { + String key = marker.getAttribute("key", ""); + + resolutions.add(new CreateResourceBundleEntry(key, dataName)); + resolutions.add(new ReplaceResourceBundleReference(key, + dataName)); + resolutions.add(new ReplaceResourceBundleDefReference(dataName, + dataStart, dataEnd)); + } else { + String bname = dataName; + + Set<IResource> bundleResources = ResourceBundleManager + .getManager(marker.getResource().getProject()) + .getAllResourceBundleResources(bname); + + if (bundleResources != null && bundleResources.size() > 0) + resolutions + .add(new IncludeResource(bname, bundleResources)); + else + resolutions.add(new CreateResourceBundle(bname, marker + .getResource(), dataStart, dataEnd)); + + resolutions.add(new ReplaceResourceBundleDefReference(bname, + dataStart, dataEnd)); + } + + break; + case IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE: + String bname = marker.getAttribute("key", ""); + + Set<IResource> bundleResources = ResourceBundleManager.getManager( + marker.getResource().getProject()) + .getAllResourceBundleResources(bname); + + if (bundleResources != null && bundleResources.size() > 0) + resolutions.add(new IncludeResource(bname, bundleResources)); + else + resolutions.add(new CreateResourceBundle(marker.getAttribute( + "key", ""), marker.getResource(), marker.getAttribute( + IMarker.CHAR_START, 0), marker.getAttribute( + IMarker.CHAR_END, 0))); + resolutions.add(new ReplaceResourceBundleDefReference(marker + .getAttribute("key", ""), marker.getAttribute( + IMarker.CHAR_START, 0), marker.getAttribute( + IMarker.CHAR_END, 0))); } - public void audit(IResource resource) { - parse(resource); - } - - private void parse(IResource resource) { - - } - - @Override - public List<ILocation> getConstantStringLiterals() { - return new ArrayList<ILocation>(); - } - - @Override - public List<ILocation> getBrokenResourceReferences() { - return new ArrayList<ILocation>(); - } - - @Override - public List<ILocation> getBrokenBundleReferences() { - return new ArrayList<ILocation>(); - } - - @Override - public String getContextId() { - return "jsf"; - } - - @Override - public List<IMarkerResolution> getMarkerResolutions(IMarker marker) { - List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>(); - int cause = marker.getAttribute("cause", -1); - - switch (cause) { - case IMarkerConstants.CAUSE_CONSTANT_LITERAL: - resolutions.add(new ExportToResourceBundleResolution()); - break; - case IMarkerConstants.CAUSE_BROKEN_REFERENCE: - String dataName = marker.getAttribute("bundleName", ""); - int dataStart = marker.getAttribute("bundleStart", 0); - int dataEnd = marker.getAttribute("bundleEnd", 0); - - IProject project = marker.getResource().getProject(); - ResourceBundleManager manager = ResourceBundleManager - .getManager(project); - - if (manager.getResourceBundle(dataName) != null) { - String key = marker.getAttribute("key", ""); - - resolutions.add(new CreateResourceBundleEntry(key, dataName)); - resolutions.add(new ReplaceResourceBundleReference(key, - dataName)); - resolutions.add(new ReplaceResourceBundleDefReference(dataName, - dataStart, dataEnd)); - } else { - String bname = dataName; - - Set<IResource> bundleResources = ResourceBundleManager - .getManager(marker.getResource().getProject()) - .getAllResourceBundleResources(bname); - - if (bundleResources != null && bundleResources.size() > 0) - resolutions - .add(new IncludeResource(bname, bundleResources)); - else - resolutions.add(new CreateResourceBundle(bname, marker - .getResource(), dataStart, dataEnd)); - - resolutions.add(new ReplaceResourceBundleDefReference(bname, - dataStart, dataEnd)); - } - - break; - case IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE: - String bname = marker.getAttribute("key", ""); - - Set<IResource> bundleResources = ResourceBundleManager.getManager( - marker.getResource().getProject()) - .getAllResourceBundleResources(bname); - - if (bundleResources != null && bundleResources.size() > 0) - resolutions.add(new IncludeResource(bname, bundleResources)); - else - resolutions.add(new CreateResourceBundle(marker.getAttribute( - "key", ""), marker.getResource(), marker.getAttribute( - IMarker.CHAR_START, 0), marker.getAttribute( - IMarker.CHAR_END, 0))); - resolutions.add(new ReplaceResourceBundleDefReference(marker - .getAttribute("key", ""), marker.getAttribute( - IMarker.CHAR_START, 0), marker.getAttribute( - IMarker.CHAR_END, 0))); - } - - return resolutions; - } + return resolutions; + } } diff --git a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceBundleDetector.java b/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceBundleDetector.java index 26c3bbed..1d6b513b 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceBundleDetector.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/auditor/JSFResourceBundleDetector.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -28,439 +28,439 @@ public class JSFResourceBundleDetector { - public static List<IRegion> getNonELValueRegions(String elExpression) { - List<IRegion> stringRegions = new ArrayList<IRegion>(); - int pos = -1; + public static List<IRegion> getNonELValueRegions(String elExpression) { + List<IRegion> stringRegions = new ArrayList<IRegion>(); + int pos = -1; - do { - int start = pos + 1; - int end = elExpression.indexOf("#{", start); - end = end >= 0 ? end : elExpression.length(); + do { + int start = pos + 1; + int end = elExpression.indexOf("#{", start); + end = end >= 0 ? end : elExpression.length(); - if (elExpression.substring(start, end).trim().length() > 0) { - IRegion region = new Region(start, end - start); - stringRegions.add(region); - } + if (elExpression.substring(start, end).trim().length() > 0) { + IRegion region = new Region(start, end - start); + stringRegions.add(region); + } - if (elExpression.substring(end).startsWith("#{")) - pos = elExpression.indexOf("}", end); - else - pos = end; - } while (pos >= 0 && pos < elExpression.length()); + if (elExpression.substring(end).startsWith("#{")) + pos = elExpression.indexOf("}", end); + else + pos = end; + } while (pos >= 0 && pos < elExpression.length()); - return stringRegions; - } + return stringRegions; + } + + public static String getBundleVariableName(String elExpression) { + String bundleVarName = null; + String[] delimitors = new String[] { ".", "[" }; - public static String getBundleVariableName(String elExpression) { - String bundleVarName = null; - String[] delimitors = new String[] { ".", "[" }; + int startPos = elExpression.indexOf(delimitors[0]); - int startPos = elExpression.indexOf(delimitors[0]); + for (String del : delimitors) { + if ((startPos > elExpression.indexOf(del) && elExpression + .indexOf(del) >= 0) + || (startPos == -1 && elExpression.indexOf(del) >= 0)) + startPos = elExpression.indexOf(del); + } - for (String del : delimitors) { - if ((startPos > elExpression.indexOf(del) && elExpression - .indexOf(del) >= 0) - || (startPos == -1 && elExpression.indexOf(del) >= 0)) - startPos = elExpression.indexOf(del); + if (startPos >= 0) + bundleVarName = elExpression.substring(0, startPos); + + return bundleVarName; + } + + public static String getResourceKey(String elExpression) { + String key = null; + + if (elExpression.indexOf("[") == -1 + || (elExpression.indexOf(".") < elExpression.indexOf("[") && elExpression + .indexOf(".") >= 0)) { + // Separation by dot + key = elExpression.substring(elExpression.indexOf(".") + 1); + } else { + // Separation by '[' and ']' + if (elExpression.indexOf("\"") >= 0 + || elExpression.indexOf("'") >= 0) { + int startPos = elExpression.indexOf("\"") >= 0 ? elExpression + .indexOf("\"") : elExpression.indexOf("'"); + int endPos = elExpression.indexOf("\"", startPos + 1) >= 0 ? elExpression + .indexOf("\"", startPos + 1) : elExpression.indexOf( + "'", startPos + 1); + if (startPos < endPos) { + key = elExpression.substring(startPos + 1, endPos); } + } + } - if (startPos >= 0) - bundleVarName = elExpression.substring(0, startPos); + return key; + } - return bundleVarName; - } + public static String resolveResourceBundleRefIdentifier(IDocument document, + int startPos) { + String result = null; - public static String getResourceKey(String elExpression) { - String key = null; - - if (elExpression.indexOf("[") == -1 - || (elExpression.indexOf(".") < elExpression.indexOf("[") && elExpression - .indexOf(".") >= 0)) { - // Separation by dot - key = elExpression.substring(elExpression.indexOf(".") + 1); - } else { - // Separation by '[' and ']' - if (elExpression.indexOf("\"") >= 0 - || elExpression.indexOf("'") >= 0) { - int startPos = elExpression.indexOf("\"") >= 0 ? elExpression - .indexOf("\"") : elExpression.indexOf("'"); - int endPos = elExpression.indexOf("\"", startPos + 1) >= 0 ? elExpression - .indexOf("\"", startPos + 1) : elExpression.indexOf( - "'", startPos + 1); - if (startPos < endPos) { - key = elExpression.substring(startPos + 1, endPos); - } - } - } + final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE + .getContext(document, startPos); + final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE + .getDOMContextResolver(context); - return key; - } + if (domResolver != null) { + final Node curNode = domResolver.getNode(); - public static String resolveResourceBundleRefIdentifier(IDocument document, - int startPos) { - String result = null; - - final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE - .getContext(document, startPos); - final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE - .getDOMContextResolver(context); - - if (domResolver != null) { - final Node curNode = domResolver.getNode(); - - // node must be an XML attribute - if (curNode instanceof Attr) { - final Attr attr = (Attr) curNode; - if (attr.getNodeName().toLowerCase().equals("basename")) { - final Element owner = attr.getOwnerElement(); - if (isBundleElement(owner, context)) - result = attr.getValue(); - } - } else if (curNode instanceof Element) { - final Element elem = (Element) curNode; - if (isBundleElement(elem, context)) - result = elem.getAttribute("basename"); - } + // node must be an XML attribute + if (curNode instanceof Attr) { + final Attr attr = (Attr) curNode; + if (attr.getNodeName().toLowerCase().equals("basename")) { + final Element owner = attr.getOwnerElement(); + if (isBundleElement(owner, context)) + result = attr.getValue(); } - - return result; + } else if (curNode instanceof Element) { + final Element elem = (Element) curNode; + if (isBundleElement(elem, context)) + result = elem.getAttribute("basename"); + } } - public static String resolveResourceBundleId(IDocument document, - String varName) { - String content = document.get(); - String bundleId = ""; - int offset = 0; - - while (content.indexOf("\"" + varName + "\"", offset + 1) >= 0 - || content.indexOf("'" + varName + "'", offset + 1) >= 0) { - offset = content.indexOf("\"" + varName + "\"") >= 0 ? content - .indexOf("\"" + varName + "\"") : content.indexOf("'" - + varName + "'"); - - final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE - .getContext(document, offset); - final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE - .getDOMContextResolver(context); - - if (domResolver != null) { - final Node curNode = domResolver.getNode(); - - // node must be an XML attribute - Attr attr = null; - if (curNode instanceof Attr) { - attr = (Attr) curNode; - if (!attr.getNodeName().toLowerCase().equals("var")) - continue; - } - - // Retrieve parent node - Element parentElement = (Element) attr.getOwnerElement(); - - if (!isBundleElement(parentElement, context)) - continue; - - bundleId = parentElement.getAttribute("basename"); - break; - } + return result; + } + + public static String resolveResourceBundleId(IDocument document, + String varName) { + String content = document.get(); + String bundleId = ""; + int offset = 0; + + while (content.indexOf("\"" + varName + "\"", offset + 1) >= 0 + || content.indexOf("'" + varName + "'", offset + 1) >= 0) { + offset = content.indexOf("\"" + varName + "\"") >= 0 ? content + .indexOf("\"" + varName + "\"") : content.indexOf("'" + + varName + "'"); + + final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE + .getContext(document, offset); + final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE + .getDOMContextResolver(context); + + if (domResolver != null) { + final Node curNode = domResolver.getNode(); + + // node must be an XML attribute + Attr attr = null; + if (curNode instanceof Attr) { + attr = (Attr) curNode; + if (!attr.getNodeName().toLowerCase().equals("var")) + continue; } - return bundleId; - } + // Retrieve parent node + Element parentElement = (Element) attr.getOwnerElement(); - public static boolean isBundleElement(Element element, - IStructuredDocumentContext context) { - String bName = element.getTagName().substring( - element.getTagName().indexOf(":") + 1); - - if (bName.equals("loadBundle")) { - final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE - .getTaglibContextResolver(context); - if (tlResolver.getTagURIForNodeName(element).trim() - .equalsIgnoreCase("http://java.sun.com/jsf/core")) { - return true; - } - } + if (!isBundleElement(parentElement, context)) + continue; - return false; + bundleId = parentElement.getAttribute("basename"); + break; + } } - public static boolean isJSFElement(Element element, - IStructuredDocumentContext context) { - try { - final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE - .getTaglibContextResolver(context); - if (tlResolver.getTagURIForNodeName(element).trim() - .equalsIgnoreCase("http://java.sun.com/jsf/core") - || tlResolver.getTagURIForNodeName(element).trim() - .equalsIgnoreCase("http://java.sun.com/jsf/html")) { - return true; - } - } catch (Exception e) { - } - return false; + return bundleId; + } + + public static boolean isBundleElement(Element element, + IStructuredDocumentContext context) { + String bName = element.getTagName().substring( + element.getTagName().indexOf(":") + 1); + + if (bName.equals("loadBundle")) { + final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE + .getTaglibContextResolver(context); + if (tlResolver.getTagURIForNodeName(element).trim() + .equalsIgnoreCase("http://java.sun.com/jsf/core")) { + return true; + } } - public static IRegion getBasenameRegion(IDocument document, int startPos) { - IRegion result = null; - - final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE - .getContext(document, startPos); - final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE - .getDOMContextResolver(context); - - if (domResolver != null) { - final Node curNode = domResolver.getNode(); - - // node must be an XML attribute - if (curNode instanceof Element) { - final Element elem = (Element) curNode; - if (isBundleElement(elem, context)) { - Attr na = elem.getAttributeNode("basename"); - - if (na != null) { - int attrStart = document.get().indexOf("basename", - startPos); - result = new Region(document.get().indexOf( - na.getValue(), attrStart), na.getValue() - .length()); - } - } - } + return false; + } + + public static boolean isJSFElement(Element element, + IStructuredDocumentContext context) { + try { + final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE + .getTaglibContextResolver(context); + if (tlResolver.getTagURIForNodeName(element).trim() + .equalsIgnoreCase("http://java.sun.com/jsf/core") + || tlResolver.getTagURIForNodeName(element).trim() + .equalsIgnoreCase("http://java.sun.com/jsf/html")) { + return true; + } + } catch (Exception e) { + } + return false; + } + + public static IRegion getBasenameRegion(IDocument document, int startPos) { + IRegion result = null; + + final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE + .getContext(document, startPos); + final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE + .getDOMContextResolver(context); + + if (domResolver != null) { + final Node curNode = domResolver.getNode(); + + // node must be an XML attribute + if (curNode instanceof Element) { + final Element elem = (Element) curNode; + if (isBundleElement(elem, context)) { + Attr na = elem.getAttributeNode("basename"); + + if (na != null) { + int attrStart = document.get().indexOf("basename", + startPos); + result = new Region(document.get().indexOf( + na.getValue(), attrStart), na.getValue() + .length()); + } } + } + } - return result; + return result; + } + + public static IRegion getElementAttrValueRegion(IDocument document, + String attribute, int startPos) { + IRegion result = null; + + final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE + .getContext(document, startPos); + final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE + .getDOMContextResolver(context); + + if (domResolver != null) { + Node curNode = domResolver.getNode(); + if (curNode instanceof Attr) + curNode = ((Attr) curNode).getOwnerElement(); + + // node must be an XML attribute + if (curNode instanceof Element) { + final Element elem = (Element) curNode; + Attr na = elem.getAttributeNode(attribute); + + if (na != null && isJSFElement(elem, context)) { + int attrStart = document.get().indexOf(attribute, startPos); + result = new Region(document.get().indexOf( + na.getValue().trim(), attrStart), na.getValue() + .trim().length()); + } + } } - public static IRegion getElementAttrValueRegion(IDocument document, - String attribute, int startPos) { - IRegion result = null; - - final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE - .getContext(document, startPos); - final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE - .getDOMContextResolver(context); - - if (domResolver != null) { - Node curNode = domResolver.getNode(); - if (curNode instanceof Attr) - curNode = ((Attr) curNode).getOwnerElement(); - - // node must be an XML attribute - if (curNode instanceof Element) { - final Element elem = (Element) curNode; - Attr na = elem.getAttributeNode(attribute); - - if (na != null && isJSFElement(elem, context)) { - int attrStart = document.get().indexOf(attribute, startPos); - result = new Region(document.get().indexOf( - na.getValue().trim(), attrStart), na.getValue() - .trim().length()); - } - } + return result; + } + + public static IRegion resolveResourceBundleRefPos(IDocument document, + String varName) { + String content = document.get(); + IRegion region = null; + int offset = 0; + + while (content.indexOf("\"" + varName + "\"", offset + 1) >= 0 + || content.indexOf("'" + varName + "'", offset + 1) >= 0) { + offset = content.indexOf("\"" + varName + "\"") >= 0 ? content + .indexOf("\"" + varName + "\"") : content.indexOf("'" + + varName + "'"); + + final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE + .getContext(document, offset); + final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE + .getDOMContextResolver(context); + + if (domResolver != null) { + final Node curNode = domResolver.getNode(); + + // node must be an XML attribute + Attr attr = null; + if (curNode instanceof Attr) { + attr = (Attr) curNode; + if (!attr.getNodeName().toLowerCase().equals("var")) + continue; } - return result; - } + // Retrieve parent node + Element parentElement = (Element) attr.getOwnerElement(); + + if (!isBundleElement(parentElement, context)) + continue; + + String bundleId = parentElement.getAttribute("basename"); - public static IRegion resolveResourceBundleRefPos(IDocument document, - String varName) { - String content = document.get(); - IRegion region = null; - int offset = 0; - - while (content.indexOf("\"" + varName + "\"", offset + 1) >= 0 - || content.indexOf("'" + varName + "'", offset + 1) >= 0) { - offset = content.indexOf("\"" + varName + "\"") >= 0 ? content - .indexOf("\"" + varName + "\"") : content.indexOf("'" - + varName + "'"); - - final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE - .getContext(document, offset); - final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE - .getDOMContextResolver(context); - - if (domResolver != null) { - final Node curNode = domResolver.getNode(); - - // node must be an XML attribute - Attr attr = null; - if (curNode instanceof Attr) { - attr = (Attr) curNode; - if (!attr.getNodeName().toLowerCase().equals("var")) - continue; - } - - // Retrieve parent node - Element parentElement = (Element) attr.getOwnerElement(); - - if (!isBundleElement(parentElement, context)) - continue; - - String bundleId = parentElement.getAttribute("basename"); - - if (bundleId != null && bundleId.trim().length() > 0) { - - while (region == null) { - int basename = content.indexOf("basename", offset); - int value = content.indexOf(bundleId, - content.indexOf("=", basename)); - if (value > basename) { - region = new Region(value, bundleId.length()); - } - } - - } - break; + if (bundleId != null && bundleId.trim().length() > 0) { + + while (region == null) { + int basename = content.indexOf("basename", offset); + int value = content.indexOf(bundleId, + content.indexOf("=", basename)); + if (value > basename) { + region = new Region(value, bundleId.length()); } - } + } - return region; + } + break; + } } - public static String resolveResourceBundleVariable(IDocument document, - String selectedResourceBundle) { - String content = document.get(); - String variableName = null; - int offset = 0; - - while (content - .indexOf("\"" + selectedResourceBundle + "\"", offset + 1) >= 0 - || content.indexOf("'" + selectedResourceBundle + "'", - offset + 1) >= 0) { - offset = content.indexOf("\"" + selectedResourceBundle + "\"") >= 0 ? content - .indexOf("\"" + selectedResourceBundle + "\"") : content - .indexOf("'" + selectedResourceBundle + "'"); - - final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE - .getContext(document, offset); - final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE - .getDOMContextResolver(context); - - if (domResolver != null) { - final Node curNode = domResolver.getNode(); - - // node must be an XML attribute - Attr attr = null; - if (curNode instanceof Attr) { - attr = (Attr) curNode; - if (!attr.getNodeName().toLowerCase().equals("basename")) - continue; - } - - // Retrieve parent node - Element parentElement = (Element) attr.getOwnerElement(); - - if (!isBundleElement(parentElement, context)) - continue; - - variableName = parentElement.getAttribute("var"); - break; - } + return region; + } + + public static String resolveResourceBundleVariable(IDocument document, + String selectedResourceBundle) { + String content = document.get(); + String variableName = null; + int offset = 0; + + while (content + .indexOf("\"" + selectedResourceBundle + "\"", offset + 1) >= 0 + || content.indexOf("'" + selectedResourceBundle + "'", + offset + 1) >= 0) { + offset = content.indexOf("\"" + selectedResourceBundle + "\"") >= 0 ? content + .indexOf("\"" + selectedResourceBundle + "\"") : content + .indexOf("'" + selectedResourceBundle + "'"); + + final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE + .getContext(document, offset); + final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE + .getDOMContextResolver(context); + + if (domResolver != null) { + final Node curNode = domResolver.getNode(); + + // node must be an XML attribute + Attr attr = null; + if (curNode instanceof Attr) { + attr = (Attr) curNode; + if (!attr.getNodeName().toLowerCase().equals("basename")) + continue; } - return variableName; + // Retrieve parent node + Element parentElement = (Element) attr.getOwnerElement(); + + if (!isBundleElement(parentElement, context)) + continue; + + variableName = parentElement.getAttribute("var"); + break; + } } - public static String resolveNewVariableName(IDocument document, - String selectedResourceBundle) { - String variableName = ""; - int i = 0; - variableName = selectedResourceBundle.replace(".", ""); - while (resolveResourceBundleId(document, variableName).trim().length() > 0) { - variableName = selectedResourceBundle + (i++); - } - return variableName; + return variableName; + } + + public static String resolveNewVariableName(IDocument document, + String selectedResourceBundle) { + String variableName = ""; + int i = 0; + variableName = selectedResourceBundle.replace(".", ""); + while (resolveResourceBundleId(document, variableName).trim().length() > 0) { + variableName = selectedResourceBundle + (i++); } + return variableName; + } - public static void createResourceBundleRef(IDocument document, - String selectedResourceBundle, String variableName) { - String content = document.get(); - int headInsertPos = -1; - int offset = 0; - - while (content.indexOf("head", offset + 1) >= 0) { - offset = content.indexOf("head", offset + 1); - - final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE - .getContext(document, offset); - final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE - .getDOMContextResolver(context); - - if (domResolver != null) { - final Node curNode = domResolver.getNode(); - - if (!(curNode instanceof Element)) { - continue; - } - - // Retrieve parent node - Element parentElement = (Element) curNode; - - if (parentElement.getNodeName().equalsIgnoreCase("head")) { - do { - headInsertPos = content.indexOf("head", offset + 5); - - final IStructuredDocumentContext contextHeadClose = IStructuredDocumentContextFactory.INSTANCE - .getContext(document, offset); - final IDOMContextResolver domResolverHeadClose = IStructuredDocumentContextResolverFactory.INSTANCE - .getDOMContextResolver(contextHeadClose); - if (domResolverHeadClose.getNode() instanceof Element - && domResolverHeadClose.getNode().getNodeName() - .equalsIgnoreCase("head")) { - headInsertPos = content.substring(0, headInsertPos) - .lastIndexOf("<"); - break; - } - } while (headInsertPos >= 0); - - if (headInsertPos < 0) { - headInsertPos = content.indexOf(">", offset) + 1; - } - - break; - } - } + public static void createResourceBundleRef(IDocument document, + String selectedResourceBundle, String variableName) { + String content = document.get(); + int headInsertPos = -1; + int offset = 0; + + while (content.indexOf("head", offset + 1) >= 0) { + offset = content.indexOf("head", offset + 1); + + final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE + .getContext(document, offset); + final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE + .getDOMContextResolver(context); + + if (domResolver != null) { + final Node curNode = domResolver.getNode(); + + if (!(curNode instanceof Element)) { + continue; } - // resolve the taglib - try { - int taglibPos = content.lastIndexOf("taglib"); - if (taglibPos > 0) { - final IStructuredDocumentContext taglibContext = IStructuredDocumentContextFactory.INSTANCE - .getContext(document, taglibPos); - taglibPos = content.indexOf("%>", taglibPos); - if (taglibPos > 0) { - String decl = createLoadBundleDeclaration(document, - taglibContext, variableName, selectedResourceBundle); - if (headInsertPos > taglibPos) - document.replace(headInsertPos, 0, decl); - else - document.replace(taglibPos, 0, decl); - } + // Retrieve parent node + Element parentElement = (Element) curNode; + + if (parentElement.getNodeName().equalsIgnoreCase("head")) { + do { + headInsertPos = content.indexOf("head", offset + 5); + + final IStructuredDocumentContext contextHeadClose = IStructuredDocumentContextFactory.INSTANCE + .getContext(document, offset); + final IDOMContextResolver domResolverHeadClose = IStructuredDocumentContextResolverFactory.INSTANCE + .getDOMContextResolver(contextHeadClose); + if (domResolverHeadClose.getNode() instanceof Element + && domResolverHeadClose.getNode().getNodeName() + .equalsIgnoreCase("head")) { + headInsertPos = content.substring(0, headInsertPos) + .lastIndexOf("<"); + break; } - } catch (Exception e) { - e.printStackTrace(); + } while (headInsertPos >= 0); + + if (headInsertPos < 0) { + headInsertPos = content.indexOf(">", offset) + 1; + } + + break; } + } + } + // resolve the taglib + try { + int taglibPos = content.lastIndexOf("taglib"); + if (taglibPos > 0) { + final IStructuredDocumentContext taglibContext = IStructuredDocumentContextFactory.INSTANCE + .getContext(document, taglibPos); + taglibPos = content.indexOf("%>", taglibPos); + if (taglibPos > 0) { + String decl = createLoadBundleDeclaration(document, + taglibContext, variableName, selectedResourceBundle); + if (headInsertPos > taglibPos) + document.replace(headInsertPos, 0, decl); + else + document.replace(taglibPos, 0, decl); + } + } + } catch (Exception e) { + e.printStackTrace(); } - private static String createLoadBundleDeclaration(IDocument document, - IStructuredDocumentContext context, String variableName, - String selectedResourceBundle) { - String bundleDecl = ""; + } - // Retrieve jsf core namespace prefix - final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE - .getTaglibContextResolver(context); - String bundlePrefix = tlResolver - .getTagPrefixForURI("http://java.sun.com/jsf/core"); + private static String createLoadBundleDeclaration(IDocument document, + IStructuredDocumentContext context, String variableName, + String selectedResourceBundle) { + String bundleDecl = ""; - MessageFormat tlFormatter = new MessageFormat( - "<{0}:loadBundle var=\"{1}\" basename=\"{2}\" />\r\n"); - bundleDecl = tlFormatter.format(new String[] { bundlePrefix, - variableName, selectedResourceBundle }); + // Retrieve jsf core namespace prefix + final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE + .getTaglibContextResolver(context); + String bundlePrefix = tlResolver + .getTagPrefixForURI("http://java.sun.com/jsf/core"); - return bundleDecl; - } + MessageFormat tlFormatter = new MessageFormat( + "<{0}:loadBundle var=\"{1}\" basename=\"{2}\" />\r\n"); + bundleDecl = tlFormatter.format(new String[] { bundlePrefix, + variableName, selectedResourceBundle }); + + return bundleDecl; + } } diff --git a/org.eclipselabs.tapiji.tools.jsf/src/auditor/model/SLLocation.java b/org.eclipselabs.tapiji.tools.jsf/src/auditor/model/SLLocation.java index 28debd95..b6998bc9 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/auditor/model/SLLocation.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/auditor/model/SLLocation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -17,55 +17,55 @@ public class SLLocation implements Serializable, ILocation { - private static final long serialVersionUID = 1L; - private IFile file = null; - private int startPos = -1; - private int endPos = -1; - private String literal; - private Serializable data; + private static final long serialVersionUID = 1L; + private IFile file = null; + private int startPos = -1; + private int endPos = -1; + private String literal; + private Serializable data; - public SLLocation(IFile file, int startPos, int endPos, String literal) { - super(); - this.file = file; - this.startPos = startPos; - this.endPos = endPos; - this.literal = literal; - } + public SLLocation(IFile file, int startPos, int endPos, String literal) { + super(); + this.file = file; + this.startPos = startPos; + this.endPos = endPos; + this.literal = literal; + } - public IFile getFile() { - return file; - } + public IFile getFile() { + return file; + } - public void setFile(IFile file) { - this.file = file; - } + public void setFile(IFile file) { + this.file = file; + } - public int getStartPos() { - return startPos; - } + public int getStartPos() { + return startPos; + } - public void setStartPos(int startPos) { - this.startPos = startPos; - } + public void setStartPos(int startPos) { + this.startPos = startPos; + } - public int getEndPos() { - return endPos; - } + public int getEndPos() { + return endPos; + } - public void setEndPos(int endPos) { - this.endPos = endPos; - } + public void setEndPos(int endPos) { + this.endPos = endPos; + } - public String getLiteral() { - return literal; - } + public String getLiteral() { + return literal; + } - public Serializable getData() { - return data; - } + public Serializable getData() { + return data; + } - public void setData(Serializable data) { - this.data = data; - } + public void setData(Serializable data) { + this.data = data; + } } diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java index 50b1fd90..5e4772d0 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ExportToResourceBundleResolution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -29,101 +29,101 @@ public class ExportToResourceBundleResolution implements IMarkerResolution2 { - public ExportToResourceBundleResolution() { + public ExportToResourceBundleResolution() { + } + + @Override + public String getDescription() { + return "Export constant string literal to a resource bundle."; + } + + @Override + public Image getImage() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getLabel() { + return "Export to Resource-Bundle"; + } + + @Override + public void run(IMarker marker) { + int startPos = marker.getAttribute(IMarker.CHAR_START, 0); + int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos; + IResource resource = marker.getResource(); + + ITextFileBufferManager bufferManager = FileBuffers + .getTextFileBufferManager(); + IPath path = resource.getRawLocation(); + try { + bufferManager.connect(path, null); + ITextFileBuffer textFileBuffer = bufferManager + .getTextFileBuffer(path); + IDocument document = textFileBuffer.getDocument(); + + CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( + Display.getDefault().getActiveShell()); + + DialogConfiguration config = dialog.new DialogConfiguration(); + config.setPreselectedKey(""); + config.setPreselectedMessage(""); + config.setPreselectedBundle((startPos < document.getLength() && endPos > 1) ? document + .get(startPos, endPos) : ""); + config.setPreselectedLocale(""); + config.setProjectName(resource.getProject().getName()); + + dialog.setDialogConfiguration(config); + + if (dialog.open() != InputDialog.OK) + return; + + /** Check for an existing resource bundle reference **/ + String bundleVar = JSFResourceBundleDetector + .resolveResourceBundleVariable(document, + dialog.getSelectedResourceBundle()); + + boolean requiresNewReference = false; + if (bundleVar == null) { + requiresNewReference = true; + bundleVar = JSFResourceBundleDetector.resolveNewVariableName( + document, dialog.getSelectedResourceBundle()); + } + + // insert resource reference + String key = dialog.getSelectedKey(); + + if (key.indexOf(".") >= 0) { + int quoteDblIdx = document.get().substring(0, startPos) + .lastIndexOf("\""); + int quoteSingleIdx = document.get().substring(0, startPos) + .lastIndexOf("'"); + String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'"; + + document.replace(startPos, endPos, "#{" + bundleVar + "[" + + quoteSign + key + quoteSign + "]}"); + } else { + document.replace(startPos, endPos, "#{" + bundleVar + "." + key + + "}"); + } + + if (requiresNewReference) { + JSFResourceBundleDetector.createResourceBundleRef(document, + dialog.getSelectedResourceBundle(), bundleVar); + } + + textFileBuffer.commit(null, false); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + bufferManager.disconnect(path, null); + } catch (CoreException e) { + e.printStackTrace(); + } } - @Override - public String getDescription() { - return "Export constant string literal to a resource bundle."; - } - - @Override - public Image getImage() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getLabel() { - return "Export to Resource-Bundle"; - } - - @Override - public void run(IMarker marker) { - int startPos = marker.getAttribute(IMarker.CHAR_START, 0); - int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos; - IResource resource = marker.getResource(); - - ITextFileBufferManager bufferManager = FileBuffers - .getTextFileBufferManager(); - IPath path = resource.getRawLocation(); - try { - bufferManager.connect(path, null); - ITextFileBuffer textFileBuffer = bufferManager - .getTextFileBuffer(path); - IDocument document = textFileBuffer.getDocument(); - - CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( - Display.getDefault().getActiveShell()); - - DialogConfiguration config = dialog.new DialogConfiguration(); - config.setPreselectedKey(""); - config.setPreselectedMessage(""); - config.setPreselectedBundle((startPos < document.getLength() && endPos > 1) ? document - .get(startPos, endPos) : ""); - config.setPreselectedLocale(""); - config.setProjectName(resource.getProject().getName()); - - dialog.setDialogConfiguration(config); - - if (dialog.open() != InputDialog.OK) - return; - - /** Check for an existing resource bundle reference **/ - String bundleVar = JSFResourceBundleDetector - .resolveResourceBundleVariable(document, - dialog.getSelectedResourceBundle()); - - boolean requiresNewReference = false; - if (bundleVar == null) { - requiresNewReference = true; - bundleVar = JSFResourceBundleDetector.resolveNewVariableName( - document, dialog.getSelectedResourceBundle()); - } - - // insert resource reference - String key = dialog.getSelectedKey(); - - if (key.indexOf(".") >= 0) { - int quoteDblIdx = document.get().substring(0, startPos) - .lastIndexOf("\""); - int quoteSingleIdx = document.get().substring(0, startPos) - .lastIndexOf("'"); - String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'"; - - document.replace(startPos, endPos, "#{" + bundleVar + "[" - + quoteSign + key + quoteSign + "]}"); - } else { - document.replace(startPos, endPos, "#{" + bundleVar + "." + key - + "}"); - } - - if (requiresNewReference) { - JSFResourceBundleDetector.createResourceBundleRef(document, - dialog.getSelectedResourceBundle(), bundleVar); - } - - textFileBuffer.commit(null, false); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - bufferManager.disconnect(path, null); - } catch (CoreException e) { - e.printStackTrace(); - } - } - - } + } } diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java index d98ba32f..6c8e7288 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/JSFViolationResolutionGenerator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -15,12 +15,12 @@ import org.eclipse.ui.IMarkerResolutionGenerator; public class JSFViolationResolutionGenerator implements - IMarkerResolutionGenerator { + IMarkerResolutionGenerator { - @Override - public IMarkerResolution[] getResolutions(IMarker marker) { - // TODO Auto-generated method stub - return null; - } + @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 79fbf52b..455ac9f3 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleDefReference.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -26,69 +26,69 @@ public class ReplaceResourceBundleDefReference implements IMarkerResolution2 { - private String key; - private int start; - private int end; + private String key; + private int start; + private int end; - public ReplaceResourceBundleDefReference(String key, int start, int end) { - this.key = key; - this.start = start; - this.end = end; - } + public ReplaceResourceBundleDefReference(String key, int start, int end) { + this.key = key; + this.start = start; + this.end = end; + } - @Override - public String getDescription() { - return "Replaces the non-existing Resource-Bundle reference '" + key - + "' with a reference to an already existing Resource-Bundle."; - } + @Override + public String getDescription() { + return "Replaces the non-existing Resource-Bundle reference '" + key + + "' with a reference to an already existing Resource-Bundle."; + } - @Override - public Image getImage() { - // TODO Auto-generated method stub - return null; - } + @Override + public Image getImage() { + // TODO Auto-generated method stub + return null; + } - @Override - public String getLabel() { - return "Select an alternative Resource-Bundle"; - } + @Override + public String getLabel() { + return "Select an alternative Resource-Bundle"; + } - @Override - public void run(IMarker marker) { - int startPos = start; - int endPos = end - start; - IResource resource = marker.getResource(); + @Override + public void run(IMarker marker) { + int startPos = start; + int endPos = end - start; + IResource resource = marker.getResource(); - ITextFileBufferManager bufferManager = FileBuffers - .getTextFileBufferManager(); - IPath path = resource.getRawLocation(); - try { - bufferManager.connect(path, null); - ITextFileBuffer textFileBuffer = bufferManager - .getTextFileBuffer(path); - IDocument document = textFileBuffer.getDocument(); + ITextFileBufferManager bufferManager = FileBuffers + .getTextFileBufferManager(); + IPath path = resource.getRawLocation(); + try { + bufferManager.connect(path, null); + ITextFileBuffer textFileBuffer = bufferManager + .getTextFileBuffer(path); + IDocument document = textFileBuffer.getDocument(); - ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog( - Display.getDefault().getActiveShell(), - resource.getProject()); + ResourceBundleSelectionDialog dialog = new ResourceBundleSelectionDialog( + Display.getDefault().getActiveShell(), + resource.getProject()); - if (dialog.open() != InputDialog.OK) - return; + if (dialog.open() != InputDialog.OK) + return; - key = dialog.getSelectedBundleId(); + key = dialog.getSelectedBundleId(); - document.replace(startPos, endPos, key); + document.replace(startPos, endPos, key); - textFileBuffer.commit(null, false); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - bufferManager.disconnect(path, null); - } catch (CoreException e) { - e.printStackTrace(); - } - } + textFileBuffer.commit(null, false); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + bufferManager.disconnect(path, null); + } catch (CoreException e) { + e.printStackTrace(); + } } + } } diff --git a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java index edd8e11f..d3204c7f 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/quickfix/ReplaceResourceBundleReference.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -30,86 +30,86 @@ public class ReplaceResourceBundleReference implements IMarkerResolution2 { - private String key; - private String bundleId; - - public ReplaceResourceBundleReference(String key, String bundleId) { - this.key = key; - this.bundleId = bundleId; - } - - @Override - public String getDescription() { - return "Replaces the non-existing Resource-Bundle key '" - + key - + "' with a reference to an already existing localized string literal."; - } - - @Override - public Image getImage() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getLabel() { - return "Select alternative Resource-Bundle entry"; - } - - @Override - public void run(IMarker marker) { - int startPos = marker.getAttribute(IMarker.CHAR_START, 0); - int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos; - IResource resource = marker.getResource(); - - ITextFileBufferManager bufferManager = FileBuffers - .getTextFileBufferManager(); - IPath path = resource.getRawLocation(); - try { - bufferManager.connect(path, null); - ITextFileBuffer textFileBuffer = bufferManager - .getTextFileBuffer(path); - IDocument document = textFileBuffer.getDocument(); - - ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog( - Display.getDefault().getActiveShell()); - - dialog.setProjectName(resource.getProject().getName()); - dialog.setBundleName(bundleId); - - if (dialog.open() != InputDialog.OK) - return; - - String key = dialog.getSelectedResource(); - Locale locale = dialog.getSelectedLocale(); - - String jsfBundleVar = JSFResourceBundleDetector - .getBundleVariableName(document.get().substring(startPos, - startPos + endPos)); - - if (key.indexOf(".") >= 0) { - int quoteDblIdx = document.get().substring(0, startPos) - .lastIndexOf("\""); - int quoteSingleIdx = document.get().substring(0, startPos) - .lastIndexOf("'"); - String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'"; - - document.replace(startPos, endPos, jsfBundleVar + "[" - + quoteSign + key + quoteSign + "]"); - } else { - document.replace(startPos, endPos, jsfBundleVar + "." + key); - } - - textFileBuffer.commit(null, false); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - bufferManager.disconnect(path, null); - } catch (CoreException e) { - e.printStackTrace(); - } - } + private String key; + private String bundleId; + + public ReplaceResourceBundleReference(String key, String bundleId) { + this.key = key; + this.bundleId = bundleId; + } + + @Override + public String getDescription() { + return "Replaces the non-existing Resource-Bundle key '" + + key + + "' with a reference to an already existing localized string literal."; + } + + @Override + public Image getImage() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getLabel() { + return "Select alternative Resource-Bundle entry"; + } + + @Override + public void run(IMarker marker) { + int startPos = marker.getAttribute(IMarker.CHAR_START, 0); + int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos; + IResource resource = marker.getResource(); + + ITextFileBufferManager bufferManager = FileBuffers + .getTextFileBufferManager(); + IPath path = resource.getRawLocation(); + try { + bufferManager.connect(path, null); + ITextFileBuffer textFileBuffer = bufferManager + .getTextFileBuffer(path); + IDocument document = textFileBuffer.getDocument(); + + ResourceBundleEntrySelectionDialog dialog = new ResourceBundleEntrySelectionDialog( + Display.getDefault().getActiveShell()); + + dialog.setProjectName(resource.getProject().getName()); + dialog.setBundleName(bundleId); + + if (dialog.open() != InputDialog.OK) + return; + + String key = dialog.getSelectedResource(); + Locale locale = dialog.getSelectedLocale(); + + String jsfBundleVar = JSFResourceBundleDetector + .getBundleVariableName(document.get().substring(startPos, + startPos + endPos)); + + if (key.indexOf(".") >= 0) { + int quoteDblIdx = document.get().substring(0, startPos) + .lastIndexOf("\""); + int quoteSingleIdx = document.get().substring(0, startPos) + .lastIndexOf("'"); + String quoteSign = quoteDblIdx < quoteSingleIdx ? "\"" : "'"; + + document.replace(startPos, endPos, jsfBundleVar + "[" + + quoteSign + key + quoteSign + "]"); + } else { + document.replace(startPos, endPos, jsfBundleVar + "." + key); + } + + textFileBuffer.commit(null, false); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + bufferManager.disconnect(path, null); + } catch (CoreException e) { + e.printStackTrace(); + } } + } } diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/JSFELMessageHover.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/JSFELMessageHover.java index d4db565d..e492212e 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/ui/JSFELMessageHover.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/JSFELMessageHover.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -32,47 +32,47 @@ */ public class JSFELMessageHover implements ITextHover { - private String expressionValue = ""; - private IProject project = null; + private String expressionValue = ""; + private IProject project = null; - public final String getHoverInfo(final ITextViewer textViewer, - final IRegion hoverRegion) { - String bundleName = JSFResourceBundleDetector.resolveResourceBundleId( - textViewer.getDocument(), JSFResourceBundleDetector - .getBundleVariableName(expressionValue)); - String resourceKey = JSFResourceBundleDetector - .getResourceKey(expressionValue); + public final String getHoverInfo(final ITextViewer textViewer, + final IRegion hoverRegion) { + String bundleName = JSFResourceBundleDetector.resolveResourceBundleId( + textViewer.getDocument(), JSFResourceBundleDetector + .getBundleVariableName(expressionValue)); + String resourceKey = JSFResourceBundleDetector + .getResourceKey(expressionValue); - return ELUtils.getResource(project, bundleName, resourceKey); - } + return ELUtils.getResource(project, bundleName, resourceKey); + } - public final IRegion getHoverRegion(final ITextViewer textViewer, - final int documentPosition) { - final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE - .getContext(textViewer, documentPosition); + public final IRegion getHoverRegion(final ITextViewer textViewer, + final int documentPosition) { + final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE + .getContext(textViewer, documentPosition); - IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE - .getWorkspaceContextResolver(context); + IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE + .getWorkspaceContextResolver(context); - project = workspaceResolver.getProject(); + project = workspaceResolver.getProject(); - if (project != null) { - if (!InternationalizationNature.hasNature(project)) - return null; - } else - return null; + if (project != null) { + if (!InternationalizationNature.hasNature(project)) + return null; + } else + return null; - final ITextRegionContextResolver symbolResolver = IStructuredDocumentContextResolverFactory.INSTANCE - .getTextRegionResolver(context); + final ITextRegionContextResolver symbolResolver = IStructuredDocumentContextResolverFactory.INSTANCE + .getTextRegionResolver(context); - if (!symbolResolver.getRegionType().equals( - DOMJSPRegionContexts.JSP_VBL_CONTENT)) - return null; - expressionValue = symbolResolver.getRegionText(); + if (!symbolResolver.getRegionType().equals( + DOMJSPRegionContexts.JSP_VBL_CONTENT)) + return null; + expressionValue = symbolResolver.getRegionText(); - return new Region(symbolResolver.getStartOffset(), - symbolResolver.getLength()); + return new Region(symbolResolver.getStartOffset(), + symbolResolver.getLength()); - } + } } diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/BundleNameProposal.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/BundleNameProposal.java index 0ddcd6ea..b0c7d4f6 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/BundleNameProposal.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/BundleNameProposal.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -36,126 +36,126 @@ public class BundleNameProposal implements IContentAssistProcessor { - @Override - public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, - int offset) { - List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>(); - - final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE - .getContext(viewer, offset); - - IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE - .getWorkspaceContextResolver(context); - - IProject project = workspaceResolver.getProject(); - IResource resource = workspaceResolver.getResource(); - - if (project != null) { - if (!InternationalizationNature.hasNature(project)) - return proposals.toArray(new ICompletionProposal[proposals - .size()]); - } else - return proposals.toArray(new ICompletionProposal[proposals.size()]); - - addBundleProposals(proposals, context, offset, viewer.getDocument(), - resource); - - return proposals.toArray(new ICompletionProposal[proposals.size()]); - } - - private void addBundleProposals(List<ICompletionProposal> proposals, - final IStructuredDocumentContext context, int startPos, - IDocument document, IResource resource) { - final ITextRegionContextResolver resolver = IStructuredDocumentContextResolverFactory.INSTANCE - .getTextRegionResolver(context); - - if (resolver != null) { - final String regionType = resolver.getRegionType(); - startPos = resolver.getStartOffset() + 1; - - if (regionType != null - && regionType - .equals(DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE)) { - - final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE - .getTaglibContextResolver(context); - - if (tlResolver != null) { - Attr attr = getAttribute(context); - String startString = attr.getValue(); - - int length = startString.length(); - - if (attr != null) { - Node tagElement = attr.getOwnerElement(); - if (tagElement == null) - return; - - String nodeName = tagElement.getNodeName(); - if (nodeName.substring(nodeName.indexOf(":") + 1) - .toLowerCase().equals("loadbundle")) { - ResourceBundleManager manager = ResourceBundleManager - .getManager(resource.getProject()); - for (String id : manager - .getResourceBundleIdentifiers()) { - if (id.startsWith(startString) - && id.length() != startString.length()) { - proposals - .add(new ui.autocompletion.MessageCompletionProposal( - startPos, length, id, true)); - } - } - } - } + @Override + public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, + int offset) { + List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>(); + + final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE + .getContext(viewer, offset); + + IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE + .getWorkspaceContextResolver(context); + + IProject project = workspaceResolver.getProject(); + IResource resource = workspaceResolver.getResource(); + + if (project != null) { + if (!InternationalizationNature.hasNature(project)) + return proposals.toArray(new ICompletionProposal[proposals + .size()]); + } else + return proposals.toArray(new ICompletionProposal[proposals.size()]); + + addBundleProposals(proposals, context, offset, viewer.getDocument(), + resource); + + return proposals.toArray(new ICompletionProposal[proposals.size()]); + } + + private void addBundleProposals(List<ICompletionProposal> proposals, + final IStructuredDocumentContext context, int startPos, + IDocument document, IResource resource) { + final ITextRegionContextResolver resolver = IStructuredDocumentContextResolverFactory.INSTANCE + .getTextRegionResolver(context); + + if (resolver != null) { + final String regionType = resolver.getRegionType(); + startPos = resolver.getStartOffset() + 1; + + if (regionType != null + && regionType + .equals(DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE)) { + + final ITaglibContextResolver tlResolver = IStructuredDocumentContextResolverFactory.INSTANCE + .getTaglibContextResolver(context); + + if (tlResolver != null) { + Attr attr = getAttribute(context); + String startString = attr.getValue(); + + int length = startString.length(); + + if (attr != null) { + Node tagElement = attr.getOwnerElement(); + if (tagElement == null) + return; + + String nodeName = tagElement.getNodeName(); + if (nodeName.substring(nodeName.indexOf(":") + 1) + .toLowerCase().equals("loadbundle")) { + ResourceBundleManager manager = ResourceBundleManager + .getManager(resource.getProject()); + for (String id : manager + .getResourceBundleIdentifiers()) { + if (id.startsWith(startString) + && id.length() != startString.length()) { + proposals + .add(new ui.autocompletion.MessageCompletionProposal( + startPos, length, id, true)); } + } } + } } + } } + } - private Attr getAttribute(IStructuredDocumentContext context) { - final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE - .getDOMContextResolver(context); - - if (domResolver != null) { - final Node curNode = domResolver.getNode(); + private Attr getAttribute(IStructuredDocumentContext context) { + final IDOMContextResolver domResolver = IStructuredDocumentContextResolverFactory.INSTANCE + .getDOMContextResolver(context); - if (curNode instanceof Attr) { - return (Attr) curNode; - } - } - return null; - - } - - @Override - public IContextInformation[] computeContextInformation(ITextViewer viewer, - int offset) { - // TODO Auto-generated method stub - return null; - } - - @Override - public char[] getCompletionProposalAutoActivationCharacters() { - // TODO Auto-generated method stub - return null; - } - - @Override - public char[] getContextInformationAutoActivationCharacters() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getErrorMessage() { - // TODO Auto-generated method stub - return null; - } + if (domResolver != null) { + final Node curNode = domResolver.getNode(); - @Override - public IContextInformationValidator getContextInformationValidator() { - // TODO Auto-generated method stub - return null; + if (curNode instanceof Attr) { + return (Attr) curNode; + } } + return null; + + } + + @Override + public IContextInformation[] computeContextInformation(ITextViewer viewer, + int offset) { + // TODO Auto-generated method stub + return null; + } + + @Override + public char[] getCompletionProposalAutoActivationCharacters() { + // TODO Auto-generated method stub + return null; + } + + @Override + public char[] getContextInformationAutoActivationCharacters() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getErrorMessage() { + // TODO Auto-generated method stub + return null; + } + + @Override + public IContextInformationValidator getContextInformationValidator() { + // TODO Auto-generated method stub + return null; + } } diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/MessageCompletionProposal.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/MessageCompletionProposal.java index 309f561f..2eddc8d8 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/MessageCompletionProposal.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/MessageCompletionProposal.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -19,64 +19,64 @@ public class MessageCompletionProposal implements IJavaCompletionProposal { - private int offset = 0; - private int length = 0; - private String content = ""; - private boolean messageAccessor = false; + private int offset = 0; + private int length = 0; + private String content = ""; + private boolean messageAccessor = false; - public MessageCompletionProposal(int offset, int length, String content, - boolean messageAccessor) { - this.offset = offset; - this.length = length; - this.content = content; - this.messageAccessor = messageAccessor; - } + public MessageCompletionProposal(int offset, int length, String content, + boolean messageAccessor) { + this.offset = offset; + this.length = length; + this.content = content; + this.messageAccessor = messageAccessor; + } - @Override - public void apply(IDocument document) { - try { - document.replace(offset, length, content); - } catch (Exception e) { - e.printStackTrace(); - } + @Override + public void apply(IDocument document) { + try { + document.replace(offset, length, content); + } catch (Exception e) { + e.printStackTrace(); } + } - @Override - public String getAdditionalProposalInfo() { - // TODO Auto-generated method stub - return "Inserts the property key '" + content - + "' of the resource-bundle 'at.test.messages'"; - } + @Override + public String getAdditionalProposalInfo() { + // TODO Auto-generated method stub + return "Inserts the property key '" + content + + "' of the resource-bundle 'at.test.messages'"; + } - @Override - public IContextInformation getContextInformation() { - // TODO Auto-generated method stub - return null; - } + @Override + public IContextInformation getContextInformation() { + // TODO Auto-generated method stub + return null; + } - @Override - public String getDisplayString() { - return content; - } + @Override + public String getDisplayString() { + return content; + } - @Override - public Image getImage() { - // TODO Auto-generated method stub - if (messageAccessor) - return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE); - return ImageUtils.getImage(ImageUtils.IMAGE_PROPERTIES_FILE); - } + @Override + public Image getImage() { + // TODO Auto-generated method stub + if (messageAccessor) + return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE); + return ImageUtils.getImage(ImageUtils.IMAGE_PROPERTIES_FILE); + } - @Override - public Point getSelection(IDocument document) { - // TODO Auto-generated method stub - return new Point(offset + content.length() + 1, 0); - } + @Override + public Point getSelection(IDocument document) { + // TODO Auto-generated method stub + return new Point(offset + content.length() + 1, 0); + } - @Override - public int getRelevance() { - // TODO Auto-generated method stub - return 99; - } + @Override + public int getRelevance() { + // TODO Auto-generated method stub + return 99; + } } diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java index c61fafcb..31abb867 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/NewResourceBundleEntryProposal.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -26,107 +26,107 @@ public class NewResourceBundleEntryProposal implements IJavaCompletionProposal { - private int startPos; - private int endPos; - private String value; - private ResourceBundleManager manager; - private IResource resource; - private String bundleName; - private String reference; - private boolean isKey; - - public NewResourceBundleEntryProposal(IResource resource, String str, - int startPos, int endPos, ResourceBundleManager manager, - String bundleName, boolean isKey) { - this.startPos = startPos; - this.endPos = endPos; - this.manager = manager; - this.value = str; - this.resource = resource; - this.bundleName = bundleName; - this.isKey = isKey; + private int startPos; + private int endPos; + private String value; + private ResourceBundleManager manager; + private IResource resource; + private String bundleName; + private String reference; + private boolean isKey; + + public NewResourceBundleEntryProposal(IResource resource, String str, + int startPos, int endPos, ResourceBundleManager manager, + String bundleName, boolean isKey) { + this.startPos = startPos; + this.endPos = endPos; + this.manager = manager; + this.value = str; + this.resource = resource; + this.bundleName = bundleName; + this.isKey = isKey; + } + + @Override + public void apply(IDocument document) { + + CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( + Display.getDefault().getActiveShell()); + + DialogConfiguration config = dialog.new DialogConfiguration(); + config.setPreselectedKey(isKey ? value : ""); + config.setPreselectedMessage(!isKey ? value : ""); + config.setPreselectedBundle(bundleName == null ? "" : bundleName); + config.setPreselectedLocale(""); + config.setProjectName(resource.getProject().getName()); + + dialog.setDialogConfiguration(config); + + if (dialog.open() != InputDialog.OK) { + return; } - @Override - public void apply(IDocument document) { + String resourceBundleId = dialog.getSelectedResourceBundle(); + String key = dialog.getSelectedKey(); - CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( - Display.getDefault().getActiveShell()); - - DialogConfiguration config = dialog.new DialogConfiguration(); - config.setPreselectedKey(isKey ? value : ""); - config.setPreselectedMessage(!isKey ? value : ""); - config.setPreselectedBundle(bundleName == null ? "" : bundleName); - config.setPreselectedLocale(""); - config.setProjectName(resource.getProject().getName()); - - dialog.setDialogConfiguration(config); - - if (dialog.open() != InputDialog.OK) { - return; - } - - String resourceBundleId = dialog.getSelectedResourceBundle(); - String key = dialog.getSelectedKey(); - - try { - document.replace(startPos, endPos, key); - reference = key + "\""; - ResourceBundleManager.rebuildProject(resource); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public String getAdditionalProposalInfo() { - // TODO Auto-generated method stub - return "Creates a new string literal within one of the" - + " project's resource bundles. This action results " - + "in a reference to the localized string literal!"; - } - - @Override - public IContextInformation getContextInformation() { - // TODO Auto-generated method stub - return null; + try { + document.replace(startPos, endPos, key); + reference = key + "\""; + ResourceBundleManager.rebuildProject(resource); + } catch (Exception e) { + e.printStackTrace(); } - - @Override - public String getDisplayString() { - String displayStr = ""; - - displayStr = "Create a new localized string literal"; - - if (this.isKey) { - if (value != null && value.length() > 0) - displayStr += " with the key '" + value + "'"; - } else { - if (value != null && value.length() > 0) - displayStr += " for '" + value + "'"; - } - return displayStr; - } - - @Override - public Image getImage() { - return PlatformUI.getWorkbench().getSharedImages() - .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage(); - } - - @Override - public Point getSelection(IDocument document) { - // TODO Auto-generated method stub - return new Point(startPos + reference.length() - 1, 0); - } - - @Override - public int getRelevance() { - // TODO Auto-generated method stub - if (this.value.trim().length() == 0) - return 1096; - else - return 1096; + } + + @Override + public String getAdditionalProposalInfo() { + // TODO Auto-generated method stub + return "Creates a new string literal within one of the" + + " project's resource bundles. This action results " + + "in a reference to the localized string literal!"; + } + + @Override + public IContextInformation getContextInformation() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getDisplayString() { + String displayStr = ""; + + displayStr = "Create a new localized string literal"; + + if (this.isKey) { + if (value != null && value.length() > 0) + displayStr += " with the key '" + value + "'"; + } else { + if (value != null && value.length() > 0) + displayStr += " for '" + value + "'"; } + return displayStr; + } + + @Override + public Image getImage() { + return PlatformUI.getWorkbench().getSharedImages() + .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage(); + } + + @Override + public Point getSelection(IDocument document) { + // TODO Auto-generated method stub + return new Point(startPos + reference.length() - 1, 0); + } + + @Override + public int getRelevance() { + // TODO Auto-generated method stub + if (this.value.trim().length() == 0) + return 1096; + else + return 1096; + } } diff --git a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java index 32559141..2bfbaf76 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/ui/autocompletion/jsf/MessageCompletionProposal.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -34,92 +34,92 @@ public class MessageCompletionProposal implements IContentAssistProcessor { - @Override - public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, - int offset) { - List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>(); - - final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE - .getContext(viewer, offset); - - IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE - .getWorkspaceContextResolver(context); - - IProject project = workspaceResolver.getProject(); - IResource resource = workspaceResolver.getResource(); - - if (project != null) { - if (!InternationalizationNature.hasNature(project)) - return proposals.toArray(new CompletionProposal[proposals - .size()]); - } else - return proposals.toArray(new CompletionProposal[proposals.size()]); - - // Compute proposals - String expression = getProposalPrefix(viewer.getDocument(), offset); - String bundleId = JSFResourceBundleDetector.resolveResourceBundleId( - viewer.getDocument(), - JSFResourceBundleDetector.getBundleVariableName(expression)); - String key = JSFResourceBundleDetector.getResourceKey(expression); - - if (expression.trim().length() > 0 && bundleId.trim().length() > 0 - && isNonExistingKey(project, bundleId, key)) { - // Add 'New Resource' proposal - int startpos = offset - key.length(); - int length = key.length(); - - proposals.add(new NewResourceBundleEntryProposal(resource, key, - startpos, length, - ResourceBundleManager.getManager(project), bundleId, true)); - } - - return proposals.toArray(new ICompletionProposal[proposals.size()]); + @Override + public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, + int offset) { + List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>(); + + final IStructuredDocumentContext context = IStructuredDocumentContextFactory.INSTANCE + .getContext(viewer, offset); + + IWorkspaceContextResolver workspaceResolver = IStructuredDocumentContextResolverFactory.INSTANCE + .getWorkspaceContextResolver(context); + + IProject project = workspaceResolver.getProject(); + IResource resource = workspaceResolver.getResource(); + + if (project != null) { + if (!InternationalizationNature.hasNature(project)) + return proposals.toArray(new CompletionProposal[proposals + .size()]); + } else + return proposals.toArray(new CompletionProposal[proposals.size()]); + + // Compute proposals + String expression = getProposalPrefix(viewer.getDocument(), offset); + String bundleId = JSFResourceBundleDetector.resolveResourceBundleId( + viewer.getDocument(), + JSFResourceBundleDetector.getBundleVariableName(expression)); + String key = JSFResourceBundleDetector.getResourceKey(expression); + + if (expression.trim().length() > 0 && bundleId.trim().length() > 0 + && isNonExistingKey(project, bundleId, key)) { + // Add 'New Resource' proposal + int startpos = offset - key.length(); + int length = key.length(); + + proposals.add(new NewResourceBundleEntryProposal(resource, key, + startpos, length, + ResourceBundleManager.getManager(project), bundleId, true)); } - private String getProposalPrefix(IDocument document, int offset) { - String content = document.get().substring(0, offset); - int expIntro = content.lastIndexOf("#{"); - - return content.substring(expIntro + 2, offset); - } - - protected boolean isNonExistingKey(IProject project, String bundleId, - String key) { - ResourceBundleManager manager = ResourceBundleManager - .getManager(project); - - return !manager.isResourceExisting(bundleId, key); - } - - @Override - public IContextInformation[] computeContextInformation(ITextViewer viewer, - int offset) { - // TODO Auto-generated method stub - return null; - } - - @Override - public char[] getCompletionProposalAutoActivationCharacters() { - // TODO Auto-generated method stub - return null; - } - - @Override - public char[] getContextInformationAutoActivationCharacters() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getErrorMessage() { - // TODO Auto-generated method stub - return null; - } - - @Override - public IContextInformationValidator getContextInformationValidator() { - // TODO Auto-generated method stub - return null; - } + return proposals.toArray(new ICompletionProposal[proposals.size()]); + } + + private String getProposalPrefix(IDocument document, int offset) { + String content = document.get().substring(0, offset); + int expIntro = content.lastIndexOf("#{"); + + return content.substring(expIntro + 2, offset); + } + + protected boolean isNonExistingKey(IProject project, String bundleId, + String key) { + ResourceBundleManager manager = ResourceBundleManager + .getManager(project); + + return !manager.isResourceExisting(bundleId, key); + } + + @Override + public IContextInformation[] computeContextInformation(ITextViewer viewer, + int offset) { + // TODO Auto-generated method stub + return null; + } + + @Override + public char[] getCompletionProposalAutoActivationCharacters() { + // TODO Auto-generated method stub + return null; + } + + @Override + public char[] getContextInformationAutoActivationCharacters() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getErrorMessage() { + // TODO Auto-generated method stub + return null; + } + + @Override + public IContextInformationValidator getContextInformationValidator() { + // TODO Auto-generated method stub + return null; + } } diff --git a/org.eclipselabs.tapiji.tools.jsf/src/util/ELUtils.java b/org.eclipselabs.tapiji.tools.jsf/src/util/ELUtils.java index cdfcc46d..b0791474 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/util/ELUtils.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/util/ELUtils.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -15,13 +15,13 @@ public class ELUtils { - public static String getResource(IProject project, String bundleName, - String key) { - ResourceBundleManager manager = ResourceBundleManager - .getManager(project); - if (manager.isResourceExisting(bundleName, key)) - return manager.getKeyHoverString(bundleName, key); - else - return null; - } + public static String getResource(IProject project, String bundleName, + String key) { + ResourceBundleManager manager = ResourceBundleManager + .getManager(project); + if (manager.isResourceExisting(bundleName, key)) + return manager.getKeyHoverString(bundleName, key); + else + return null; + } } diff --git a/org.eclipselabs.tapiji.tools.jsf/src/validator/JSFInternationalizationValidator.java b/org.eclipselabs.tapiji.tools.jsf/src/validator/JSFInternationalizationValidator.java index 02b5f6e8..e1a1aff8 100644 --- a/org.eclipselabs.tapiji.tools.jsf/src/validator/JSFInternationalizationValidator.java +++ b/org.eclipselabs.tapiji.tools.jsf/src/validator/JSFInternationalizationValidator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * Copyright (c) 2012 Matthias Lettmayer. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -31,182 +31,182 @@ import auditor.model.SLLocation; public class JSFInternationalizationValidator implements IValidator, - ISourceValidator { - - private IDocument document; - - @Override - public void cleanup(IReporter reporter) { + ISourceValidator { + + private IDocument document; + + @Override + public void cleanup(IReporter reporter) { + } + + @Override + public void validate(IValidationContext context, IReporter reporter) + throws ValidationException { + if (context.getURIs().length > 0) { + IFile file = ResourcesPlugin.getWorkspace().getRoot() + .getFile(new Path(context.getURIs()[0])); + + // full document validation + org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils + .deleteAuditMarkersForResource(file.getProject() + .findMember(file.getProjectRelativePath())); + + // validate all bundle definitions + int pos = document.get().indexOf("loadBundle", 0); + while (pos >= 0) { + validateRegion(new Region(pos, 1), context, reporter); + pos = document.get().indexOf("loadBundle", pos + 1); + } + + // iterate all value definitions + pos = document.get().indexOf(" value", 0); + while (pos >= 0) { + validateRegion(new Region(pos, 1), context, reporter); + pos = document.get().indexOf(" value", pos + 1); + } } - - @Override - public void validate(IValidationContext context, IReporter reporter) - throws ValidationException { - if (context.getURIs().length > 0) { - IFile file = ResourcesPlugin.getWorkspace().getRoot() - .getFile(new Path(context.getURIs()[0])); - - // full document validation - org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils - .deleteAuditMarkersForResource(file.getProject() - .findMember(file.getProjectRelativePath())); - - // validate all bundle definitions - int pos = document.get().indexOf("loadBundle", 0); - while (pos >= 0) { - validateRegion(new Region(pos, 1), context, reporter); - pos = document.get().indexOf("loadBundle", pos + 1); - } - - // iterate all value definitions - pos = document.get().indexOf(" value", 0); - while (pos >= 0) { - validateRegion(new Region(pos, 1), context, reporter); - pos = document.get().indexOf(" value", pos + 1); - } + } + + @Override + public void connect(IDocument doc) { + document = doc; + } + + @Override + public void disconnect(IDocument arg0) { + document = null; + } + + public void validateRegion(IRegion dirtyRegion, IValidationContext context, + IReporter reporter) { + int startPos = dirtyRegion.getOffset(); + int endPos = dirtyRegion.getOffset() + dirtyRegion.getLength(); + + if (context.getURIs().length > 0) { + IFile file = ResourcesPlugin.getWorkspace().getRoot() + .getFile(new Path(context.getURIs()[0])); + ResourceBundleManager manager = ResourceBundleManager + .getManager(file.getProject()); + + String bundleName = JSFResourceBundleDetector + .resolveResourceBundleRefIdentifier(document, startPos); + if (bundleName != null + && !manager.getResourceBundleIdentifiers().contains( + bundleName)) { + IRegion reg = JSFResourceBundleDetector.getBasenameRegion( + document, startPos); + String ref = document.get().substring(reg.getOffset(), + reg.getOffset() + reg.getLength()); + + org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils + .reportToMarker( + EditorUtils + .getFormattedMessage( + EditorUtils.MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE, + new String[] { ref }), + new SLLocation(file, reg.getOffset(), reg + .getOffset() + reg.getLength(), ref), + IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE, + ref, null, "jsf"); + return; + } + + IRegion evr = JSFResourceBundleDetector.getElementAttrValueRegion( + document, "value", startPos); + if (evr != null) { + String elementValue = document.get().substring(evr.getOffset(), + evr.getOffset() + evr.getLength()); + + // check all constant string expressions + List<IRegion> regions = JSFResourceBundleDetector + .getNonELValueRegions(elementValue); + + for (IRegion region : regions) { + // report constant string literals + String constantLiteral = elementValue.substring( + region.getOffset(), + region.getOffset() + region.getLength()); + + org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils + .reportToMarker( + EditorUtils + .getFormattedMessage( + EditorUtils.MESSAGE_NON_LOCALIZED_LITERAL, + new String[] { constantLiteral }), + new SLLocation(file, region.getOffset() + + evr.getOffset(), evr.getOffset() + + region.getOffset() + + region.getLength(), + constantLiteral), + IMarkerConstants.CAUSE_CONSTANT_LITERAL, + constantLiteral, null, "jsf"); } - } - @Override - public void connect(IDocument doc) { - document = doc; - } - - @Override - public void disconnect(IDocument arg0) { - document = null; - } - - public void validateRegion(IRegion dirtyRegion, IValidationContext context, - IReporter reporter) { - int startPos = dirtyRegion.getOffset(); - int endPos = dirtyRegion.getOffset() + dirtyRegion.getLength(); - - if (context.getURIs().length > 0) { - IFile file = ResourcesPlugin.getWorkspace().getRoot() - .getFile(new Path(context.getURIs()[0])); - ResourceBundleManager manager = ResourceBundleManager - .getManager(file.getProject()); - - String bundleName = JSFResourceBundleDetector - .resolveResourceBundleRefIdentifier(document, startPos); - if (bundleName != null - && !manager.getResourceBundleIdentifiers().contains( - bundleName)) { - IRegion reg = JSFResourceBundleDetector.getBasenameRegion( - document, startPos); - String ref = document.get().substring(reg.getOffset(), - reg.getOffset() + reg.getLength()); - - org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils - .reportToMarker( - EditorUtils - .getFormattedMessage( - EditorUtils.MESSAGE_BROKEN_RESOURCE_BUNDLE_REFERENCE, - new String[] { ref }), - new SLLocation(file, reg.getOffset(), reg - .getOffset() + reg.getLength(), ref), - IMarkerConstants.CAUSE_BROKEN_RB_REFERENCE, - ref, null, "jsf"); - return; - } - - IRegion evr = JSFResourceBundleDetector.getElementAttrValueRegion( - document, "value", startPos); - if (evr != null) { - String elementValue = document.get().substring(evr.getOffset(), - evr.getOffset() + evr.getLength()); - - // check all constant string expressions - List<IRegion> regions = JSFResourceBundleDetector - .getNonELValueRegions(elementValue); - - for (IRegion region : regions) { - // report constant string literals - String constantLiteral = elementValue.substring( - region.getOffset(), - region.getOffset() + region.getLength()); - - org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils - .reportToMarker( - EditorUtils - .getFormattedMessage( - EditorUtils.MESSAGE_NON_LOCALIZED_LITERAL, - new String[] { constantLiteral }), - new SLLocation(file, region.getOffset() - + evr.getOffset(), evr.getOffset() - + region.getOffset() - + region.getLength(), - constantLiteral), - IMarkerConstants.CAUSE_CONSTANT_LITERAL, - constantLiteral, null, "jsf"); + // check el expressions + int start = document.get().indexOf("#{", evr.getOffset()); + + while (start >= 0 && start < evr.getOffset() + evr.getLength()) { + int end = document.get().indexOf("}", start); + end = Math.min(end, evr.getOffset() + evr.getLength()); + + if ((end - start) > 6) { + String def = document.get().substring(start + 2, end); + String varName = JSFResourceBundleDetector + .getBundleVariableName(def); + String key = JSFResourceBundleDetector + .getResourceKey(def); + if (varName != null && key != null) { + if (varName.length() > 0) { + IRegion refReg = JSFResourceBundleDetector + .resolveResourceBundleRefPos(document, + varName); + + if (refReg == null) { + start = document.get().indexOf("#{", end); + continue; } - // check el expressions - int start = document.get().indexOf("#{", evr.getOffset()); - - while (start >= 0 && start < evr.getOffset() + evr.getLength()) { - int end = document.get().indexOf("}", start); - end = Math.min(end, evr.getOffset() + evr.getLength()); - - if ((end - start) > 6) { - String def = document.get().substring(start + 2, end); - String varName = JSFResourceBundleDetector - .getBundleVariableName(def); - String key = JSFResourceBundleDetector - .getResourceKey(def); - if (varName != null && key != null) { - if (varName.length() > 0) { - IRegion refReg = JSFResourceBundleDetector - .resolveResourceBundleRefPos(document, - varName); - - if (refReg == null) { - start = document.get().indexOf("#{", end); - continue; - } - - int bundleStart = refReg.getOffset(); - int bundleEnd = refReg.getOffset() - + refReg.getLength(); - - if (manager.isKeyBroken( - document.get().substring( - refReg.getOffset(), - refReg.getOffset() - + refReg.getLength()), - key)) { - SLLocation subMarker = new SLLocation(file, - bundleStart, bundleEnd, document - .get().substring( - bundleStart, - bundleEnd)); - org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils - .reportToMarker( - EditorUtils - .getFormattedMessage( - EditorUtils.MESSAGE_BROKEN_RESOURCE_REFERENCE, - new String[] { - key, - subMarker - .getLiteral() }), - new SLLocation(file, - start + 2, end, key), - IMarkerConstants.CAUSE_BROKEN_REFERENCE, - key, subMarker, "jsf"); - } - } - } - } - - start = document.get().indexOf("#{", end); + int bundleStart = refReg.getOffset(); + int bundleEnd = refReg.getOffset() + + refReg.getLength(); + + if (manager.isKeyBroken( + document.get().substring( + refReg.getOffset(), + refReg.getOffset() + + refReg.getLength()), + key)) { + SLLocation subMarker = new SLLocation(file, + bundleStart, bundleEnd, document + .get().substring( + bundleStart, + bundleEnd)); + org.eclipse.babel.tapiji.tools.core.ui.utils.EditorUtils + .reportToMarker( + EditorUtils + .getFormattedMessage( + EditorUtils.MESSAGE_BROKEN_RESOURCE_REFERENCE, + new String[] { + key, + subMarker + .getLiteral() }), + new SLLocation(file, + start + 2, end, key), + IMarkerConstants.CAUSE_BROKEN_REFERENCE, + key, subMarker, "jsf"); } + } } + } + + start = document.get().indexOf("#{", end); } + } } + } - @Override - public void validate(IRegion arg0, IValidationContext arg1, IReporter arg2) { - } + @Override + public void validate(IRegion arg0, IValidationContext arg1, IReporter arg2) { + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Activator.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Activator.java index fe5188e1..e3434895 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Activator.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Activator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -19,60 +19,60 @@ */ public class Activator extends AbstractUIPlugin { - // The plug-in ID - public static final String PLUGIN_ID = "org.eclipselabs.tapiji.translator"; //$NON-NLS-1$ + // The plug-in ID + public static final String PLUGIN_ID = "org.eclipselabs.tapiji.translator"; //$NON-NLS-1$ - // The shared instance - private static Activator plugin; + // The shared instance + private static Activator plugin; - /** - * The constructor - */ - public Activator() { - } + /** + * The constructor + */ + public Activator() { + } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext - * ) - */ - public void start(BundleContext context) throws Exception { - super.start(context); - plugin = this; - } + /* + * (non-Javadoc) + * + * @see + * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext + * ) + */ + public void start(BundleContext context) throws Exception { + super.start(context); + plugin = this; + } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext - * ) - */ - public void stop(BundleContext context) throws Exception { - plugin = null; - super.stop(context); - } + /* + * (non-Javadoc) + * + * @see + * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext + * ) + */ + public void stop(BundleContext context) throws Exception { + plugin = null; + super.stop(context); + } - /** - * Returns the shared instance - * - * @return the shared instance - */ - public static Activator getDefault() { - return plugin; - } + /** + * Returns the shared instance + * + * @return the shared instance + */ + public static Activator getDefault() { + return plugin; + } - /** - * Returns an image descriptor for the image file at the given plug-in - * relative path - * - * @param path - * the path - * @return the image descriptor - */ - public static ImageDescriptor getImageDescriptor(String path) { - return imageDescriptorFromPlugin(PLUGIN_ID, path); - } + /** + * Returns an image descriptor for the image file at the given plug-in + * relative path + * + * @param path + * the path + * @return the image descriptor + */ + public static ImageDescriptor getImageDescriptor(String path) { + return imageDescriptorFromPlugin(PLUGIN_ID, path); + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Application.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Application.java index e7aa31fc..b6913678 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Application.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Application.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -21,41 +21,41 @@ */ public class Application implements IApplication { - /* - * (non-Javadoc) - * - * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app. - * IApplicationContext) - */ - public Object start(IApplicationContext context) { - Display display = PlatformUI.createDisplay(); - try { - int returnCode = PlatformUI.createAndRunWorkbench(display, - new ApplicationWorkbenchAdvisor()); - if (returnCode == PlatformUI.RETURN_RESTART) { - return IApplication.EXIT_RESTART; - } - return IApplication.EXIT_OK; - } finally { - display.dispose(); - } + /* + * (non-Javadoc) + * + * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app. + * IApplicationContext) + */ + public Object start(IApplicationContext context) { + Display display = PlatformUI.createDisplay(); + try { + int returnCode = PlatformUI.createAndRunWorkbench(display, + new ApplicationWorkbenchAdvisor()); + if (returnCode == PlatformUI.RETURN_RESTART) { + return IApplication.EXIT_RESTART; + } + return IApplication.EXIT_OK; + } finally { + display.dispose(); } + } - /* - * (non-Javadoc) - * - * @see org.eclipse.equinox.app.IApplication#stop() - */ - public void stop() { - if (!PlatformUI.isWorkbenchRunning()) - return; - final IWorkbench workbench = PlatformUI.getWorkbench(); - final Display display = workbench.getDisplay(); - display.syncExec(new Runnable() { - public void run() { - if (!display.isDisposed()) - workbench.close(); - } - }); - } + /* + * (non-Javadoc) + * + * @see org.eclipse.equinox.app.IApplication#stop() + */ + public void stop() { + if (!PlatformUI.isWorkbenchRunning()) + return; + final IWorkbench workbench = PlatformUI.getWorkbench(); + final Display display = workbench.getDisplay(); + display.syncExec(new Runnable() { + public void run() { + if (!display.isDisposed()) + workbench.close(); + } + }); + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationActionBarAdvisor.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationActionBarAdvisor.java index ee1cda38..9293d6bf 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationActionBarAdvisor.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationActionBarAdvisor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -33,92 +33,92 @@ */ public class ApplicationActionBarAdvisor extends ActionBarAdvisor { - public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) { - super(configurer); - } - - @Override - protected void fillCoolBar(ICoolBarManager coolBar) { - super.fillCoolBar(coolBar); - - coolBar.add(new GroupMarker("group.file")); - { - // File Group - IToolBarManager fileToolBar = new ToolBarManager(coolBar.getStyle()); - - fileToolBar.add(new Separator(IWorkbenchActionConstants.NEW_GROUP)); - fileToolBar - .add(new GroupMarker(IWorkbenchActionConstants.OPEN_EXT)); - - fileToolBar.add(new GroupMarker( - IWorkbenchActionConstants.SAVE_GROUP)); - fileToolBar.add(getAction(ActionFactory.SAVE.getId())); - - // Add to the cool bar manager - coolBar.add(new ToolBarContributionItem(fileToolBar, - IWorkbenchActionConstants.TOOLBAR_FILE)); - } - - coolBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); - coolBar.add(new GroupMarker(IWorkbenchActionConstants.GROUP_EDITOR)); - } - - @Override - protected void fillMenuBar(IMenuManager menuBar) { - super.fillMenuBar(menuBar); + public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) { + super(configurer); + } - menuBar.add(fileMenu()); - menuBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); - menuBar.add(helpMenu()); - } + @Override + protected void fillCoolBar(ICoolBarManager coolBar) { + super.fillCoolBar(coolBar); - private MenuManager helpMenu() { - MenuManager helpMenu = new MenuManager("&Help", - IWorkbenchActionConstants.M_HELP); + coolBar.add(new GroupMarker("group.file")); + { + // File Group + IToolBarManager fileToolBar = new ToolBarManager(coolBar.getStyle()); - helpMenu.add(getAction(ActionFactory.ABOUT.getId())); + fileToolBar.add(new Separator(IWorkbenchActionConstants.NEW_GROUP)); + fileToolBar + .add(new GroupMarker(IWorkbenchActionConstants.OPEN_EXT)); - return helpMenu; - } + fileToolBar.add(new GroupMarker( + IWorkbenchActionConstants.SAVE_GROUP)); + fileToolBar.add(getAction(ActionFactory.SAVE.getId())); - private MenuManager fileMenu() { - MenuManager menu = new MenuManager("&File", "file_mnu"); - menu.add(new GroupMarker(IWorkbenchActionConstants.FILE_START)); - - menu.add(getAction(ActionFactory.CLOSE.getId())); - menu.add(getAction(ActionFactory.CLOSE_ALL.getId())); - - menu.add(new GroupMarker(IWorkbenchActionConstants.CLOSE_EXT)); - menu.add(new Separator()); - menu.add(getAction(ActionFactory.SAVE.getId())); - menu.add(getAction(ActionFactory.SAVE_ALL.getId())); - - menu.add(ContributionItemFactory.REOPEN_EDITORS - .create(getActionBarConfigurer().getWindowConfigurer() - .getWindow())); - menu.add(new GroupMarker(IWorkbenchActionConstants.MRU)); - menu.add(new Separator()); - menu.add(getAction(ActionFactory.QUIT.getId())); - return menu; + // Add to the cool bar manager + coolBar.add(new ToolBarContributionItem(fileToolBar, + IWorkbenchActionConstants.TOOLBAR_FILE)); } - @Override - protected void makeActions(IWorkbenchWindow window) { - super.makeActions(window); - - registerAsGlobal(ActionFactory.SAVE.create(window)); - registerAsGlobal(ActionFactory.SAVE_AS.create(window)); - registerAsGlobal(ActionFactory.SAVE_ALL.create(window)); - registerAsGlobal(ActionFactory.CLOSE.create(window)); - registerAsGlobal(ActionFactory.CLOSE_ALL.create(window)); - registerAsGlobal(ActionFactory.CLOSE_ALL_SAVED.create(window)); - registerAsGlobal(ActionFactory.ABOUT.create(window)); - registerAsGlobal(ActionFactory.QUIT.create(window)); - } - - private void registerAsGlobal(IAction action) { - getActionBarConfigurer().registerGlobalAction(action); - register(action); - } + coolBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); + coolBar.add(new GroupMarker(IWorkbenchActionConstants.GROUP_EDITOR)); + } + + @Override + protected void fillMenuBar(IMenuManager menuBar) { + super.fillMenuBar(menuBar); + + menuBar.add(fileMenu()); + menuBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); + menuBar.add(helpMenu()); + } + + private MenuManager helpMenu() { + MenuManager helpMenu = new MenuManager("&Help", + IWorkbenchActionConstants.M_HELP); + + helpMenu.add(getAction(ActionFactory.ABOUT.getId())); + + return helpMenu; + } + + private MenuManager fileMenu() { + MenuManager menu = new MenuManager("&File", "file_mnu"); + menu.add(new GroupMarker(IWorkbenchActionConstants.FILE_START)); + + menu.add(getAction(ActionFactory.CLOSE.getId())); + menu.add(getAction(ActionFactory.CLOSE_ALL.getId())); + + menu.add(new GroupMarker(IWorkbenchActionConstants.CLOSE_EXT)); + menu.add(new Separator()); + menu.add(getAction(ActionFactory.SAVE.getId())); + menu.add(getAction(ActionFactory.SAVE_ALL.getId())); + + menu.add(ContributionItemFactory.REOPEN_EDITORS + .create(getActionBarConfigurer().getWindowConfigurer() + .getWindow())); + menu.add(new GroupMarker(IWorkbenchActionConstants.MRU)); + menu.add(new Separator()); + menu.add(getAction(ActionFactory.QUIT.getId())); + return menu; + } + + @Override + protected void makeActions(IWorkbenchWindow window) { + super.makeActions(window); + + registerAsGlobal(ActionFactory.SAVE.create(window)); + registerAsGlobal(ActionFactory.SAVE_AS.create(window)); + registerAsGlobal(ActionFactory.SAVE_ALL.create(window)); + registerAsGlobal(ActionFactory.CLOSE.create(window)); + registerAsGlobal(ActionFactory.CLOSE_ALL.create(window)); + registerAsGlobal(ActionFactory.CLOSE_ALL_SAVED.create(window)); + registerAsGlobal(ActionFactory.ABOUT.create(window)); + registerAsGlobal(ActionFactory.QUIT.create(window)); + } + + private void registerAsGlobal(IAction action) { + getActionBarConfigurer().registerGlobalAction(action); + register(action); + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchAdvisor.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchAdvisor.java index 5a897172..3cca0c64 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchAdvisor.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchAdvisor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -17,21 +17,21 @@ public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor { - private static final String PERSPECTIVE_ID = "org.eclipselabs.tapiji.translator.perspective"; + private static final String PERSPECTIVE_ID = "org.eclipselabs.tapiji.translator.perspective"; - public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor( - IWorkbenchWindowConfigurer configurer) { - return new ApplicationWorkbenchWindowAdvisor(configurer); - } + public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor( + IWorkbenchWindowConfigurer configurer) { + return new ApplicationWorkbenchWindowAdvisor(configurer); + } - public String getInitialWindowPerspectiveId() { - return PERSPECTIVE_ID; - } + public String getInitialWindowPerspectiveId() { + return PERSPECTIVE_ID; + } - @Override - public void initialize(IWorkbenchConfigurer configurer) { - super.initialize(configurer); - configurer.setSaveAndRestore(true); - } + @Override + public void initialize(IWorkbenchConfigurer configurer) { + super.initialize(configurer); + configurer.setSaveAndRestore(true); + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchWindowAdvisor.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchWindowAdvisor.java index 93cb05f9..f8e6e2e8 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchWindowAdvisor.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/ApplicationWorkbenchWindowAdvisor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -34,156 +34,156 @@ public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor { - /** Workbench state **/ - private IWorkbenchWindow window; + /** Workbench state **/ + private IWorkbenchWindow window; + + /** System tray item / icon **/ + private TrayItem trayItem; + private Image trayImage; + + /** Command ids **/ + private final static String COMMAND_ABOUT_ID = "org.eclipse.ui.help.aboutAction"; + private final static String COMMAND_EXIT_ID = "org.eclipse.ui.file.exit"; + + public ApplicationWorkbenchWindowAdvisor( + IWorkbenchWindowConfigurer configurer) { + super(configurer); + } + + public ActionBarAdvisor createActionBarAdvisor( + IActionBarConfigurer configurer) { + return new ApplicationActionBarAdvisor(configurer); + } + + public void preWindowOpen() { + IWorkbenchWindowConfigurer configurer = getWindowConfigurer(); + configurer.setShowFastViewBars(true); + configurer.setShowCoolBar(true); + configurer.setShowStatusLine(true); + configurer.setInitialSize(new Point(1024, 768)); + + /** Init workspace and container project */ + try { + FileUtils.getProject(); + } catch (CoreException e) { + } + } - /** System tray item / icon **/ - private TrayItem trayItem; - private Image trayImage; + @Override + public void postWindowOpen() { + super.postWindowOpen(); + window = getWindowConfigurer().getWindow(); - /** Command ids **/ - private final static String COMMAND_ABOUT_ID = "org.eclipse.ui.help.aboutAction"; - private final static String COMMAND_EXIT_ID = "org.eclipse.ui.file.exit"; + /** Add the application into the system tray icon section **/ + trayItem = initTrayItem(window); - public ApplicationWorkbenchWindowAdvisor( - IWorkbenchWindowConfigurer configurer) { - super(configurer); - } + // If tray items are not supported by the operating system + if (trayItem != null) { - public ActionBarAdvisor createActionBarAdvisor( - IActionBarConfigurer configurer) { - return new ApplicationActionBarAdvisor(configurer); - } - - public void preWindowOpen() { - IWorkbenchWindowConfigurer configurer = getWindowConfigurer(); - configurer.setShowFastViewBars(true); - configurer.setShowCoolBar(true); - configurer.setShowStatusLine(true); - configurer.setInitialSize(new Point(1024, 768)); - - /** Init workspace and container project */ - try { - FileUtils.getProject(); - } catch (CoreException e) { + // minimize / maximize action + window.getShell().addShellListener(new ShellAdapter() { + public void shellIconified(ShellEvent e) { + window.getShell().setMinimized(true); + window.getShell().setVisible(false); } - } - - @Override - public void postWindowOpen() { - super.postWindowOpen(); - window = getWindowConfigurer().getWindow(); - - /** Add the application into the system tray icon section **/ - trayItem = initTrayItem(window); - - // If tray items are not supported by the operating system - if (trayItem != null) { - - // minimize / maximize action - window.getShell().addShellListener(new ShellAdapter() { - public void shellIconified(ShellEvent e) { - window.getShell().setMinimized(true); - window.getShell().setVisible(false); - } - }); - - trayItem.addListener(SWT.DefaultSelection, new Listener() { - public void handleEvent(Event event) { - Shell shell = window.getShell(); - if (!shell.isVisible() || window.getShell().getMinimized()) { - window.getShell().setMinimized(false); - shell.setVisible(true); - } - } - }); - - // Add actions menu - hookActionsMenu(); + }); + + trayItem.addListener(SWT.DefaultSelection, new Listener() { + public void handleEvent(Event event) { + Shell shell = window.getShell(); + if (!shell.isVisible() || window.getShell().getMinimized()) { + window.getShell().setMinimized(false); + shell.setVisible(true); + } } - } + }); - private void hookActionsMenu() { - trayItem.addListener(SWT.MenuDetect, new Listener() { - @Override - public void handleEvent(Event event) { - Menu menu = new Menu(window.getShell(), SWT.POP_UP); - - MenuItem about = new MenuItem(menu, SWT.None); - about.setText("&�ber"); - about.addListener(SWT.Selection, new Listener() { - - @Override - public void handleEvent(Event event) { - try { - IHandlerService handlerService = (IHandlerService) window - .getService(IHandlerService.class); - handlerService.executeCommand(COMMAND_ABOUT_ID, - null); - } catch (Exception e) { - e.printStackTrace(); - } - } - - }); - - MenuItem sep = new MenuItem(menu, SWT.SEPARATOR); - - // Add exit action - MenuItem exit = new MenuItem(menu, SWT.NONE); - exit.setText("Exit"); - exit.addListener(SWT.Selection, new Listener() { - @Override - public void handleEvent(Event event) { - // Perform a call to the exit command - IHandlerService handlerService = (IHandlerService) window - .getService(IHandlerService.class); - try { - handlerService - .executeCommand(COMMAND_EXIT_ID, null); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - - menu.setVisible(true); - } - }); + // Add actions menu + hookActionsMenu(); } + } + + private void hookActionsMenu() { + trayItem.addListener(SWT.MenuDetect, new Listener() { + @Override + public void handleEvent(Event event) { + Menu menu = new Menu(window.getShell(), SWT.POP_UP); + + MenuItem about = new MenuItem(menu, SWT.None); + about.setText("&�ber"); + about.addListener(SWT.Selection, new Listener() { + + @Override + public void handleEvent(Event event) { + try { + IHandlerService handlerService = (IHandlerService) window + .getService(IHandlerService.class); + handlerService.executeCommand(COMMAND_ABOUT_ID, + null); + } catch (Exception e) { + e.printStackTrace(); + } + } - private TrayItem initTrayItem(IWorkbenchWindow window) { - final Tray osTray = window.getShell().getDisplay().getSystemTray(); - TrayItem item = new TrayItem(osTray, SWT.None); + }); - trayImage = AbstractUIPlugin.imageDescriptorFromPlugin( - Activator.PLUGIN_ID, "/icons/TapiJI_32.png").createImage(); - item.setImage(trayImage); - item.setToolTipText("TapiJI - Translator"); + MenuItem sep = new MenuItem(menu, SWT.SEPARATOR); + + // Add exit action + MenuItem exit = new MenuItem(menu, SWT.NONE); + exit.setText("Exit"); + exit.addListener(SWT.Selection, new Listener() { + @Override + public void handleEvent(Event event) { + // Perform a call to the exit command + IHandlerService handlerService = (IHandlerService) window + .getService(IHandlerService.class); + try { + handlerService + .executeCommand(COMMAND_EXIT_ID, null); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); - return item; + menu.setVisible(true); + } + }); + } + + private TrayItem initTrayItem(IWorkbenchWindow window) { + final Tray osTray = window.getShell().getDisplay().getSystemTray(); + TrayItem item = new TrayItem(osTray, SWT.None); + + trayImage = AbstractUIPlugin.imageDescriptorFromPlugin( + Activator.PLUGIN_ID, "/icons/TapiJI_32.png").createImage(); + item.setImage(trayImage); + item.setToolTipText("TapiJI - Translator"); + + return item; + } + + @Override + public void dispose() { + try { + super.dispose(); + } catch (Exception e) { + e.printStackTrace(); } - @Override - public void dispose() { - try { - super.dispose(); - } catch (Exception e) { - e.printStackTrace(); - } - - try { - if (trayImage != null) - trayImage.dispose(); - if (trayItem != null) - trayItem.dispose(); - } catch (Exception e) { - e.printStackTrace(); - } + try { + if (trayImage != null) + trayImage.dispose(); + if (trayItem != null) + trayItem.dispose(); + } catch (Exception e) { + e.printStackTrace(); } + } - @Override - public void postWindowClose() { - super.postWindowClose(); - } + @Override + public void postWindowClose() { + super.postWindowClose(); + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Perspective.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Perspective.java index 910e91fe..63801013 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Perspective.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/Perspective.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -16,21 +16,21 @@ public class Perspective implements IPerspectiveFactory { - public void createInitialLayout(IPageLayout layout) { - layout.setEditorAreaVisible(true); - layout.setFixed(true); + public void createInitialLayout(IPageLayout layout) { + layout.setEditorAreaVisible(true); + layout.setFixed(true); - initEditorArea(layout); - initViewsArea(layout); - } + initEditorArea(layout); + initViewsArea(layout); + } - private void initViewsArea(IPageLayout layout) { - layout.addStandaloneView(GlossaryView.ID, false, IPageLayout.BOTTOM, - .6f, IPageLayout.ID_EDITOR_AREA); - } + private void initViewsArea(IPageLayout layout) { + layout.addStandaloneView(GlossaryView.ID, false, IPageLayout.BOTTOM, + .6f, IPageLayout.ID_EDITOR_AREA); + } - private void initEditorArea(IPageLayout layout) { + private void initEditorArea(IPageLayout layout) { - } + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/FileOpenAction.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/FileOpenAction.java index 3bfaa322..d6ee0227 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/FileOpenAction.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/FileOpenAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -23,53 +23,53 @@ import org.eclipselabs.tapiji.translator.utils.FileUtils; public class FileOpenAction extends Action implements - IWorkbenchWindowActionDelegate { + IWorkbenchWindowActionDelegate { - /** Editor ids **/ - public static final String RESOURCE_BUNDLE_EDITOR = "com.essiembre.rbe.eclipse.editor.ResourceBundleEditor"; + /** Editor ids **/ + public static final String RESOURCE_BUNDLE_EDITOR = "com.essiembre.rbe.eclipse.editor.ResourceBundleEditor"; - private IWorkbenchWindow window; + private IWorkbenchWindow window; - @Override - public void run(IAction action) { - String fileName = FileUtils.queryFileName(window.getShell(), - "Open Resource-Bundle", SWT.OPEN, - new String[] { "*.properties" }); - if (!FileUtils.isResourceBundle(fileName)) { - MessageDialog.openError(window.getShell(), - "Cannot open Resource-Bundle", - "The choosen file does not represent a Resource-Bundle!"); - return; - } + @Override + public void run(IAction action) { + String fileName = FileUtils.queryFileName(window.getShell(), + "Open Resource-Bundle", SWT.OPEN, + new String[] { "*.properties" }); + if (!FileUtils.isResourceBundle(fileName)) { + MessageDialog.openError(window.getShell(), + "Cannot open Resource-Bundle", + "The choosen file does not represent a Resource-Bundle!"); + return; + } - if (fileName != null) { - IWorkbenchPage page = window.getActivePage(); - try { - page.openEditor( - new FileEditorInput(FileUtils - .getResourceBundleRef(fileName)), - RESOURCE_BUNDLE_EDITOR); + if (fileName != null) { + IWorkbenchPage page = window.getActivePage(); + try { + page.openEditor( + new FileEditorInput(FileUtils + .getResourceBundleRef(fileName)), + RESOURCE_BUNDLE_EDITOR); - } catch (CoreException e) { - e.printStackTrace(); - } - } + } catch (CoreException e) { + e.printStackTrace(); + } } + } - @Override - public void selectionChanged(IAction action, ISelection selection) { - // TODO Auto-generated method stub + @Override + public void selectionChanged(IAction action, ISelection selection) { + // TODO Auto-generated method stub - } + } - @Override - public void dispose() { - window = null; - } + @Override + public void dispose() { + window = null; + } - @Override - public void init(IWorkbenchWindow window) { - this.window = window; - } + @Override + public void init(IWorkbenchWindow window) { + this.window = window; + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/NewGlossaryAction.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/NewGlossaryAction.java index ad78187d..e8ef19b2 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/NewGlossaryAction.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/NewGlossaryAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -25,50 +25,50 @@ public class NewGlossaryAction implements IWorkbenchWindowActionDelegate { - /** The workbench window */ - private IWorkbenchWindow window; + /** The workbench window */ + private IWorkbenchWindow window; - @Override - public void run(IAction action) { - String fileName = FileUtils.queryFileName(window.getShell(), - "New Glossary", SWT.SAVE, new String[] { "*.xml" }); + @Override + public void run(IAction action) { + String fileName = FileUtils.queryFileName(window.getShell(), + "New Glossary", SWT.SAVE, new String[] { "*.xml" }); - if (!fileName.endsWith(".xml")) { - if (fileName.endsWith(".")) - fileName += "xml"; - else - fileName += ".xml"; - } + if (!fileName.endsWith(".xml")) { + if (fileName.endsWith(".")) + fileName += "xml"; + else + fileName += ".xml"; + } - if (new File(fileName).exists()) { - String recallPattern = "The file \"{0}\" already exists. Do you want to replace this file with an empty translation glossary?"; - MessageFormat mf = new MessageFormat(recallPattern); + if (new File(fileName).exists()) { + String recallPattern = "The file \"{0}\" already exists. Do you want to replace this file with an empty translation glossary?"; + MessageFormat mf = new MessageFormat(recallPattern); - if (!MessageDialog.openQuestion(window.getShell(), - "File already exists!", - mf.format(new String[] { fileName }))) - return; - } + if (!MessageDialog.openQuestion(window.getShell(), + "File already exists!", + mf.format(new String[] { fileName }))) + return; + } - if (fileName != null) { - IWorkbenchPage page = window.getActivePage(); - GlossaryManager.newGlossary(new File(fileName)); - } + if (fileName != null) { + IWorkbenchPage page = window.getActivePage(); + GlossaryManager.newGlossary(new File(fileName)); } + } - @Override - public void selectionChanged(IAction action, ISelection selection) { + @Override + public void selectionChanged(IAction action, ISelection selection) { - } + } - @Override - public void dispose() { - this.window = null; - } + @Override + public void dispose() { + this.window = null; + } - @Override - public void init(IWorkbenchWindow window) { - this.window = window; - } + @Override + public void init(IWorkbenchWindow window) { + this.window = window; + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/OpenGlossaryAction.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/OpenGlossaryAction.java index 2ba8eb2d..403a4a4c 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/OpenGlossaryAction.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/actions/OpenGlossaryAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -24,40 +24,40 @@ public class OpenGlossaryAction implements IWorkbenchWindowActionDelegate { - /** The workbench window */ - private IWorkbenchWindow window; - - @Override - public void run(IAction action) { - String fileName = FileUtils.queryFileName(window.getShell(), - "Open Glossary", SWT.OPEN, new String[] { "*.xml" }); - if (!FileUtils.isGlossary(fileName)) { - MessageDialog.openError(window.getShell(), "Cannot open Glossary", - "The choosen file does not represent a Glossary!"); - return; - } - - if (fileName != null) { - IWorkbenchPage page = window.getActivePage(); - if (fileName != null) { - GlossaryManager.loadGlossary(new File(fileName)); - } - } + /** The workbench window */ + private IWorkbenchWindow window; + + @Override + public void run(IAction action) { + String fileName = FileUtils.queryFileName(window.getShell(), + "Open Glossary", SWT.OPEN, new String[] { "*.xml" }); + if (!FileUtils.isGlossary(fileName)) { + MessageDialog.openError(window.getShell(), "Cannot open Glossary", + "The choosen file does not represent a Glossary!"); + return; } - @Override - public void selectionChanged(IAction action, ISelection selection) { - + if (fileName != null) { + IWorkbenchPage page = window.getActivePage(); + if (fileName != null) { + GlossaryManager.loadGlossary(new File(fileName)); + } } + } - @Override - public void dispose() { - this.window = null; - } + @Override + public void selectionChanged(IAction action, ISelection selection) { - @Override - public void init(IWorkbenchWindow window) { - this.window = window; - } + } + + @Override + public void dispose() { + this.window = null; + } + + @Override + public void init(IWorkbenchWindow window) { + this.window = window; + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/GlossaryManager.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/GlossaryManager.java index e59ed45d..5c9a0111 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/GlossaryManager.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/GlossaryManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -26,68 +26,68 @@ public class GlossaryManager { - private Glossary glossary; - private File file; - private static List<ILoadGlossaryListener> loadGlossaryListeners = new ArrayList<ILoadGlossaryListener>(); + private Glossary glossary; + private File file; + private static List<ILoadGlossaryListener> loadGlossaryListeners = new ArrayList<ILoadGlossaryListener>(); - public GlossaryManager(File file, boolean overwrite) throws Exception { - this.file = file; + public GlossaryManager(File file, boolean overwrite) throws Exception { + this.file = file; - if (file.exists() && !overwrite) { - // load the existing glossary - glossary = new Glossary(); - JAXBContext context = JAXBContext.newInstance(glossary.getClass()); - Unmarshaller unmarshaller = context.createUnmarshaller(); - glossary = (Glossary) unmarshaller.unmarshal(file); - } else { - // Create a new glossary - glossary = new Glossary(); - saveGlossary(); - } + if (file.exists() && !overwrite) { + // load the existing glossary + glossary = new Glossary(); + JAXBContext context = JAXBContext.newInstance(glossary.getClass()); + Unmarshaller unmarshaller = context.createUnmarshaller(); + glossary = (Glossary) unmarshaller.unmarshal(file); + } else { + // Create a new glossary + glossary = new Glossary(); + saveGlossary(); } + } - public void saveGlossary() throws Exception { - JAXBContext context = JAXBContext.newInstance(glossary.getClass()); - Marshaller marshaller = context.createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-16"); + public void saveGlossary() throws Exception { + JAXBContext context = JAXBContext.newInstance(glossary.getClass()); + Marshaller marshaller = context.createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-16"); - OutputStream fout = new FileOutputStream(file.getAbsolutePath()); - OutputStream bout = new BufferedOutputStream(fout); - marshaller.marshal(glossary, new OutputStreamWriter(bout, "UTF-16")); - } + OutputStream fout = new FileOutputStream(file.getAbsolutePath()); + OutputStream bout = new BufferedOutputStream(fout); + marshaller.marshal(glossary, new OutputStreamWriter(bout, "UTF-16")); + } - public void setGlossary(Glossary glossary) { - this.glossary = glossary; - } + public void setGlossary(Glossary glossary) { + this.glossary = glossary; + } - public Glossary getGlossary() { - return glossary; - } + public Glossary getGlossary() { + return glossary; + } - public static void loadGlossary(File file) { - /* Inform the listeners */ - LoadGlossaryEvent event = new LoadGlossaryEvent(file); - for (ILoadGlossaryListener listener : loadGlossaryListeners) { - listener.glossaryLoaded(event); - } + public static void loadGlossary(File file) { + /* Inform the listeners */ + LoadGlossaryEvent event = new LoadGlossaryEvent(file); + for (ILoadGlossaryListener listener : loadGlossaryListeners) { + listener.glossaryLoaded(event); } + } - public static void registerLoadGlossaryListener( - ILoadGlossaryListener listener) { - loadGlossaryListeners.add(listener); - } + public static void registerLoadGlossaryListener( + ILoadGlossaryListener listener) { + loadGlossaryListeners.add(listener); + } - public static void unregisterLoadGlossaryListener( - ILoadGlossaryListener listener) { - loadGlossaryListeners.remove(listener); - } + public static void unregisterLoadGlossaryListener( + ILoadGlossaryListener listener) { + loadGlossaryListeners.remove(listener); + } - public static void newGlossary(File file) { - /* Inform the listeners */ - LoadGlossaryEvent event = new LoadGlossaryEvent(file); - event.setNewGlossary(true); - for (ILoadGlossaryListener listener : loadGlossaryListeners) { - listener.glossaryLoaded(event); - } + public static void newGlossary(File file) { + /* Inform the listeners */ + LoadGlossaryEvent event = new LoadGlossaryEvent(file); + event.setNewGlossary(true); + for (ILoadGlossaryListener listener : loadGlossaryListeners) { + listener.glossaryLoaded(event); } + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/ILoadGlossaryListener.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/ILoadGlossaryListener.java index e460f2d1..00b29729 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/ILoadGlossaryListener.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/ILoadGlossaryListener.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -12,6 +12,6 @@ public interface ILoadGlossaryListener { - void glossaryLoaded(LoadGlossaryEvent event); + void glossaryLoaded(LoadGlossaryEvent event); } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/LoadGlossaryEvent.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/LoadGlossaryEvent.java index 65cbd414..1df7ddb4 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/LoadGlossaryEvent.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/core/LoadGlossaryEvent.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -14,27 +14,27 @@ public class LoadGlossaryEvent { - private boolean newGlossary = false; - private File glossaryFile; + private boolean newGlossary = false; + private File glossaryFile; - public LoadGlossaryEvent(File glossaryFile) { - this.glossaryFile = glossaryFile; - } + public LoadGlossaryEvent(File glossaryFile) { + this.glossaryFile = glossaryFile; + } - public File getGlossaryFile() { - return glossaryFile; - } + public File getGlossaryFile() { + return glossaryFile; + } - public void setNewGlossary(boolean newGlossary) { - this.newGlossary = newGlossary; - } + public void setNewGlossary(boolean newGlossary) { + this.newGlossary = newGlossary; + } - public boolean isNewGlossary() { - return newGlossary; - } + public boolean isNewGlossary() { + return newGlossary; + } - public void setGlossaryFile(File glossaryFile) { - this.glossaryFile = glossaryFile; - } + public void setGlossaryFile(File glossaryFile) { + this.glossaryFile = glossaryFile; + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Glossary.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Glossary.java index d03b760e..a73203e4 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Glossary.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Glossary.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -24,62 +24,62 @@ @XmlAccessorType(XmlAccessType.FIELD) public class Glossary implements Serializable { - private static final long serialVersionUID = 2070750758712154134L; + private static final long serialVersionUID = 2070750758712154134L; - public Info info; + public Info info; - @XmlElementWrapper(name = "terms") - @XmlElement(name = "term") - public List<Term> terms; + @XmlElementWrapper(name = "terms") + @XmlElement(name = "term") + public List<Term> terms; - public Glossary() { - terms = new ArrayList<Term>(); - info = new Info(); - } + public Glossary() { + terms = new ArrayList<Term>(); + info = new Info(); + } + + public Term[] getAllTerms() { + return terms.toArray(new Term[terms.size()]); + } + + public int getIndexOfLocale(String referenceLocale) { + int i = 0; - public Term[] getAllTerms() { - return terms.toArray(new Term[terms.size()]); + for (String locale : info.translations) { + if (locale.equalsIgnoreCase(referenceLocale)) + return i; + i++; } - public int getIndexOfLocale(String referenceLocale) { - int i = 0; + return 0; + } - for (String locale : info.translations) { - if (locale.equalsIgnoreCase(referenceLocale)) - return i; - i++; - } + public void removeTerm(Term elem) { + for (Term term : terms) { + if (term == elem) { + terms.remove(term); + break; + } - return 0; + if (term.removeTerm(elem)) + break; } + } - public void removeTerm(Term elem) { - for (Term term : terms) { - if (term == elem) { - terms.remove(term); - break; - } - - if (term.removeTerm(elem)) - break; - } + public void addTerm(Term parentTerm, Term newTerm) { + if (parentTerm == null) { + this.terms.add(newTerm); + return; } - public void addTerm(Term parentTerm, Term newTerm) { - if (parentTerm == null) { - this.terms.add(newTerm); - return; - } - - for (Term term : terms) { - if (term == parentTerm) { - term.subTerms.add(newTerm); - break; - } - - if (term.addTerm(parentTerm, newTerm)) - break; - } + for (Term term : terms) { + if (term == parentTerm) { + term.subTerms.add(newTerm); + break; + } + + if (term.addTerm(parentTerm, newTerm)) + break; } + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Info.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Info.java index 24376dc0..a7494cfc 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Info.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Info.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -22,21 +22,21 @@ @XmlAccessorType(XmlAccessType.FIELD) public class Info implements Serializable { - private static final long serialVersionUID = 8607746669906026928L; + private static final long serialVersionUID = 8607746669906026928L; - @XmlElementWrapper(name = "locales") - @XmlElement(name = "locale") - public List<String> translations; + @XmlElementWrapper(name = "locales") + @XmlElement(name = "locale") + public List<String> translations; - public Info() { - this.translations = new ArrayList<String>(); + public Info() { + this.translations = new ArrayList<String>(); - // Add the default Locale - this.translations.add("Default"); - } + // Add the default Locale + this.translations.add("Default"); + } - public String[] getTranslations() { - return translations.toArray(new String[translations.size()]); - } + public String[] getTranslations() { + return translations.toArray(new String[translations.size()]); + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Term.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Term.java index afa6f3d3..c15ea0aa 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Term.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Term.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -23,94 +23,94 @@ @XmlAccessorType(XmlAccessType.FIELD) public class Term implements Serializable { - private static final long serialVersionUID = 7004998590181568026L; + private static final long serialVersionUID = 7004998590181568026L; - @XmlElementWrapper(name = "translations") - @XmlElement(name = "translation") - public List<Translation> translations; + @XmlElementWrapper(name = "translations") + @XmlElement(name = "translation") + public List<Translation> translations; - @XmlElementWrapper(name = "terms") - @XmlElement(name = "term") - public List<Term> subTerms; + @XmlElementWrapper(name = "terms") + @XmlElement(name = "term") + public List<Term> subTerms; - public Term parentTerm; + public Term parentTerm; - @XmlTransient - private Object info; + @XmlTransient + private Object info; - public Term() { - translations = new ArrayList<Translation>(); - subTerms = new ArrayList<Term>(); - parentTerm = null; - info = null; - } - - public void setInfo(Object info) { - this.info = info; - } - - public Object getInfo() { - return info; - } + public Term() { + translations = new ArrayList<Translation>(); + subTerms = new ArrayList<Term>(); + parentTerm = null; + info = null; + } - public Term[] getAllSubTerms() { - return subTerms.toArray(new Term[subTerms.size()]); - } + public void setInfo(Object info) { + this.info = info; + } - public Term getParentTerm() { - return parentTerm; - } + public Object getInfo() { + return info; + } - public boolean hasChildTerms() { - return subTerms != null && subTerms.size() > 0; - } + public Term[] getAllSubTerms() { + return subTerms.toArray(new Term[subTerms.size()]); + } - public Translation[] getAllTranslations() { - return translations.toArray(new Translation[translations.size()]); - } + public Term getParentTerm() { + return parentTerm; + } - public Translation getTranslation(String language) { - for (Translation translation : translations) { - if (translation.id.equalsIgnoreCase(language)) - return translation; - } + public boolean hasChildTerms() { + return subTerms != null && subTerms.size() > 0; + } - Translation newTranslation = new Translation(); - newTranslation.id = language; - translations.add(newTranslation); + public Translation[] getAllTranslations() { + return translations.toArray(new Translation[translations.size()]); + } - return newTranslation; + public Translation getTranslation(String language) { + for (Translation translation : translations) { + if (translation.id.equalsIgnoreCase(language)) + return translation; } - public boolean removeTerm(Term elem) { - boolean hasFound = false; - for (Term subTerm : subTerms) { - if (subTerm == elem) { - subTerms.remove(elem); - hasFound = true; - break; - } else { - hasFound = subTerm.removeTerm(elem); - if (hasFound) - break; - } - } - return hasFound; + Translation newTranslation = new Translation(); + newTranslation.id = language; + translations.add(newTranslation); + + return newTranslation; + } + + public boolean removeTerm(Term elem) { + boolean hasFound = false; + for (Term subTerm : subTerms) { + if (subTerm == elem) { + subTerms.remove(elem); + hasFound = true; + break; + } else { + hasFound = subTerm.removeTerm(elem); + if (hasFound) + break; + } } - - public boolean addTerm(Term parentTerm, Term newTerm) { - boolean hasFound = false; - for (Term subTerm : subTerms) { - if (subTerm == parentTerm) { - subTerms.add(newTerm); - hasFound = true; - break; - } else { - hasFound = subTerm.addTerm(parentTerm, newTerm); - if (hasFound) - break; - } - } - return hasFound; + return hasFound; + } + + public boolean addTerm(Term parentTerm, Term newTerm) { + boolean hasFound = false; + for (Term subTerm : subTerms) { + if (subTerm == parentTerm) { + subTerms.add(newTerm); + hasFound = true; + break; + } else { + hasFound = subTerm.addTerm(parentTerm, newTerm); + if (hasFound) + break; + } } + return hasFound; + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Translation.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Translation.java index b62184ea..d0ef8c59 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Translation.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/model/Translation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -20,15 +20,15 @@ @XmlType(name = "Translation") public class Translation implements Serializable { - private static final long serialVersionUID = 2033276999496196690L; + private static final long serialVersionUID = 2033276999496196690L; - public String id; + public String id; - public String value; + public String value; - public Translation() { - id = ""; - value = ""; - } + public Translation() { + id = ""; + value = ""; + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/tests/JaxBTest.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/tests/JaxBTest.java index 949a61bc..6ce52445 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/tests/JaxBTest.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/tests/JaxBTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -27,111 +27,111 @@ public class JaxBTest { - @Test - public void testModel() { - Glossary glossary = new Glossary(); - Info info = new Info(); - info.translations = new ArrayList<String>(); - info.translations.add("default"); - info.translations.add("de"); - info.translations.add("en"); - glossary.info = info; - glossary.terms = new ArrayList<Term>(); - - // Hello World - Term term = new Term(); - - Translation tranl1 = new Translation(); - tranl1.id = "default"; - tranl1.value = "Hallo Welt"; - - Translation tranl2 = new Translation(); - tranl2.id = "de"; - tranl2.value = "Hallo Welt"; - - Translation tranl3 = new Translation(); - tranl3.id = "en"; - tranl3.value = "Hello World!"; - - term.translations = new ArrayList<Translation>(); - term.translations.add(tranl1); - term.translations.add(tranl2); - term.translations.add(tranl3); - term.parentTerm = null; - - glossary.terms.add(term); - - // Hello World 2 - Term term2 = new Term(); - - Translation tranl12 = new Translation(); - tranl12.id = "default"; - tranl12.value = "Hallo Welt2"; - - Translation tranl22 = new Translation(); - tranl22.id = "de"; - tranl22.value = "Hallo Welt2"; - - Translation tranl32 = new Translation(); - tranl32.id = "en"; - tranl32.value = "Hello World2!"; - - term2.translations = new ArrayList<Translation>(); - term2.translations.add(tranl12); - term2.translations.add(tranl22); - term2.translations.add(tranl32); - // term2.parentTerm = term; - - term.subTerms = new ArrayList<Term>(); - term.subTerms.add(term2); - - // Hello World 3 - Term term3 = new Term(); - - Translation tranl13 = new Translation(); - tranl13.id = "default"; - tranl13.value = "Hallo Welt3"; - - Translation tranl23 = new Translation(); - tranl23.id = "de"; - tranl23.value = "Hallo Welt3"; - - Translation tranl33 = new Translation(); - tranl33.id = "en"; - tranl33.value = "Hello World3!"; - - term3.translations = new ArrayList<Translation>(); - term3.translations.add(tranl13); - term3.translations.add(tranl23); - term3.translations.add(tranl33); - term3.parentTerm = null; - - glossary.terms.add(term3); - - // Serialize model - try { - JAXBContext context = JAXBContext.newInstance(glossary.getClass()); - Marshaller marshaller = context.createMarshaller(); - marshaller.marshal(glossary, new FileWriter("C:\\test.xml")); - } catch (Exception e) { - e.printStackTrace(); - Assert.assertFalse(true); - } + @Test + public void testModel() { + Glossary glossary = new Glossary(); + Info info = new Info(); + info.translations = new ArrayList<String>(); + info.translations.add("default"); + info.translations.add("de"); + info.translations.add("en"); + glossary.info = info; + glossary.terms = new ArrayList<Term>(); + + // Hello World + Term term = new Term(); + + Translation tranl1 = new Translation(); + tranl1.id = "default"; + tranl1.value = "Hallo Welt"; + + Translation tranl2 = new Translation(); + tranl2.id = "de"; + tranl2.value = "Hallo Welt"; + + Translation tranl3 = new Translation(); + tranl3.id = "en"; + tranl3.value = "Hello World!"; + + term.translations = new ArrayList<Translation>(); + term.translations.add(tranl1); + term.translations.add(tranl2); + term.translations.add(tranl3); + term.parentTerm = null; + + glossary.terms.add(term); + + // Hello World 2 + Term term2 = new Term(); + + Translation tranl12 = new Translation(); + tranl12.id = "default"; + tranl12.value = "Hallo Welt2"; + + Translation tranl22 = new Translation(); + tranl22.id = "de"; + tranl22.value = "Hallo Welt2"; + + Translation tranl32 = new Translation(); + tranl32.id = "en"; + tranl32.value = "Hello World2!"; + + term2.translations = new ArrayList<Translation>(); + term2.translations.add(tranl12); + term2.translations.add(tranl22); + term2.translations.add(tranl32); + // term2.parentTerm = term; + + term.subTerms = new ArrayList<Term>(); + term.subTerms.add(term2); + + // Hello World 3 + Term term3 = new Term(); + + Translation tranl13 = new Translation(); + tranl13.id = "default"; + tranl13.value = "Hallo Welt3"; + + Translation tranl23 = new Translation(); + tranl23.id = "de"; + tranl23.value = "Hallo Welt3"; + + Translation tranl33 = new Translation(); + tranl33.id = "en"; + tranl33.value = "Hello World3!"; + + term3.translations = new ArrayList<Translation>(); + term3.translations.add(tranl13); + term3.translations.add(tranl23); + term3.translations.add(tranl33); + term3.parentTerm = null; + + glossary.terms.add(term3); + + // Serialize model + try { + JAXBContext context = JAXBContext.newInstance(glossary.getClass()); + Marshaller marshaller = context.createMarshaller(); + marshaller.marshal(glossary, new FileWriter("C:\\test.xml")); + } catch (Exception e) { + e.printStackTrace(); + Assert.assertFalse(true); } - - @Test - public void testReadModel() { - Glossary glossary = new Glossary(); - - try { - JAXBContext context = JAXBContext.newInstance(glossary.getClass()); - Unmarshaller unmarshaller = context.createUnmarshaller(); - glossary = (Glossary) unmarshaller.unmarshal(new File( - "C:\\test.xml")); - } catch (Exception e) { - e.printStackTrace(); - Assert.assertFalse(true); - } + } + + @Test + public void testReadModel() { + Glossary glossary = new Glossary(); + + try { + JAXBContext context = JAXBContext.newInstance(glossary.getClass()); + Unmarshaller unmarshaller = context.createUnmarshaller(); + glossary = (Glossary) unmarshaller.unmarshal(new File( + "C:\\test.xml")); + } catch (Exception e) { + e.printStackTrace(); + Assert.assertFalse(true); } + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FileUtils.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FileUtils.java index 5738a3a3..6d920013 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FileUtils.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FileUtils.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -25,125 +25,125 @@ public class FileUtils { - /** Token to replace in a regular expression with a bundle name. */ - private static final String TOKEN_BUNDLE_NAME = "BUNDLENAME"; - /** Token to replace in a regular expression with a file extension. */ - private static final String TOKEN_FILE_EXTENSION = "FILEEXTENSION"; - /** Regex to match a properties file. */ - private static final String PROPERTIES_FILE_REGEX = "^(" - + TOKEN_BUNDLE_NAME + ")" + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" - + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." + TOKEN_FILE_EXTENSION - + ")$"; - - /** The singleton instance of Workspace */ - private static IWorkspace workspace; - - /** Wrapper project for external file resources */ - private static IProject project; - - public static boolean isResourceBundle(String fileName) { - return fileName.toLowerCase().endsWith(".properties"); + /** Token to replace in a regular expression with a bundle name. */ + private static final String TOKEN_BUNDLE_NAME = "BUNDLENAME"; + /** Token to replace in a regular expression with a file extension. */ + private static final String TOKEN_FILE_EXTENSION = "FILEEXTENSION"; + /** Regex to match a properties file. */ + private static final String PROPERTIES_FILE_REGEX = "^(" + + TOKEN_BUNDLE_NAME + ")" + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" + + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." + TOKEN_FILE_EXTENSION + + ")$"; + + /** The singleton instance of Workspace */ + private static IWorkspace workspace; + + /** Wrapper project for external file resources */ + private static IProject project; + + public static boolean isResourceBundle(String fileName) { + return fileName.toLowerCase().endsWith(".properties"); + } + + public static boolean isGlossary(String fileName) { + return fileName.toLowerCase().endsWith(".xml"); + } + + public static IWorkspace getWorkspace() { + if (workspace == null) { + workspace = ResourcesPlugin.getWorkspace(); } - public static boolean isGlossary(String fileName) { - return fileName.toLowerCase().endsWith(".xml"); - } - - public static IWorkspace getWorkspace() { - if (workspace == null) { - workspace = ResourcesPlugin.getWorkspace(); - } - - return workspace; - } - - public static IProject getProject() throws CoreException { - if (project == null) { - project = getWorkspace().getRoot().getProject( - "ExternalResourceBundles"); - } - - if (!project.exists()) - project.create(null); - if (!project.isOpen()) - project.open(null); - - return project; - } + return workspace; + } - public static void prePareEditorInputs() { - IWorkspace workspace = getWorkspace(); + public static IProject getProject() throws CoreException { + if (project == null) { + project = getWorkspace().getRoot().getProject( + "ExternalResourceBundles"); } - public static IFile getResourceBundleRef(String location) - throws CoreException { - IPath path = new Path(location); - - /** - * Create all files of the Resource-Bundle within the project space and - * link them to the original file - */ - String regex = getPropertiesFileRegEx(path); - String projPathName = toProjectRelativePathName(path); - IFile file = getProject().getFile(projPathName); - file.createLink(path, IResource.REPLACE, null); - - File parentDir = new File(path.toFile().getParent()); - String[] files = parentDir.list(); - - for (String fn : files) { - File fo = new File(parentDir, fn); - if (!fo.isFile()) - continue; - - IPath newFilePath = new Path(fo.getAbsolutePath()); - if (fo.getName().matches(regex) - && !path.toFile().getName() - .equals(newFilePath.toFile().getName())) { - IFile newFile = project - .getFile(toProjectRelativePathName(newFilePath)); - newFile.createLink(newFilePath, IResource.REPLACE, null); - } - } - - return file; + if (!project.exists()) + project.create(null); + if (!project.isOpen()) + project.open(null); + + return project; + } + + public static void prePareEditorInputs() { + IWorkspace workspace = getWorkspace(); + } + + public static IFile getResourceBundleRef(String location) + throws CoreException { + IPath path = new Path(location); + + /** + * Create all files of the Resource-Bundle within the project space and + * link them to the original file + */ + String regex = getPropertiesFileRegEx(path); + String projPathName = toProjectRelativePathName(path); + IFile file = getProject().getFile(projPathName); + file.createLink(path, IResource.REPLACE, null); + + File parentDir = new File(path.toFile().getParent()); + String[] files = parentDir.list(); + + for (String fn : files) { + File fo = new File(parentDir, fn); + if (!fo.isFile()) + continue; + + IPath newFilePath = new Path(fo.getAbsolutePath()); + if (fo.getName().matches(regex) + && !path.toFile().getName() + .equals(newFilePath.toFile().getName())) { + IFile newFile = project + .getFile(toProjectRelativePathName(newFilePath)); + newFile.createLink(newFilePath, IResource.REPLACE, null); + } } - protected static String toProjectRelativePathName(IPath path) { - String projectRelativeName = ""; - - projectRelativeName = path.toString().replaceAll(":", ""); - projectRelativeName = projectRelativeName.replaceAll("/", "."); - - return projectRelativeName; - } - - protected static String getPropertiesFileRegEx(IPath file) { - String bundleName = getBundleName(file); - return PROPERTIES_FILE_REGEX - .replaceFirst(TOKEN_BUNDLE_NAME, bundleName).replaceFirst( - TOKEN_FILE_EXTENSION, file.getFileExtension()); - } - - public static String getBundleName(IPath file) { - String name = file.toFile().getName(); - String regex = "^(.*?)" //$NON-NLS-1$ - + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" - + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." - + file.getFileExtension() + ")$"; - return name.replaceFirst(regex, "$1"); - } - - public static String queryFileName(Shell shell, String title, - int dialogOptions, String[] endings) { - FileDialog dialog = new FileDialog(shell, dialogOptions); - dialog.setText(title); - dialog.setFilterExtensions(endings); - String path = dialog.open(); - - if (path != null && path.length() > 0) - return path; - return null; - } + return file; + } + + protected static String toProjectRelativePathName(IPath path) { + String projectRelativeName = ""; + + projectRelativeName = path.toString().replaceAll(":", ""); + projectRelativeName = projectRelativeName.replaceAll("/", "."); + + return projectRelativeName; + } + + protected static String getPropertiesFileRegEx(IPath file) { + String bundleName = getBundleName(file); + return PROPERTIES_FILE_REGEX + .replaceFirst(TOKEN_BUNDLE_NAME, bundleName).replaceFirst( + TOKEN_FILE_EXTENSION, file.getFileExtension()); + } + + public static String getBundleName(IPath file) { + String name = file.toFile().getName(); + String regex = "^(.*?)" //$NON-NLS-1$ + + "((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})" + + "|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?(\\." + + file.getFileExtension() + ")$"; + return name.replaceFirst(regex, "$1"); + } + + public static String queryFileName(Shell shell, String title, + int dialogOptions, String[] endings) { + FileDialog dialog = new FileDialog(shell, dialogOptions); + dialog.setText(title); + dialog.setFilterExtensions(endings); + String path = dialog.open(); + + if (path != null && path.length() > 0) + return path; + return null; + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FontUtils.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FontUtils.java index a2828e2b..14681af0 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FontUtils.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/utils/FontUtils.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -19,84 +19,84 @@ public class FontUtils { - /** - * Gets a system color. - * - * @param colorId - * SWT constant - * @return system color - */ - public static Color getSystemColor(int colorId) { - return Activator.getDefault().getWorkbench().getDisplay() - .getSystemColor(colorId); - } + /** + * Gets a system color. + * + * @param colorId + * SWT constant + * @return system color + */ + public static Color getSystemColor(int colorId) { + return Activator.getDefault().getWorkbench().getDisplay() + .getSystemColor(colorId); + } - /** - * Creates a font by altering the font associated with the given control and - * applying the provided style (size is unaffected). - * - * @param control - * control we base our font data on - * @param style - * style to apply to the new font - * @return newly created font - */ - public static Font createFont(Control control, int style) { - // TODO consider dropping in favor of control-less version? - return createFont(control, style, 0); - } + /** + * Creates a font by altering the font associated with the given control and + * applying the provided style (size is unaffected). + * + * @param control + * control we base our font data on + * @param style + * style to apply to the new font + * @return newly created font + */ + public static Font createFont(Control control, int style) { + // TODO consider dropping in favor of control-less version? + return createFont(control, style, 0); + } - /** - * Creates a font by altering the font associated with the given control and - * applying the provided style and relative size. - * - * @param control - * control we base our font data on - * @param style - * style to apply to the new font - * @param relSize - * size to add or remove from the control size - * @return newly created font - */ - public static Font createFont(Control control, int style, int relSize) { - // TODO consider dropping in favor of control-less version? - FontData[] fontData = control.getFont().getFontData(); - for (int i = 0; i < fontData.length; i++) { - fontData[i].setHeight(fontData[i].getHeight() + relSize); - fontData[i].setStyle(style); - } - return new Font(control.getDisplay(), fontData); + /** + * Creates a font by altering the font associated with the given control and + * applying the provided style and relative size. + * + * @param control + * control we base our font data on + * @param style + * style to apply to the new font + * @param relSize + * size to add or remove from the control size + * @return newly created font + */ + public static Font createFont(Control control, int style, int relSize) { + // TODO consider dropping in favor of control-less version? + FontData[] fontData = control.getFont().getFontData(); + for (int i = 0; i < fontData.length; i++) { + fontData[i].setHeight(fontData[i].getHeight() + relSize); + fontData[i].setStyle(style); } + return new Font(control.getDisplay(), fontData); + } - /** - * Creates a font by altering the system font and applying the provided - * style and relative size. - * - * @param style - * style to apply to the new font - * @return newly created font - */ - public static Font createFont(int style) { - return createFont(style, 0); - } + /** + * Creates a font by altering the system font and applying the provided + * style and relative size. + * + * @param style + * style to apply to the new font + * @return newly created font + */ + public static Font createFont(int style) { + return createFont(style, 0); + } - /** - * Creates a font by altering the system font and applying the provided - * style and relative size. - * - * @param style - * style to apply to the new font - * @param relSize - * size to add or remove from the control size - * @return newly created font - */ - public static Font createFont(int style, int relSize) { - Display display = Activator.getDefault().getWorkbench().getDisplay(); - FontData[] fontData = display.getSystemFont().getFontData(); - for (int i = 0; i < fontData.length; i++) { - fontData[i].setHeight(fontData[i].getHeight() + relSize); - fontData[i].setStyle(style); - } - return new Font(display, fontData); + /** + * Creates a font by altering the system font and applying the provided + * style and relative size. + * + * @param style + * style to apply to the new font + * @param relSize + * size to add or remove from the control size + * @return newly created font + */ + public static Font createFont(int style, int relSize) { + Display display = Activator.getDefault().getWorkbench().getDisplay(); + FontData[] fontData = display.getSystemFont().getFontData(); + for (int i = 0; i < fontData.length; i++) { + fontData[i].setHeight(fontData[i].getHeight() + relSize); + fontData[i].setStyle(style); } + return new Font(display, fontData); + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/GlossaryView.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/GlossaryView.java index b89cd208..0811f28e 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/GlossaryView.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/GlossaryView.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -55,689 +55,689 @@ public class GlossaryView extends ViewPart implements ILoadGlossaryListener { + /** + * The ID of the view as specified by the extension. + */ + public static final String ID = "org.eclipselabs.tapiji.translator.views.GlossaryView"; + + /*** Primary view controls ***/ + private GlossaryWidget treeViewer; + private Scale fuzzyScaler; + private Label lblScale; + private Text filter; + + /*** ACTIONS ***/ + private GlossaryEntryMenuContribution glossaryEditContribution; + private MenuManager referenceMenu; + private MenuManager displayMenu; + private MenuManager showMenu; + private Action newEntry; + private Action enableFuzzyMatching; + private Action editable; + private Action newTranslation; + private Action deleteTranslation; + private Action showAll; + private Action showSelectiveContent; + private List<Action> referenceActions; + private List<Action> displayActions; + + /*** Parent component ***/ + private Composite parent; + + /*** View state ***/ + private IMemento memento; + private GlossaryViewState viewState; + private GlossaryManager glossary; + + /** + * The constructor. + */ + public GlossaryView() { /** - * The ID of the view as specified by the extension. + * Register the view for being informed each time a new glossary is + * loaded into the translator */ - public static final String ID = "org.eclipselabs.tapiji.translator.views.GlossaryView"; - - /*** Primary view controls ***/ - private GlossaryWidget treeViewer; - private Scale fuzzyScaler; - private Label lblScale; - private Text filter; - - /*** ACTIONS ***/ - private GlossaryEntryMenuContribution glossaryEditContribution; - private MenuManager referenceMenu; - private MenuManager displayMenu; - private MenuManager showMenu; - private Action newEntry; - private Action enableFuzzyMatching; - private Action editable; - private Action newTranslation; - private Action deleteTranslation; - private Action showAll; - private Action showSelectiveContent; - private List<Action> referenceActions; - private List<Action> displayActions; - - /*** Parent component ***/ - private Composite parent; - - /*** View state ***/ - private IMemento memento; - private GlossaryViewState viewState; - private GlossaryManager glossary; + GlossaryManager.registerLoadGlossaryListener(this); + } + + /** + * This is a callback that will allow us to create the viewer and initialize + * it. + */ + public void createPartControl(Composite parent) { + this.parent = parent; + + initLayout(parent); + initSearchBar(parent); + initMessagesTree(parent); + makeActions(); + hookContextMenu(); + contributeToActionBars(); + initListener(parent); + } + + protected void initListener(Composite parent) { + filter.addModifyListener(new ModifyListener() { + + @Override + public void modifyText(ModifyEvent e) { + if (glossary != null && glossary.getGlossary() != null) + treeViewer.setSearchString(filter.getText()); + } + }); + } + + protected void initLayout(Composite parent) { + GridLayout mainLayout = new GridLayout(); + mainLayout.numColumns = 1; + parent.setLayout(mainLayout); + + } + + protected void initSearchBar(Composite parent) { + // Construct a new parent container + Composite parentComp = new Composite(parent, SWT.BORDER); + parentComp.setLayout(new GridLayout(4, false)); + parentComp + .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); + + Label lblSearchText = new Label(parentComp, SWT.NONE); + lblSearchText.setText("Search expression:"); + + // define the grid data for the layout + GridData gridData = new GridData(); + gridData.horizontalAlignment = SWT.FILL; + gridData.grabExcessHorizontalSpace = false; + gridData.horizontalSpan = 1; + lblSearchText.setLayoutData(gridData); + + filter = new Text(parentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); + if (viewState != null && viewState.getSearchString() != null) { + if (viewState.getSearchString().length() > 1 + && viewState.getSearchString().startsWith("*") + && viewState.getSearchString().endsWith("*")) + filter.setText(viewState.getSearchString().substring(1) + .substring(0, viewState.getSearchString().length() - 2)); + else + filter.setText(viewState.getSearchString()); - /** - * The constructor. - */ - public GlossaryView() { - /** - * Register the view for being informed each time a new glossary is - * loaded into the translator - */ - GlossaryManager.registerLoadGlossaryListener(this); } - - /** - * This is a callback that will allow us to create the viewer and initialize - * it. - */ - public void createPartControl(Composite parent) { - this.parent = parent; - - initLayout(parent); - initSearchBar(parent); - initMessagesTree(parent); - makeActions(); - hookContextMenu(); - contributeToActionBars(); - initListener(parent); + GridData gridDatas = new GridData(); + gridDatas.horizontalAlignment = SWT.FILL; + gridDatas.grabExcessHorizontalSpace = true; + gridDatas.horizontalSpan = 3; + filter.setLayoutData(gridDatas); + + lblScale = new Label(parentComp, SWT.None); + lblScale.setText("\nPrecision:"); + GridData gdScaler = new GridData(); + gdScaler.verticalAlignment = SWT.CENTER; + gdScaler.grabExcessVerticalSpace = true; + gdScaler.horizontalSpan = 1; + lblScale.setLayoutData(gdScaler); + + // Add a scale for specification of fuzzy Matching precision + fuzzyScaler = new Scale(parentComp, SWT.None); + fuzzyScaler.setMaximum(100); + fuzzyScaler.setMinimum(0); + fuzzyScaler.setIncrement(1); + fuzzyScaler.setPageIncrement(5); + fuzzyScaler + .setSelection(Math.round((treeViewer != null ? treeViewer + .getMatchingPrecision() : viewState + .getMatchingPrecision()) * 100.f)); + fuzzyScaler.addListener(SWT.Selection, new Listener() { + public void handleEvent(Event event) { + float val = 1f - (Float.parseFloat((fuzzyScaler.getMaximum() + - fuzzyScaler.getSelection() + fuzzyScaler.getMinimum()) + + "") / 100.f); + treeViewer.setMatchingPrecision(val); + } + }); + fuzzyScaler.setSize(100, 10); + + GridData gdScalers = new GridData(); + gdScalers.verticalAlignment = SWT.BEGINNING; + gdScalers.horizontalAlignment = SWT.FILL; + gdScalers.horizontalSpan = 3; + fuzzyScaler.setLayoutData(gdScalers); + refreshSearchbarState(); + } + + protected void refreshSearchbarState() { + lblScale.setVisible(treeViewer != null ? treeViewer + .isFuzzyMatchingEnabled() : viewState.isFuzzyMatchingEnabled()); + fuzzyScaler.setVisible(treeViewer != null ? treeViewer + .isFuzzyMatchingEnabled() : viewState.isFuzzyMatchingEnabled()); + if (treeViewer != null ? treeViewer.isFuzzyMatchingEnabled() + : viewState.isFuzzyMatchingEnabled()) { + ((GridData) lblScale.getLayoutData()).heightHint = 40; + ((GridData) fuzzyScaler.getLayoutData()).heightHint = 40; + } else { + ((GridData) lblScale.getLayoutData()).heightHint = 0; + ((GridData) fuzzyScaler.getLayoutData()).heightHint = 0; } - protected void initListener(Composite parent) { - filter.addModifyListener(new ModifyListener() { - - @Override - public void modifyText(ModifyEvent e) { - if (glossary != null && glossary.getGlossary() != null) - treeViewer.setSearchString(filter.getText()); - } - }); + lblScale.getParent().layout(); + lblScale.getParent().getParent().layout(); + } + + protected void initMessagesTree(Composite parent) { + // Unregister the label provider as selection listener + if (treeViewer != null + && treeViewer.getViewer() != null + && treeViewer.getViewer().getLabelProvider() != null + && treeViewer.getViewer().getLabelProvider() instanceof GlossaryLabelProvider) + getSite() + .getWorkbenchWindow() + .getSelectionService() + .removeSelectionListener( + ((GlossaryLabelProvider) treeViewer.getViewer() + .getLabelProvider())); + + treeViewer = new GlossaryWidget(getSite(), parent, SWT.NONE, + glossary != null ? glossary : null, + viewState != null ? viewState.getReferenceLanguage() : null, + viewState != null ? viewState.getDisplayLanguages() : null); + + // Register the label provider as selection listener + if (treeViewer.getViewer() != null + && treeViewer.getViewer().getLabelProvider() != null + && treeViewer.getViewer().getLabelProvider() instanceof GlossaryLabelProvider) + getSite() + .getWorkbenchWindow() + .getSelectionService() + .addSelectionListener( + ((GlossaryLabelProvider) treeViewer.getViewer() + .getLabelProvider())); + if (treeViewer != null && this.glossary != null + && this.glossary.getGlossary() != null) { + if (viewState != null && viewState.getSortings() != null) + treeViewer.setSortInfo(viewState.getSortings()); + + treeViewer.enableFuzzyMatching(viewState.isFuzzyMatchingEnabled()); + treeViewer.bindContentToSelection(viewState + .isSelectiveViewEnabled()); + treeViewer.setMatchingPrecision(viewState.getMatchingPrecision()); + treeViewer.setEditable(viewState.isEditable()); + + if (viewState.getSearchString() != null) + treeViewer.setSearchString(viewState.getSearchString()); } - protected void initLayout(Composite parent) { - GridLayout mainLayout = new GridLayout(); - mainLayout.numColumns = 1; - parent.setLayout(mainLayout); - + // define the grid data for the layout + GridData gridData = new GridData(); + gridData.horizontalAlignment = SWT.FILL; + gridData.verticalAlignment = SWT.FILL; + gridData.grabExcessHorizontalSpace = true; + gridData.grabExcessVerticalSpace = true; + treeViewer.setLayoutData(gridData); + } + + /** + * Passing the focus request to the viewer's control. + */ + public void setFocus() { + treeViewer.setFocus(); + } + + protected void redrawTreeViewer() { + parent.setRedraw(false); + treeViewer.dispose(); + try { + initMessagesTree(parent); + makeActions(); + contributeToActionBars(); + hookContextMenu(); + } catch (Exception e) { + e.printStackTrace(); } - - protected void initSearchBar(Composite parent) { - // Construct a new parent container - Composite parentComp = new Composite(parent, SWT.BORDER); - parentComp.setLayout(new GridLayout(4, false)); - parentComp - .setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); - - Label lblSearchText = new Label(parentComp, SWT.NONE); - lblSearchText.setText("Search expression:"); - - // define the grid data for the layout - GridData gridData = new GridData(); - gridData.horizontalAlignment = SWT.FILL; - gridData.grabExcessHorizontalSpace = false; - gridData.horizontalSpan = 1; - lblSearchText.setLayoutData(gridData); - - filter = new Text(parentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); - if (viewState != null && viewState.getSearchString() != null) { - if (viewState.getSearchString().length() > 1 - && viewState.getSearchString().startsWith("*") - && viewState.getSearchString().endsWith("*")) - filter.setText(viewState.getSearchString().substring(1) - .substring(0, viewState.getSearchString().length() - 2)); - else - filter.setText(viewState.getSearchString()); - - } - GridData gridDatas = new GridData(); - gridDatas.horizontalAlignment = SWT.FILL; - gridDatas.grabExcessHorizontalSpace = true; - gridDatas.horizontalSpan = 3; - filter.setLayoutData(gridDatas); - - lblScale = new Label(parentComp, SWT.None); - lblScale.setText("\nPrecision:"); - GridData gdScaler = new GridData(); - gdScaler.verticalAlignment = SWT.CENTER; - gdScaler.grabExcessVerticalSpace = true; - gdScaler.horizontalSpan = 1; - lblScale.setLayoutData(gdScaler); - - // Add a scale for specification of fuzzy Matching precision - fuzzyScaler = new Scale(parentComp, SWT.None); - fuzzyScaler.setMaximum(100); - fuzzyScaler.setMinimum(0); - fuzzyScaler.setIncrement(1); - fuzzyScaler.setPageIncrement(5); - fuzzyScaler - .setSelection(Math.round((treeViewer != null ? treeViewer - .getMatchingPrecision() : viewState - .getMatchingPrecision()) * 100.f)); - fuzzyScaler.addListener(SWT.Selection, new Listener() { - public void handleEvent(Event event) { - float val = 1f - (Float.parseFloat((fuzzyScaler.getMaximum() - - fuzzyScaler.getSelection() + fuzzyScaler.getMinimum()) - + "") / 100.f); - treeViewer.setMatchingPrecision(val); - } - }); - fuzzyScaler.setSize(100, 10); - - GridData gdScalers = new GridData(); - gdScalers.verticalAlignment = SWT.BEGINNING; - gdScalers.horizontalAlignment = SWT.FILL; - gdScalers.horizontalSpan = 3; - fuzzyScaler.setLayoutData(gdScalers); + parent.setRedraw(true); + parent.layout(true); + treeViewer.layout(true); + refreshSearchbarState(); + } + + /*** ACTIONS ***/ + private void makeActions() { + newEntry = new Action() { + @Override + public void run() { + super.run(); + } + }; + newEntry.setText("New term ..."); + newEntry.setDescription("Creates a new glossary entry"); + newEntry.setToolTipText("Creates a new glossary entry"); + + enableFuzzyMatching = new Action() { + public void run() { + super.run(); + treeViewer.enableFuzzyMatching(!treeViewer + .isFuzzyMatchingEnabled()); + viewState.setFuzzyMatchingEnabled(treeViewer + .isFuzzyMatchingEnabled()); refreshSearchbarState(); - } - - protected void refreshSearchbarState() { - lblScale.setVisible(treeViewer != null ? treeViewer - .isFuzzyMatchingEnabled() : viewState.isFuzzyMatchingEnabled()); - fuzzyScaler.setVisible(treeViewer != null ? treeViewer - .isFuzzyMatchingEnabled() : viewState.isFuzzyMatchingEnabled()); - if (treeViewer != null ? treeViewer.isFuzzyMatchingEnabled() - : viewState.isFuzzyMatchingEnabled()) { - ((GridData) lblScale.getLayoutData()).heightHint = 40; - ((GridData) fuzzyScaler.getLayoutData()).heightHint = 40; - } else { - ((GridData) lblScale.getLayoutData()).heightHint = 0; - ((GridData) fuzzyScaler.getLayoutData()).heightHint = 0; + } + }; + enableFuzzyMatching.setText("Fuzzy-Matching"); + enableFuzzyMatching + .setDescription("Enables Fuzzy matching for searching Resource-Bundle entries."); + enableFuzzyMatching.setChecked(viewState.isFuzzyMatchingEnabled()); + enableFuzzyMatching + .setToolTipText(enableFuzzyMatching.getDescription()); + + editable = new Action() { + public void run() { + super.run(); + treeViewer.setEditable(!treeViewer.isEditable()); + } + }; + editable.setText("Editable"); + editable.setDescription("Allows you to edit Resource-Bundle entries."); + editable.setChecked(viewState.isEditable()); + editable.setToolTipText(editable.getDescription()); + + /** New Translation */ + newTranslation = new Action("New Translation ...") { + public void run() { + /* + * Construct a list of all Locales except Locales that are + * already part of the translation glossary + */ + if (glossary == null || glossary.getGlossary() == null) + return; + + List<Locale> allLocales = new ArrayList<Locale>(); + List<Locale> locales = new ArrayList<Locale>(); + for (String l : glossary.getGlossary().info.getTranslations()) { + String[] locDef = l.split("_"); + Locale locale = locDef.length < 3 ? (locDef.length < 2 ? new Locale( + locDef[0]) : new Locale(locDef[0], locDef[1])) + : new Locale(locDef[0], locDef[1], locDef[2]); + locales.add(locale); } - lblScale.getParent().layout(); - lblScale.getParent().getParent().layout(); - } - - protected void initMessagesTree(Composite parent) { - // Unregister the label provider as selection listener - if (treeViewer != null - && treeViewer.getViewer() != null - && treeViewer.getViewer().getLabelProvider() != null - && treeViewer.getViewer().getLabelProvider() instanceof GlossaryLabelProvider) - getSite() - .getWorkbenchWindow() - .getSelectionService() - .removeSelectionListener( - ((GlossaryLabelProvider) treeViewer.getViewer() - .getLabelProvider())); - - treeViewer = new GlossaryWidget(getSite(), parent, SWT.NONE, - glossary != null ? glossary : null, - viewState != null ? viewState.getReferenceLanguage() : null, - viewState != null ? viewState.getDisplayLanguages() : null); - - // Register the label provider as selection listener - if (treeViewer.getViewer() != null - && treeViewer.getViewer().getLabelProvider() != null - && treeViewer.getViewer().getLabelProvider() instanceof GlossaryLabelProvider) - getSite() - .getWorkbenchWindow() - .getSelectionService() - .addSelectionListener( - ((GlossaryLabelProvider) treeViewer.getViewer() - .getLabelProvider())); - if (treeViewer != null && this.glossary != null - && this.glossary.getGlossary() != null) { - if (viewState != null && viewState.getSortings() != null) - treeViewer.setSortInfo(viewState.getSortings()); - - treeViewer.enableFuzzyMatching(viewState.isFuzzyMatchingEnabled()); - treeViewer.bindContentToSelection(viewState - .isSelectiveViewEnabled()); - treeViewer.setMatchingPrecision(viewState.getMatchingPrecision()); - treeViewer.setEditable(viewState.isEditable()); - - if (viewState.getSearchString() != null) - treeViewer.setSearchString(viewState.getSearchString()); + for (Locale l : Locale.getAvailableLocales()) { + if (!locales.contains(l)) + allLocales.add(l); } - // define the grid data for the layout - GridData gridData = new GridData(); - gridData.horizontalAlignment = SWT.FILL; - gridData.verticalAlignment = SWT.FILL; - gridData.grabExcessHorizontalSpace = true; - gridData.grabExcessVerticalSpace = true; - treeViewer.setLayoutData(gridData); - } - - /** - * Passing the focus request to the viewer's control. - */ - public void setFocus() { - treeViewer.setFocus(); - } + /* + * Ask the user for the set of locales that need to be added to + * the translation glossary + */ + Collections.sort(allLocales, new Comparator<Locale>() { + @Override + public int compare(Locale o1, Locale o2) { + return o1.getDisplayName().compareTo( + o2.getDisplayName()); + } + }); + ListSelectionDialog dlg = new ListSelectionDialog(getSite() + .getShell(), allLocales, new LocaleContentProvider(), + new LocaleLabelProvider(), "Select the Translation:"); + dlg.setTitle("Translation Selection"); + if (dlg.open() == dlg.OK) { + Object[] addLocales = (Object[]) dlg.getResult(); + for (Object addLoc : addLocales) { + Locale locale = (Locale) addLoc; + String strLocale = locale.toString(); + glossary.getGlossary().info.translations.add(strLocale); + } + + try { + glossary.saveGlossary(); + displayActions = null; + referenceActions = null; + viewState.setDisplayLanguages(null); + redrawTreeViewer(); + } catch (Exception e) { + e.printStackTrace(); + } + } + }; + }; + newTranslation.setDescription("Adds a new Locale for translation."); + newTranslation.setToolTipText(newTranslation.getDescription()); + + /** Delete Translation */ + deleteTranslation = new Action("Delete Translation ...") { + public void run() { + /* + * Construct a list of type locale from all existing + * translations + */ + if (glossary == null || glossary.getGlossary() == null) + return; + + String referenceLang = glossary.getGlossary().info + .getTranslations()[0]; + if (viewState != null + && viewState.getReferenceLanguage() != null) + referenceLang = viewState.getReferenceLanguage(); + + List<Locale> locales = new ArrayList<Locale>(); + List<String> strLoc = new ArrayList<String>(); + for (String l : glossary.getGlossary().info.getTranslations()) { + if (l.equalsIgnoreCase(referenceLang)) + continue; + String[] locDef = l.split("_"); + Locale locale = locDef.length < 3 ? (locDef.length < 2 ? new Locale( + locDef[0]) : new Locale(locDef[0], locDef[1])) + : new Locale(locDef[0], locDef[1], locDef[2]); + locales.add(locale); + strLoc.add(l); + } - protected void redrawTreeViewer() { - parent.setRedraw(false); - treeViewer.dispose(); - try { - initMessagesTree(parent); - makeActions(); - contributeToActionBars(); - hookContextMenu(); - } catch (Exception e) { + /* + * Ask the user for the set of locales that need to be removed + * from the translation glossary + */ + ListSelectionDialog dlg = new ListSelectionDialog(getSite() + .getShell(), locales, new LocaleContentProvider(), + new LocaleLabelProvider(), "Select the Translation:"); + dlg.setTitle("Translation Selection"); + if (dlg.open() == ListSelectionDialog.OK) { + Object[] delLocales = (Object[]) dlg.getResult(); + List<String> toRemove = new ArrayList<String>(); + for (Object delLoc : delLocales) { + toRemove.add(strLoc.get(locales.indexOf(delLoc))); + } + glossary.getGlossary().info.translations + .removeAll(toRemove); + try { + glossary.saveGlossary(); + displayActions = null; + referenceActions = null; + viewState.setDisplayLanguages(null); + redrawTreeViewer(); + } catch (Exception e) { e.printStackTrace(); + } } - parent.setRedraw(true); - parent.layout(true); - treeViewer.layout(true); - refreshSearchbarState(); + }; + }; + deleteTranslation + .setDescription("Deletes a specific Locale from the translation glossary."); + deleteTranslation.setToolTipText(deleteTranslation.getDescription()); + } + + private void contributeToActionBars() { + IActionBars bars = getViewSite().getActionBars(); + fillLocalPullDown(bars.getMenuManager()); + fillLocalToolBar(bars.getToolBarManager()); + } + + private void fillLocalPullDown(IMenuManager manager) { + manager.removeAll(); + + if (this.glossary != null && this.glossary.getGlossary() != null) { + glossaryEditContribution = new GlossaryEntryMenuContribution( + treeViewer, !treeViewer.getViewer().getSelection() + .isEmpty()); + manager.add(this.glossaryEditContribution); + manager.add(new Separator()); } - /*** ACTIONS ***/ - private void makeActions() { - newEntry = new Action() { - @Override - public void run() { - super.run(); - } - }; - newEntry.setText("New term ..."); - newEntry.setDescription("Creates a new glossary entry"); - newEntry.setToolTipText("Creates a new glossary entry"); + manager.add(enableFuzzyMatching); + manager.add(editable); - enableFuzzyMatching = new Action() { - public void run() { - super.run(); - treeViewer.enableFuzzyMatching(!treeViewer - .isFuzzyMatchingEnabled()); - viewState.setFuzzyMatchingEnabled(treeViewer - .isFuzzyMatchingEnabled()); - refreshSearchbarState(); - } - }; - enableFuzzyMatching.setText("Fuzzy-Matching"); - enableFuzzyMatching - .setDescription("Enables Fuzzy matching for searching Resource-Bundle entries."); - enableFuzzyMatching.setChecked(viewState.isFuzzyMatchingEnabled()); - enableFuzzyMatching - .setToolTipText(enableFuzzyMatching.getDescription()); - - editable = new Action() { - public void run() { - super.run(); - treeViewer.setEditable(!treeViewer.isEditable()); - } - }; - editable.setText("Editable"); - editable.setDescription("Allows you to edit Resource-Bundle entries."); - editable.setChecked(viewState.isEditable()); - editable.setToolTipText(editable.getDescription()); - - /** New Translation */ - newTranslation = new Action("New Translation ...") { - public void run() { - /* - * Construct a list of all Locales except Locales that are - * already part of the translation glossary - */ - if (glossary == null || glossary.getGlossary() == null) - return; - - List<Locale> allLocales = new ArrayList<Locale>(); - List<Locale> locales = new ArrayList<Locale>(); - for (String l : glossary.getGlossary().info.getTranslations()) { - String[] locDef = l.split("_"); - Locale locale = locDef.length < 3 ? (locDef.length < 2 ? new Locale( - locDef[0]) : new Locale(locDef[0], locDef[1])) - : new Locale(locDef[0], locDef[1], locDef[2]); - locales.add(locale); - } - - for (Locale l : Locale.getAvailableLocales()) { - if (!locales.contains(l)) - allLocales.add(l); - } - - /* - * Ask the user for the set of locales that need to be added to - * the translation glossary - */ - Collections.sort(allLocales, new Comparator<Locale>() { - @Override - public int compare(Locale o1, Locale o2) { - return o1.getDisplayName().compareTo( - o2.getDisplayName()); - } - }); - ListSelectionDialog dlg = new ListSelectionDialog(getSite() - .getShell(), allLocales, new LocaleContentProvider(), - new LocaleLabelProvider(), "Select the Translation:"); - dlg.setTitle("Translation Selection"); - if (dlg.open() == dlg.OK) { - Object[] addLocales = (Object[]) dlg.getResult(); - for (Object addLoc : addLocales) { - Locale locale = (Locale) addLoc; - String strLocale = locale.toString(); - glossary.getGlossary().info.translations.add(strLocale); - } - - try { - glossary.saveGlossary(); - displayActions = null; - referenceActions = null; - viewState.setDisplayLanguages(null); - redrawTreeViewer(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }; - }; - newTranslation.setDescription("Adds a new Locale for translation."); - newTranslation.setToolTipText(newTranslation.getDescription()); - - /** Delete Translation */ - deleteTranslation = new Action("Delete Translation ...") { - public void run() { - /* - * Construct a list of type locale from all existing - * translations - */ - if (glossary == null || glossary.getGlossary() == null) - return; - - String referenceLang = glossary.getGlossary().info - .getTranslations()[0]; - if (viewState != null - && viewState.getReferenceLanguage() != null) - referenceLang = viewState.getReferenceLanguage(); - - List<Locale> locales = new ArrayList<Locale>(); - List<String> strLoc = new ArrayList<String>(); - for (String l : glossary.getGlossary().info.getTranslations()) { - if (l.equalsIgnoreCase(referenceLang)) - continue; - String[] locDef = l.split("_"); - Locale locale = locDef.length < 3 ? (locDef.length < 2 ? new Locale( - locDef[0]) : new Locale(locDef[0], locDef[1])) - : new Locale(locDef[0], locDef[1], locDef[2]); - locales.add(locale); - strLoc.add(l); - } - - /* - * Ask the user for the set of locales that need to be removed - * from the translation glossary - */ - ListSelectionDialog dlg = new ListSelectionDialog(getSite() - .getShell(), locales, new LocaleContentProvider(), - new LocaleLabelProvider(), "Select the Translation:"); - dlg.setTitle("Translation Selection"); - if (dlg.open() == ListSelectionDialog.OK) { - Object[] delLocales = (Object[]) dlg.getResult(); - List<String> toRemove = new ArrayList<String>(); - for (Object delLoc : delLocales) { - toRemove.add(strLoc.get(locales.indexOf(delLoc))); - } - glossary.getGlossary().info.translations - .removeAll(toRemove); - try { - glossary.saveGlossary(); - displayActions = null; - referenceActions = null; - viewState.setDisplayLanguages(null); - redrawTreeViewer(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }; - }; - deleteTranslation - .setDescription("Deletes a specific Locale from the translation glossary."); - deleteTranslation.setToolTipText(deleteTranslation.getDescription()); + if (this.glossary != null && this.glossary.getGlossary() != null) { + manager.add(new Separator()); + manager.add(newTranslation); + manager.add(deleteTranslation); + createMenuAdditions(manager); } - - private void contributeToActionBars() { - IActionBars bars = getViewSite().getActionBars(); - fillLocalPullDown(bars.getMenuManager()); - fillLocalToolBar(bars.getToolBarManager()); + } + + /*** CONTEXT MENU ***/ + private void hookContextMenu() { + MenuManager menuMgr = new MenuManager("#PopupMenu"); + menuMgr.setRemoveAllWhenShown(true); + menuMgr.addMenuListener(new IMenuListener() { + public void menuAboutToShow(IMenuManager manager) { + fillContextMenu(manager); + } + }); + Menu menu = menuMgr.createContextMenu(treeViewer.getViewer() + .getControl()); + treeViewer.getViewer().getControl().setMenu(menu); + getViewSite().registerContextMenu(menuMgr, treeViewer.getViewer()); + } + + private void fillContextMenu(IMenuManager manager) { + manager.removeAll(); + + if (this.glossary != null && this.glossary.getGlossary() != null) { + glossaryEditContribution = new GlossaryEntryMenuContribution( + treeViewer, !treeViewer.getViewer().getSelection() + .isEmpty()); + manager.add(this.glossaryEditContribution); + manager.add(new Separator()); + + createShowContentMenu(manager); + manager.add(new Separator()); + } + manager.add(editable); + manager.add(enableFuzzyMatching); + + /** Locale management section */ + if (this.glossary != null && this.glossary.getGlossary() != null) { + manager.add(new Separator()); + manager.add(newTranslation); + manager.add(deleteTranslation); } - private void fillLocalPullDown(IMenuManager manager) { - manager.removeAll(); - - if (this.glossary != null && this.glossary.getGlossary() != null) { - glossaryEditContribution = new GlossaryEntryMenuContribution( - treeViewer, !treeViewer.getViewer().getSelection() - .isEmpty()); - manager.add(this.glossaryEditContribution); - manager.add(new Separator()); - } + createMenuAdditions(manager); + } - manager.add(enableFuzzyMatching); - manager.add(editable); + private void createShowContentMenu(IMenuManager manager) { + showMenu = new MenuManager("&Show", "show"); - if (this.glossary != null && this.glossary.getGlossary() != null) { - manager.add(new Separator()); - manager.add(newTranslation); - manager.add(deleteTranslation); - createMenuAdditions(manager); + if (showAll == null || showSelectiveContent == null) { + showAll = new Action("All terms", Action.AS_RADIO_BUTTON) { + @Override + public void run() { + super.run(); + treeViewer.bindContentToSelection(false); + } + }; + showAll.setDescription("Display all glossary entries"); + showAll.setToolTipText(showAll.getDescription()); + showAll.setChecked(!viewState.isSelectiveViewEnabled()); + + showSelectiveContent = new Action("Relevant terms", + Action.AS_RADIO_BUTTON) { + @Override + public void run() { + super.run(); + treeViewer.bindContentToSelection(true); } + }; + showSelectiveContent + .setDescription("Displays only terms that are relevant for the currently selected Resource-Bundle entry"); + showSelectiveContent.setToolTipText(showSelectiveContent + .getDescription()); + showSelectiveContent.setChecked(viewState.isSelectiveViewEnabled()); } - /*** CONTEXT MENU ***/ - private void hookContextMenu() { - MenuManager menuMgr = new MenuManager("#PopupMenu"); - menuMgr.setRemoveAllWhenShown(true); - menuMgr.addMenuListener(new IMenuListener() { - public void menuAboutToShow(IMenuManager manager) { - fillContextMenu(manager); - } - }); - Menu menu = menuMgr.createContextMenu(treeViewer.getViewer() - .getControl()); - treeViewer.getViewer().getControl().setMenu(menu); - getViewSite().registerContextMenu(menuMgr, treeViewer.getViewer()); - } + showMenu.add(showAll); + showMenu.add(showSelectiveContent); - private void fillContextMenu(IMenuManager manager) { - manager.removeAll(); + manager.add(showMenu); + } - if (this.glossary != null && this.glossary.getGlossary() != null) { - glossaryEditContribution = new GlossaryEntryMenuContribution( - treeViewer, !treeViewer.getViewer().getSelection() - .isEmpty()); - manager.add(this.glossaryEditContribution); - manager.add(new Separator()); + private void createMenuAdditions(IMenuManager manager) { + // Make reference language actions + if (glossary != null && glossary.getGlossary() != null) { + Glossary g = glossary.getGlossary(); + final String[] translations = g.info.getTranslations(); - createShowContentMenu(manager); - manager.add(new Separator()); - } - manager.add(editable); - manager.add(enableFuzzyMatching); - - /** Locale management section */ - if (this.glossary != null && this.glossary.getGlossary() != null) { - manager.add(new Separator()); - manager.add(newTranslation); - manager.add(deleteTranslation); - } + if (translations == null || translations.length == 0) + return; - createMenuAdditions(manager); - } + referenceMenu = new MenuManager("&Reference Translation", "reflang"); + if (referenceActions == null) { + referenceActions = new ArrayList<Action>(); - private void createShowContentMenu(IMenuManager manager) { - showMenu = new MenuManager("&Show", "show"); - - if (showAll == null || showSelectiveContent == null) { - showAll = new Action("All terms", Action.AS_RADIO_BUTTON) { - @Override - public void run() { - super.run(); - treeViewer.bindContentToSelection(false); - } - }; - showAll.setDescription("Display all glossary entries"); - showAll.setToolTipText(showAll.getDescription()); - showAll.setChecked(!viewState.isSelectiveViewEnabled()); - - showSelectiveContent = new Action("Relevant terms", - Action.AS_RADIO_BUTTON) { - @Override - public void run() { - super.run(); - treeViewer.bindContentToSelection(true); - } - }; - showSelectiveContent - .setDescription("Displays only terms that are relevant for the currently selected Resource-Bundle entry"); - showSelectiveContent.setToolTipText(showSelectiveContent - .getDescription()); - showSelectiveContent.setChecked(viewState.isSelectiveViewEnabled()); - } + for (final String lang : translations) { + String[] locDef = lang.split("_"); + Locale l = locDef.length < 3 ? (locDef.length < 2 ? new Locale( + locDef[0]) : new Locale(locDef[0], locDef[1])) + : new Locale(locDef[0], locDef[1], locDef[2]); + Action refLangAction = new Action(lang, + Action.AS_RADIO_BUTTON) { + @Override + public void run() { + super.run(); + // init reference language specification + String referenceLanguage = translations[0]; + if (viewState.getReferenceLanguage() != null) + referenceLanguage = viewState + .getReferenceLanguage(); - showMenu.add(showAll); - showMenu.add(showSelectiveContent); + if (!lang.equalsIgnoreCase(referenceLanguage)) { + viewState.setReferenceLanguage(lang); - manager.add(showMenu); - } + // trigger redraw of displayed translations menu + displayActions = null; - private void createMenuAdditions(IMenuManager manager) { - // Make reference language actions - if (glossary != null && glossary.getGlossary() != null) { - Glossary g = glossary.getGlossary(); - final String[] translations = g.info.getTranslations(); - - if (translations == null || translations.length == 0) - return; - - referenceMenu = new MenuManager("&Reference Translation", "reflang"); - if (referenceActions == null) { - referenceActions = new ArrayList<Action>(); - - for (final String lang : translations) { - String[] locDef = lang.split("_"); - Locale l = locDef.length < 3 ? (locDef.length < 2 ? new Locale( - locDef[0]) : new Locale(locDef[0], locDef[1])) - : new Locale(locDef[0], locDef[1], locDef[2]); - Action refLangAction = new Action(lang, - Action.AS_RADIO_BUTTON) { - @Override - public void run() { - super.run(); - // init reference language specification - String referenceLanguage = translations[0]; - if (viewState.getReferenceLanguage() != null) - referenceLanguage = viewState - .getReferenceLanguage(); - - if (!lang.equalsIgnoreCase(referenceLanguage)) { - viewState.setReferenceLanguage(lang); - - // trigger redraw of displayed translations menu - displayActions = null; - - redrawTreeViewer(); - } - } - }; - // init reference language specification - String referenceLanguage = translations[0]; - if (viewState.getReferenceLanguage() != null) - referenceLanguage = viewState.getReferenceLanguage(); - else - viewState.setReferenceLanguage(referenceLanguage); - - refLangAction.setChecked(lang - .equalsIgnoreCase(referenceLanguage)); - refLangAction.setText(l.getDisplayName()); - referenceActions.add(refLangAction); - } + redrawTreeViewer(); + } } + }; + // init reference language specification + String referenceLanguage = translations[0]; + if (viewState.getReferenceLanguage() != null) + referenceLanguage = viewState.getReferenceLanguage(); + else + viewState.setReferenceLanguage(referenceLanguage); + + refLangAction.setChecked(lang + .equalsIgnoreCase(referenceLanguage)); + refLangAction.setText(l.getDisplayName()); + referenceActions.add(refLangAction); + } + } - for (Action a : referenceActions) { - referenceMenu.add(a); - } + for (Action a : referenceActions) { + referenceMenu.add(a); + } - // Make display language actions - displayMenu = new MenuManager("&Displayed Translations", - "displaylang"); - - if (displayActions == null) { - List<String> displayLanguages = viewState.getDisplayLanguages(); - - if (displayLanguages == null) { - viewState.setDisplayLangArr(translations); - displayLanguages = viewState.getDisplayLanguages(); - } - - displayActions = new ArrayList<Action>(); - for (final String lang : translations) { - String referenceLanguage = translations[0]; - if (viewState.getReferenceLanguage() != null) - referenceLanguage = viewState.getReferenceLanguage(); - - if (lang.equalsIgnoreCase(referenceLanguage)) - continue; - - String[] locDef = lang.split("_"); - Locale l = locDef.length < 3 ? (locDef.length < 2 ? new Locale( - locDef[0]) : new Locale(locDef[0], locDef[1])) - : new Locale(locDef[0], locDef[1], locDef[2]); - Action refLangAction = new Action(lang, Action.AS_CHECK_BOX) { - @Override - public void run() { - super.run(); - List<String> dls = viewState.getDisplayLanguages(); - if (this.isChecked()) { - if (!dls.contains(lang)) - dls.add(lang); - } else { - if (dls.contains(lang)) - dls.remove(lang); - } - viewState.setDisplayLanguages(dls); - redrawTreeViewer(); - } - }; - // init reference language specification - refLangAction.setChecked(displayLanguages.contains(lang)); - refLangAction.setText(l.getDisplayName()); - displayActions.add(refLangAction); - } - } + // Make display language actions + displayMenu = new MenuManager("&Displayed Translations", + "displaylang"); - for (Action a : displayActions) { - displayMenu.add(a); - } + if (displayActions == null) { + List<String> displayLanguages = viewState.getDisplayLanguages(); - manager.add(new Separator()); - manager.add(referenceMenu); - manager.add(displayMenu); + if (displayLanguages == null) { + viewState.setDisplayLangArr(translations); + displayLanguages = viewState.getDisplayLanguages(); } - } - private void fillLocalToolBar(IToolBarManager manager) { - } + displayActions = new ArrayList<Action>(); + for (final String lang : translations) { + String referenceLanguage = translations[0]; + if (viewState.getReferenceLanguage() != null) + referenceLanguage = viewState.getReferenceLanguage(); - @Override - public void saveState(IMemento memento) { - super.saveState(memento); - try { - viewState.setEditable(treeViewer.isEditable()); - viewState.setSortings(treeViewer.getSortInfo()); - viewState.setSearchString(treeViewer.getSearchString()); - viewState.setFuzzyMatchingEnabled(treeViewer - .isFuzzyMatchingEnabled()); - viewState.setMatchingPrecision(treeViewer.getMatchingPrecision()); - viewState.setSelectiveViewEnabled(treeViewer - .isSelectiveViewEnabled()); - viewState.saveState(memento); - } catch (Exception e) { - } - } + if (lang.equalsIgnoreCase(referenceLanguage)) + continue; - @Override - public void init(IViewSite site, IMemento memento) throws PartInitException { - super.init(site, memento); - this.memento = memento; - - // init Viewstate - viewState = new GlossaryViewState(null, null, false, null); - viewState.init(memento); - if (viewState.getGlossaryFile() != null) { - try { - glossary = new GlossaryManager(new File( - viewState.getGlossaryFile()), false); - } catch (Exception e) { - e.printStackTrace(); + String[] locDef = lang.split("_"); + Locale l = locDef.length < 3 ? (locDef.length < 2 ? new Locale( + locDef[0]) : new Locale(locDef[0], locDef[1])) + : new Locale(locDef[0], locDef[1], locDef[2]); + Action refLangAction = new Action(lang, Action.AS_CHECK_BOX) { + @Override + public void run() { + super.run(); + List<String> dls = viewState.getDisplayLanguages(); + if (this.isChecked()) { + if (!dls.contains(lang)) + dls.add(lang); + } else { + if (dls.contains(lang)) + dls.remove(lang); + } + viewState.setDisplayLanguages(dls); + redrawTreeViewer(); } + }; + // init reference language specification + refLangAction.setChecked(displayLanguages.contains(lang)); + refLangAction.setText(l.getDisplayName()); + displayActions.add(refLangAction); } - } + } - @Override - public void glossaryLoaded(LoadGlossaryEvent event) { - File glossaryFile = event.getGlossaryFile(); - try { - this.glossary = new GlossaryManager(glossaryFile, - event.isNewGlossary()); - viewState.setGlossaryFile(glossaryFile.getAbsolutePath()); + for (Action a : displayActions) { + displayMenu.add(a); + } - referenceActions = null; - displayActions = null; - viewState.setDisplayLangArr(glossary.getGlossary().info - .getTranslations()); - this.redrawTreeViewer(); - } catch (Exception e) { - MessageDialog.openError(getViewSite().getShell(), - "Cannot open Glossary", - "The choosen file does not represent a valid Glossary!"); - } + manager.add(new Separator()); + manager.add(referenceMenu); + manager.add(displayMenu); + } + } + + private void fillLocalToolBar(IToolBarManager manager) { + } + + @Override + public void saveState(IMemento memento) { + super.saveState(memento); + try { + viewState.setEditable(treeViewer.isEditable()); + viewState.setSortings(treeViewer.getSortInfo()); + viewState.setSearchString(treeViewer.getSearchString()); + viewState.setFuzzyMatchingEnabled(treeViewer + .isFuzzyMatchingEnabled()); + viewState.setMatchingPrecision(treeViewer.getMatchingPrecision()); + viewState.setSelectiveViewEnabled(treeViewer + .isSelectiveViewEnabled()); + viewState.saveState(memento); + } catch (Exception e) { + } + } + + @Override + public void init(IViewSite site, IMemento memento) throws PartInitException { + super.init(site, memento); + this.memento = memento; + + // init Viewstate + viewState = new GlossaryViewState(null, null, false, null); + viewState.init(memento); + if (viewState.getGlossaryFile() != null) { + try { + glossary = new GlossaryManager(new File( + viewState.getGlossaryFile()), false); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + @Override + public void glossaryLoaded(LoadGlossaryEvent event) { + File glossaryFile = event.getGlossaryFile(); + try { + this.glossary = new GlossaryManager(glossaryFile, + event.isNewGlossary()); + viewState.setGlossaryFile(glossaryFile.getAbsolutePath()); + + referenceActions = null; + displayActions = null; + viewState.setDisplayLangArr(glossary.getGlossary().info + .getTranslations()); + this.redrawTreeViewer(); + } catch (Exception e) { + MessageDialog.openError(getViewSite().getShell(), + "Cannot open Glossary", + "The choosen file does not represent a valid Glossary!"); } + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleContentProvider.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleContentProvider.java index 6c8fcec8..a28f99d3 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleContentProvider.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleContentProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -18,22 +18,22 @@ public class LocaleContentProvider implements IStructuredContentProvider { - @Override - public void dispose() { - } + @Override + public void dispose() { + } - @Override - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + @Override + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - } + } - @Override - public Object[] getElements(Object inputElement) { - if (inputElement instanceof List) { - List<Locale> locales = (List<Locale>) inputElement; - return locales.toArray(new Locale[locales.size()]); - } - return null; + @Override + public Object[] getElements(Object inputElement) { + if (inputElement instanceof List) { + List<Locale> locales = (List<Locale>) inputElement; + return locales.toArray(new Locale[locales.size()]); } + return null; + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleLabelProvider.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleLabelProvider.java index aa5f64f4..5a5e8100 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleLabelProvider.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/dialog/LocaleLabelProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -18,38 +18,38 @@ public class LocaleLabelProvider implements ILabelProvider { - @Override - public void addListener(ILabelProviderListener listener) { + @Override + public void addListener(ILabelProviderListener listener) { - } + } - @Override - public void dispose() { + @Override + public void dispose() { - } + } - @Override - public boolean isLabelProperty(Object element, String property) { - return false; - } + @Override + public boolean isLabelProperty(Object element, String property) { + return false; + } - @Override - public void removeListener(ILabelProviderListener listener) { + @Override + public void removeListener(ILabelProviderListener listener) { - } + } - @Override - public Image getImage(Object element) { - // TODO add image output for Locale entries - return null; - } + @Override + public Image getImage(Object element) { + // TODO add image output for Locale entries + return null; + } - @Override - public String getText(Object element) { - if (element != null && element instanceof Locale) - return ((Locale) element).getDisplayName(); + @Override + public String getText(Object element) { + if (element != null && element instanceof Locale) + return ((Locale) element).getDisplayName(); - return null; - } + return null; + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java index 2422e95b..9a91eeb6 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -23,80 +23,80 @@ import org.eclipselabs.tapiji.translator.views.widgets.GlossaryWidget; public class GlossaryEntryMenuContribution extends ContributionItem implements - ISelectionChangedListener { - - private GlossaryWidget parentView; - private boolean legalSelection = false; - - // Menu-Items - private MenuItem addItem; - private MenuItem removeItem; - - public GlossaryEntryMenuContribution() { - } + ISelectionChangedListener { + + private GlossaryWidget parentView; + private boolean legalSelection = false; + + // Menu-Items + private MenuItem addItem; + private MenuItem removeItem; + + public GlossaryEntryMenuContribution() { + } + + public GlossaryEntryMenuContribution(GlossaryWidget view, + boolean legalSelection) { + this.legalSelection = legalSelection; + this.parentView = view; + parentView.addSelectionChangedListener(this); + } + + @Override + public void fill(Menu menu, int index) { + + // MenuItem for adding a new entry + addItem = new MenuItem(menu, SWT.NONE, index); + addItem.setText("Add ..."); + addItem.setImage(PlatformUI.getWorkbench().getSharedImages() + .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage()); + addItem.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { + parentView.addNewItem(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + + } + }); + + if ((parentView == null && legalSelection) || parentView != null) { + // MenuItem for deleting the currently selected entry + removeItem = new MenuItem(menu, SWT.NONE, index + 1); + removeItem.setText("Remove"); + removeItem.setImage(PlatformUI.getWorkbench().getSharedImages() + .getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE) + .createImage()); + removeItem.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { + parentView.deleteSelectedItems(); + } - public GlossaryEntryMenuContribution(GlossaryWidget view, - boolean legalSelection) { - this.legalSelection = legalSelection; - this.parentView = view; - parentView.addSelectionChangedListener(this); - } + @Override + public void widgetDefaultSelected(SelectionEvent e) { - @Override - public void fill(Menu menu, int index) { - - // MenuItem for adding a new entry - addItem = new MenuItem(menu, SWT.NONE, index); - addItem.setText("Add ..."); - addItem.setImage(PlatformUI.getWorkbench().getSharedImages() - .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage()); - addItem.addSelectionListener(new SelectionListener() { - - @Override - public void widgetSelected(SelectionEvent e) { - parentView.addNewItem(); - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - - } - }); - - if ((parentView == null && legalSelection) || parentView != null) { - // MenuItem for deleting the currently selected entry - removeItem = new MenuItem(menu, SWT.NONE, index + 1); - removeItem.setText("Remove"); - removeItem.setImage(PlatformUI.getWorkbench().getSharedImages() - .getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE) - .createImage()); - removeItem.addSelectionListener(new SelectionListener() { - - @Override - public void widgetSelected(SelectionEvent e) { - parentView.deleteSelectedItems(); - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - - } - }); - enableMenuItems(); } + }); + enableMenuItems(); } + } - protected void enableMenuItems() { - try { - removeItem.setEnabled(legalSelection); - } catch (Exception e) { - } + protected void enableMenuItems() { + try { + removeItem.setEnabled(legalSelection); + } catch (Exception e) { } + } - @Override - public void selectionChanged(SelectionChangedEvent event) { - legalSelection = !event.getSelection().isEmpty(); - // enableMenuItems (); - } + @Override + public void selectionChanged(SelectionChangedEvent event) { + legalSelection = !event.getSelection().isEmpty(); + // enableMenuItems (); + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/GlossaryWidget.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/GlossaryWidget.java index 4c0c0b47..0e2850ac 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/GlossaryWidget.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/GlossaryWidget.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -64,593 +64,593 @@ import org.eclipselabs.tapiji.translator.views.widgets.sorter.SortInfo; public class GlossaryWidget extends Composite implements - IResourceChangeListener { - - private final int TERM_COLUMN_WEIGHT = 1; - private final int DESCRIPTION_COLUMN_WEIGHT = 1; - - private boolean editable; - - private IWorkbenchPartSite site; - private TreeColumnLayout basicLayout; - private TreeViewer treeViewer; - private TreeColumn termColumn; - private boolean grouped = true; - private boolean fuzzyMatchingEnabled = false; - private boolean selectiveViewEnabled = false; - private float matchingPrecision = .75f; - private String referenceLocale; - private List<String> displayedTranslations; - private String[] translationsToDisplay; - - private SortInfo sortInfo; - private Glossary glossary; - private GlossaryManager manager; - - private GlossaryContentProvider contentProvider; - private GlossaryLabelProvider labelProvider; - - /*** MATCHER ***/ - ExactMatcher matcher; - - /*** SORTER ***/ - GlossaryEntrySorter sorter; - - /*** ACTIONS ***/ - private Action doubleClickAction; - - public GlossaryWidget(IWorkbenchPartSite site, Composite parent, int style, - GlossaryManager manager, String refLang, List<String> dls) { - super(parent, style); - this.site = site; - - if (manager != null) { - this.manager = manager; - this.glossary = manager.getGlossary(); - - if (refLang != null) - this.referenceLocale = refLang; - else - this.referenceLocale = glossary.info.getTranslations()[0]; - - if (dls != null) - this.translationsToDisplay = dls - .toArray(new String[dls.size()]); - else - this.translationsToDisplay = glossary.info.getTranslations(); - } + IResourceChangeListener { - constructWidget(); + private final int TERM_COLUMN_WEIGHT = 1; + private final int DESCRIPTION_COLUMN_WEIGHT = 1; - if (this.glossary != null) { - initTreeViewer(); - initMatchers(); - initSorters(); - } + private boolean editable; - hookDragAndDrop(); - registerListeners(); - } + private IWorkbenchPartSite site; + private TreeColumnLayout basicLayout; + private TreeViewer treeViewer; + private TreeColumn termColumn; + private boolean grouped = true; + private boolean fuzzyMatchingEnabled = false; + private boolean selectiveViewEnabled = false; + private float matchingPrecision = .75f; + private String referenceLocale; + private List<String> displayedTranslations; + private String[] translationsToDisplay; - protected void registerListeners() { - treeViewer.getControl().addKeyListener(new KeyAdapter() { - public void keyPressed(KeyEvent event) { - if (event.character == SWT.DEL && event.stateMask == 0) { - deleteSelectedItems(); - } - } - }); + private SortInfo sortInfo; + private Glossary glossary; + private GlossaryManager manager; - // Listen resource changes - ResourcesPlugin.getWorkspace().addResourceChangeListener(this); - } + private GlossaryContentProvider contentProvider; + private GlossaryLabelProvider labelProvider; - protected void initSorters() { - sorter = new GlossaryEntrySorter(treeViewer, sortInfo, - glossary.getIndexOfLocale(referenceLocale), - glossary.info.translations); - treeViewer.setSorter(sorter); - } + /*** MATCHER ***/ + ExactMatcher matcher; - public void enableFuzzyMatching(boolean enable) { - String pattern = ""; - if (matcher != null) { - pattern = matcher.getPattern(); - - if (!fuzzyMatchingEnabled && enable) { - if (matcher.getPattern().trim().length() > 1 - && matcher.getPattern().startsWith("*") - && matcher.getPattern().endsWith("*")) - pattern = pattern.substring(1).substring(0, - pattern.length() - 2); - matcher.setPattern(null); - } - } - fuzzyMatchingEnabled = enable; - initMatchers(); - - matcher.setPattern(pattern); - treeViewer.refresh(); - } + /*** SORTER ***/ + GlossaryEntrySorter sorter; - public boolean isFuzzyMatchingEnabled() { - return fuzzyMatchingEnabled; - } - - protected void initMatchers() { - treeViewer.resetFilters(); + /*** ACTIONS ***/ + private Action doubleClickAction; - String patternBefore = matcher != null ? matcher.getPattern() : ""; + public GlossaryWidget(IWorkbenchPartSite site, Composite parent, int style, + GlossaryManager manager, String refLang, List<String> dls) { + super(parent, style); + this.site = site; - if (fuzzyMatchingEnabled) { - matcher = new FuzzyMatcher(treeViewer); - ((FuzzyMatcher) matcher).setMinimumSimilarity(matchingPrecision); - } else - matcher = new ExactMatcher(treeViewer); + if (manager != null) { + this.manager = manager; + this.glossary = manager.getGlossary(); - matcher.setPattern(patternBefore); + if (refLang != null) + this.referenceLocale = refLang; + else + this.referenceLocale = glossary.info.getTranslations()[0]; - if (this.selectiveViewEnabled) - new SelectiveMatcher(treeViewer, site.getPage()); + if (dls != null) + this.translationsToDisplay = dls + .toArray(new String[dls.size()]); + else + this.translationsToDisplay = glossary.info.getTranslations(); } - protected void initTreeViewer() { - // init content provider - contentProvider = new GlossaryContentProvider(this.glossary); - treeViewer.setContentProvider(contentProvider); - - // init label provider - labelProvider = new GlossaryLabelProvider( - this.displayedTranslations.indexOf(referenceLocale), - this.displayedTranslations, site.getPage()); - treeViewer.setLabelProvider(labelProvider); + constructWidget(); - setTreeStructure(grouped); + if (this.glossary != null) { + initTreeViewer(); + initMatchers(); + initSorters(); } - public void setTreeStructure(boolean grouped) { - this.grouped = grouped; - ((GlossaryContentProvider) treeViewer.getContentProvider()) - .setGrouped(this.grouped); - if (treeViewer.getInput() == null) - treeViewer.setUseHashlookup(false); - treeViewer.setInput(this.glossary); - treeViewer.refresh(); - } - - protected void constructWidget() { - basicLayout = new TreeColumnLayout(); - this.setLayout(basicLayout); - - treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE - | SWT.BORDER); - Tree tree = treeViewer.getTree(); + hookDragAndDrop(); + registerListeners(); + } - if (glossary != null) { - tree.setHeaderVisible(true); - tree.setLinesVisible(true); - - // create tree-columns - constructTreeColumns(tree); - } else { - tree.setHeaderVisible(false); - tree.setLinesVisible(false); + protected void registerListeners() { + treeViewer.getControl().addKeyListener(new KeyAdapter() { + public void keyPressed(KeyEvent event) { + if (event.character == SWT.DEL && event.stateMask == 0) { + deleteSelectedItems(); } - - makeActions(); - hookDoubleClickAction(); - - // register messages table as selection provider - site.setSelectionProvider(treeViewer); - } - - /** - * Gets the orientation suited for a given locale. - * - * @param locale - * the locale - * @return <code>SWT.RIGHT_TO_LEFT</code> or <code>SWT.LEFT_TO_RIGHT</code> - */ - private int getOrientation(Locale locale) { - if (locale != null) { - ComponentOrientation orientation = ComponentOrientation - .getOrientation(locale); - if (orientation == ComponentOrientation.RIGHT_TO_LEFT) { - return SWT.RIGHT_TO_LEFT; + } + }); + + // Listen resource changes + ResourcesPlugin.getWorkspace().addResourceChangeListener(this); + } + + protected void initSorters() { + sorter = new GlossaryEntrySorter(treeViewer, sortInfo, + glossary.getIndexOfLocale(referenceLocale), + glossary.info.translations); + treeViewer.setSorter(sorter); + } + + public void enableFuzzyMatching(boolean enable) { + String pattern = ""; + if (matcher != null) { + pattern = matcher.getPattern(); + + if (!fuzzyMatchingEnabled && enable) { + if (matcher.getPattern().trim().length() > 1 + && matcher.getPattern().startsWith("*") + && matcher.getPattern().endsWith("*")) + pattern = pattern.substring(1).substring(0, + pattern.length() - 2); + matcher.setPattern(null); + } + } + fuzzyMatchingEnabled = enable; + initMatchers(); + + matcher.setPattern(pattern); + treeViewer.refresh(); + } + + public boolean isFuzzyMatchingEnabled() { + return fuzzyMatchingEnabled; + } + + protected void initMatchers() { + treeViewer.resetFilters(); + + String patternBefore = matcher != null ? matcher.getPattern() : ""; + + if (fuzzyMatchingEnabled) { + matcher = new FuzzyMatcher(treeViewer); + ((FuzzyMatcher) matcher).setMinimumSimilarity(matchingPrecision); + } else + matcher = new ExactMatcher(treeViewer); + + matcher.setPattern(patternBefore); + + if (this.selectiveViewEnabled) + new SelectiveMatcher(treeViewer, site.getPage()); + } + + protected void initTreeViewer() { + // init content provider + contentProvider = new GlossaryContentProvider(this.glossary); + treeViewer.setContentProvider(contentProvider); + + // init label provider + labelProvider = new GlossaryLabelProvider( + this.displayedTranslations.indexOf(referenceLocale), + this.displayedTranslations, site.getPage()); + treeViewer.setLabelProvider(labelProvider); + + setTreeStructure(grouped); + } + + public void setTreeStructure(boolean grouped) { + this.grouped = grouped; + ((GlossaryContentProvider) treeViewer.getContentProvider()) + .setGrouped(this.grouped); + if (treeViewer.getInput() == null) + treeViewer.setUseHashlookup(false); + treeViewer.setInput(this.glossary); + treeViewer.refresh(); + } + + protected void constructWidget() { + basicLayout = new TreeColumnLayout(); + this.setLayout(basicLayout); + + treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE + | SWT.BORDER); + Tree tree = treeViewer.getTree(); + + if (glossary != null) { + tree.setHeaderVisible(true); + tree.setLinesVisible(true); + + // create tree-columns + constructTreeColumns(tree); + } else { + tree.setHeaderVisible(false); + tree.setLinesVisible(false); + } + + makeActions(); + hookDoubleClickAction(); + + // register messages table as selection provider + site.setSelectionProvider(treeViewer); + } + + /** + * Gets the orientation suited for a given locale. + * + * @param locale + * the locale + * @return <code>SWT.RIGHT_TO_LEFT</code> or <code>SWT.LEFT_TO_RIGHT</code> + */ + private int getOrientation(Locale locale) { + if (locale != null) { + ComponentOrientation orientation = ComponentOrientation + .getOrientation(locale); + if (orientation == ComponentOrientation.RIGHT_TO_LEFT) { + return SWT.RIGHT_TO_LEFT; + } + } + return SWT.LEFT_TO_RIGHT; + } + + protected void constructTreeColumns(Tree tree) { + tree.removeAll(); + if (this.displayedTranslations == null) + this.displayedTranslations = new ArrayList<String>(); + + this.displayedTranslations.clear(); + + /** Reference term */ + String[] refDef = referenceLocale.split("_"); + Locale l = refDef.length < 3 ? (refDef.length < 2 ? new Locale( + refDef[0]) : new Locale(refDef[0], refDef[1])) : new Locale( + refDef[0], refDef[1], refDef[2]); + + this.displayedTranslations.add(referenceLocale); + termColumn = new TreeColumn(tree, SWT.RIGHT_TO_LEFT/* getOrientation(l) */); + + termColumn.setText(l.getDisplayName()); + TreeViewerColumn termCol = new TreeViewerColumn(treeViewer, termColumn); + termCol.setEditingSupport(new EditingSupport(treeViewer) { + TextCellEditor editor = null; + + @Override + protected void setValue(Object element, Object value) { + if (element instanceof Term) { + Term term = (Term) element; + Translation translation = (Translation) term + .getTranslation(referenceLocale); + + if (translation != null) { + translation.value = (String) value; + Glossary gl = ((GlossaryContentProvider) treeViewer + .getContentProvider()).getGlossary(); + manager.setGlossary(gl); + try { + manager.saveGlossary(); + } catch (Exception e) { + e.printStackTrace(); } + } + treeViewer.refresh(); } - return SWT.LEFT_TO_RIGHT; - } - - protected void constructTreeColumns(Tree tree) { - tree.removeAll(); - if (this.displayedTranslations == null) - this.displayedTranslations = new ArrayList<String>(); - - this.displayedTranslations.clear(); - - /** Reference term */ - String[] refDef = referenceLocale.split("_"); - Locale l = refDef.length < 3 ? (refDef.length < 2 ? new Locale( - refDef[0]) : new Locale(refDef[0], refDef[1])) : new Locale( - refDef[0], refDef[1], refDef[2]); - - this.displayedTranslations.add(referenceLocale); - termColumn = new TreeColumn(tree, SWT.RIGHT_TO_LEFT/* getOrientation(l) */); - - termColumn.setText(l.getDisplayName()); - TreeViewerColumn termCol = new TreeViewerColumn(treeViewer, termColumn); - termCol.setEditingSupport(new EditingSupport(treeViewer) { - TextCellEditor editor = null; - - @Override - protected void setValue(Object element, Object value) { - if (element instanceof Term) { - Term term = (Term) element; - Translation translation = (Translation) term - .getTranslation(referenceLocale); - - if (translation != null) { - translation.value = (String) value; - Glossary gl = ((GlossaryContentProvider) treeViewer - .getContentProvider()).getGlossary(); - manager.setGlossary(gl); - try { - manager.saveGlossary(); - } catch (Exception e) { - e.printStackTrace(); - } - } - treeViewer.refresh(); - } - } - - @Override - protected Object getValue(Object element) { - return labelProvider.getColumnText(element, 0); - } - - @Override - protected CellEditor getCellEditor(Object element) { - if (editor == null) { - Composite tree = (Composite) treeViewer.getControl(); - editor = new TextCellEditor(tree); - } - return editor; - } - - @Override - protected boolean canEdit(Object element) { - return editable; - } - }); - termColumn.addSelectionListener(new SelectionListener() { - - @Override - public void widgetSelected(SelectionEvent e) { - updateSorter(0); - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - updateSorter(0); - } - }); - basicLayout.setColumnData(termColumn, new ColumnWeightData( - TERM_COLUMN_WEIGHT)); - - /** Translations */ - String[] allLocales = this.translationsToDisplay; - - int iCol = 1; - for (String locale : allLocales) { - final int ifCall = iCol; - final String sfLocale = locale; - if (locale.equalsIgnoreCase(this.referenceLocale)) - continue; - - // trac the rendered translation - this.displayedTranslations.add(locale); - - String[] locDef = locale.split("_"); - l = locDef.length < 3 ? (locDef.length < 2 ? new Locale(locDef[0]) - : new Locale(locDef[0], locDef[1])) : new Locale(locDef[0], - locDef[1], locDef[2]); - - // Add editing support to this table column - TreeColumn descriptionColumn = new TreeColumn(tree, SWT.NONE); - TreeViewerColumn tCol = new TreeViewerColumn(treeViewer, - descriptionColumn); - tCol.setEditingSupport(new EditingSupport(treeViewer) { - TextCellEditor editor = null; - - @Override - protected void setValue(Object element, Object value) { - if (element instanceof Term) { - Term term = (Term) element; - Translation translation = (Translation) term - .getTranslation(sfLocale); - - if (translation != null) { - translation.value = (String) value; - Glossary gl = ((GlossaryContentProvider) treeViewer - .getContentProvider()).getGlossary(); - manager.setGlossary(gl); - try { - manager.saveGlossary(); - } catch (Exception e) { - e.printStackTrace(); - } - } - treeViewer.refresh(); - } - } - - @Override - protected Object getValue(Object element) { - return labelProvider.getColumnText(element, ifCall); - } - - @Override - protected CellEditor getCellEditor(Object element) { - if (editor == null) { - Composite tree = (Composite) treeViewer.getControl(); - editor = new TextCellEditor(tree); - } - return editor; - } - - @Override - protected boolean canEdit(Object element) { - return editable; - } - }); - - descriptionColumn.setText(l.getDisplayName()); - descriptionColumn.addSelectionListener(new SelectionListener() { - @Override - public void widgetSelected(SelectionEvent e) { - updateSorter(ifCall); - } - - @Override - public void widgetDefaultSelected(SelectionEvent e) { - updateSorter(ifCall); - } - }); - basicLayout.setColumnData(descriptionColumn, new ColumnWeightData( - DESCRIPTION_COLUMN_WEIGHT)); - iCol++; - } - - } - - protected void updateSorter(int idx) { - SortInfo sortInfo = sorter.getSortInfo(); - if (idx == sortInfo.getColIdx()) - sortInfo.setDESC(!sortInfo.isDESC()); - else { - sortInfo.setColIdx(idx); - sortInfo.setDESC(false); + } + + @Override + protected Object getValue(Object element) { + return labelProvider.getColumnText(element, 0); + } + + @Override + protected CellEditor getCellEditor(Object element) { + if (editor == null) { + Composite tree = (Composite) treeViewer.getControl(); + editor = new TextCellEditor(tree); } - sorter.setSortInfo(sortInfo); - setTreeStructure(idx == 0); - treeViewer.refresh(); - } - - @Override - public boolean setFocus() { - return treeViewer.getControl().setFocus(); - } - - /*** DRAG AND DROP ***/ - protected void hookDragAndDrop() { - GlossaryDragSource source = new GlossaryDragSource(treeViewer, manager); - GlossaryDropTarget target = new GlossaryDropTarget(treeViewer, manager); - - // Initialize drag source for copy event - DragSource dragSource = new DragSource(treeViewer.getControl(), - DND.DROP_MOVE); - dragSource.setTransfer(new Transfer[] { TermTransfer.getInstance() }); - dragSource.addDragListener(source); - - // Initialize drop target for copy event - DropTarget dropTarget = new DropTarget(treeViewer.getControl(), - DND.DROP_MOVE); - dropTarget.setTransfer(new Transfer[] { TermTransfer.getInstance() }); - dropTarget.addDropListener(target); - } - - /*** ACTIONS ***/ - - private void makeActions() { - doubleClickAction = new Action() { - - @Override - public void run() { - // implement the cell edit event - } - - }; - } + return editor; + } - private void hookDoubleClickAction() { - treeViewer.addDoubleClickListener(new IDoubleClickListener() { - public void doubleClick(DoubleClickEvent event) { - doubleClickAction.run(); + @Override + protected boolean canEdit(Object element) { + return editable; + } + }); + termColumn.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { + updateSorter(0); + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + updateSorter(0); + } + }); + basicLayout.setColumnData(termColumn, new ColumnWeightData( + TERM_COLUMN_WEIGHT)); + + /** Translations */ + String[] allLocales = this.translationsToDisplay; + + int iCol = 1; + for (String locale : allLocales) { + final int ifCall = iCol; + final String sfLocale = locale; + if (locale.equalsIgnoreCase(this.referenceLocale)) + continue; + + // trac the rendered translation + this.displayedTranslations.add(locale); + + String[] locDef = locale.split("_"); + l = locDef.length < 3 ? (locDef.length < 2 ? new Locale(locDef[0]) + : new Locale(locDef[0], locDef[1])) : new Locale(locDef[0], + locDef[1], locDef[2]); + + // Add editing support to this table column + TreeColumn descriptionColumn = new TreeColumn(tree, SWT.NONE); + TreeViewerColumn tCol = new TreeViewerColumn(treeViewer, + descriptionColumn); + tCol.setEditingSupport(new EditingSupport(treeViewer) { + TextCellEditor editor = null; + + @Override + protected void setValue(Object element, Object value) { + if (element instanceof Term) { + Term term = (Term) element; + Translation translation = (Translation) term + .getTranslation(sfLocale); + + if (translation != null) { + translation.value = (String) value; + Glossary gl = ((GlossaryContentProvider) treeViewer + .getContentProvider()).getGlossary(); + manager.setGlossary(gl); + try { + manager.saveGlossary(); + } catch (Exception e) { + e.printStackTrace(); + } } - }); - } - - /*** SELECTION LISTENER ***/ - - private void refreshViewer() { - treeViewer.refresh(); - } - - public StructuredViewer getViewer() { - return this.treeViewer; - } - - public void setSearchString(String pattern) { - matcher.setPattern(pattern); - if (matcher.getPattern().trim().length() > 0) - grouped = false; - else - grouped = true; - labelProvider.setSearchEnabled(!grouped); - this.setTreeStructure(grouped && sorter != null - && sorter.getSortInfo().getColIdx() == 0); - treeViewer.refresh(); - } - - public SortInfo getSortInfo() { - if (this.sorter != null) - return this.sorter.getSortInfo(); - else - return null; - } - - public void setSortInfo(SortInfo sortInfo) { - if (sorter != null) { - sorter.setSortInfo(sortInfo); - setTreeStructure(sortInfo.getColIdx() == 0); treeViewer.refresh(); + } } - } - public String getSearchString() { - return matcher.getPattern(); - } - - public boolean isEditable() { - return editable; - } - - public void setEditable(boolean editable) { - this.editable = editable; - } - - public void deleteSelectedItems() { - List<String> ids = new ArrayList<String>(); - this.glossary = ((GlossaryContentProvider) treeViewer - .getContentProvider()).getGlossary(); - - ISelection selection = site.getSelectionProvider().getSelection(); - if (selection instanceof IStructuredSelection) { - for (Iterator<?> iter = ((IStructuredSelection) selection) - .iterator(); iter.hasNext();) { - Object elem = iter.next(); - if (elem instanceof Term) { - this.glossary.removeTerm((Term) elem); - this.manager.setGlossary(this.glossary); - try { - this.manager.saveGlossary(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } + @Override + protected Object getValue(Object element) { + return labelProvider.getColumnText(element, ifCall); } - this.refreshViewer(); - } - public void addNewItem() { - // event.feedback = DND.FEEDBACK_INSERT_BEFORE; - Term parentTerm = null; - - ISelection selection = site.getSelectionProvider().getSelection(); - if (selection instanceof IStructuredSelection) { - for (Iterator<?> iter = ((IStructuredSelection) selection) - .iterator(); iter.hasNext();) { - Object elem = iter.next(); - if (elem instanceof Term) { - parentTerm = ((Term) elem); - break; - } - } + @Override + protected CellEditor getCellEditor(Object element) { + if (editor == null) { + Composite tree = (Composite) treeViewer.getControl(); + editor = new TextCellEditor(tree); + } + return editor; } - InputDialog dialog = new InputDialog(this.getShell(), "Neuer Begriff", - "Please, define the new term:", "", null); - - if (dialog.open() == InputDialog.OK) { - if (dialog.getValue() != null - && dialog.getValue().trim().length() > 0) { - this.glossary = ((GlossaryContentProvider) treeViewer - .getContentProvider()).getGlossary(); - - // Construct a new term - Term newTerm = new Term(); - Translation defaultTranslation = new Translation(); - defaultTranslation.id = referenceLocale; - defaultTranslation.value = dialog.getValue(); - newTerm.translations.add(defaultTranslation); - - this.glossary.addTerm(parentTerm, newTerm); - - this.manager.setGlossary(this.glossary); - try { - this.manager.saveGlossary(); - } catch (Exception e) { - e.printStackTrace(); - } - } + @Override + protected boolean canEdit(Object element) { + return editable; } - this.refreshViewer(); - } + }); - public void setMatchingPrecision(float value) { - matchingPrecision = value; - if (matcher instanceof FuzzyMatcher) { - ((FuzzyMatcher) matcher).setMinimumSimilarity(value); - treeViewer.refresh(); + descriptionColumn.setText(l.getDisplayName()); + descriptionColumn.addSelectionListener(new SelectionListener() { + @Override + public void widgetSelected(SelectionEvent e) { + updateSorter(ifCall); } - } - - public float getMatchingPrecision() { - return matchingPrecision; - } - - public Control getControl() { - return treeViewer.getControl(); - } - - public Glossary getGlossary() { - return this.glossary; - } - - public void addSelectionChangedListener(ISelectionChangedListener listener) { - treeViewer.addSelectionChangedListener(listener); - } - - public String getReferenceLanguage() { - return referenceLocale; - } - - public void setReferenceLanguage(String lang) { - this.referenceLocale = lang; - } - public void bindContentToSelection(boolean enable) { - this.selectiveViewEnabled = enable; - initMatchers(); - } - - public boolean isSelectiveViewEnabled() { - return selectiveViewEnabled; + @Override + public void widgetDefaultSelected(SelectionEvent e) { + updateSorter(ifCall); + } + }); + basicLayout.setColumnData(descriptionColumn, new ColumnWeightData( + DESCRIPTION_COLUMN_WEIGHT)); + iCol++; + } + + } + + protected void updateSorter(int idx) { + SortInfo sortInfo = sorter.getSortInfo(); + if (idx == sortInfo.getColIdx()) + sortInfo.setDESC(!sortInfo.isDESC()); + else { + sortInfo.setColIdx(idx); + sortInfo.setDESC(false); + } + sorter.setSortInfo(sortInfo); + setTreeStructure(idx == 0); + treeViewer.refresh(); + } + + @Override + public boolean setFocus() { + return treeViewer.getControl().setFocus(); + } + + /*** DRAG AND DROP ***/ + protected void hookDragAndDrop() { + GlossaryDragSource source = new GlossaryDragSource(treeViewer, manager); + GlossaryDropTarget target = new GlossaryDropTarget(treeViewer, manager); + + // Initialize drag source for copy event + DragSource dragSource = new DragSource(treeViewer.getControl(), + DND.DROP_MOVE); + dragSource.setTransfer(new Transfer[] { TermTransfer.getInstance() }); + dragSource.addDragListener(source); + + // Initialize drop target for copy event + DropTarget dropTarget = new DropTarget(treeViewer.getControl(), + DND.DROP_MOVE); + dropTarget.setTransfer(new Transfer[] { TermTransfer.getInstance() }); + dropTarget.addDropListener(target); + } + + /*** ACTIONS ***/ + + private void makeActions() { + doubleClickAction = new Action() { + + @Override + public void run() { + // implement the cell edit event + } + + }; + } + + private void hookDoubleClickAction() { + treeViewer.addDoubleClickListener(new IDoubleClickListener() { + public void doubleClick(DoubleClickEvent event) { + doubleClickAction.run(); + } + }); + } + + /*** SELECTION LISTENER ***/ + + private void refreshViewer() { + treeViewer.refresh(); + } + + public StructuredViewer getViewer() { + return this.treeViewer; + } + + public void setSearchString(String pattern) { + matcher.setPattern(pattern); + if (matcher.getPattern().trim().length() > 0) + grouped = false; + else + grouped = true; + labelProvider.setSearchEnabled(!grouped); + this.setTreeStructure(grouped && sorter != null + && sorter.getSortInfo().getColIdx() == 0); + treeViewer.refresh(); + } + + public SortInfo getSortInfo() { + if (this.sorter != null) + return this.sorter.getSortInfo(); + else + return null; + } + + public void setSortInfo(SortInfo sortInfo) { + if (sorter != null) { + sorter.setSortInfo(sortInfo); + setTreeStructure(sortInfo.getColIdx() == 0); + treeViewer.refresh(); + } + } + + public String getSearchString() { + return matcher.getPattern(); + } + + public boolean isEditable() { + return editable; + } + + public void setEditable(boolean editable) { + this.editable = editable; + } + + public void deleteSelectedItems() { + List<String> ids = new ArrayList<String>(); + this.glossary = ((GlossaryContentProvider) treeViewer + .getContentProvider()).getGlossary(); + + ISelection selection = site.getSelectionProvider().getSelection(); + if (selection instanceof IStructuredSelection) { + for (Iterator<?> iter = ((IStructuredSelection) selection) + .iterator(); iter.hasNext();) { + Object elem = iter.next(); + if (elem instanceof Term) { + this.glossary.removeTerm((Term) elem); + this.manager.setGlossary(this.glossary); + try { + this.manager.saveGlossary(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + this.refreshViewer(); + } + + public void addNewItem() { + // event.feedback = DND.FEEDBACK_INSERT_BEFORE; + Term parentTerm = null; + + ISelection selection = site.getSelectionProvider().getSelection(); + if (selection instanceof IStructuredSelection) { + for (Iterator<?> iter = ((IStructuredSelection) selection) + .iterator(); iter.hasNext();) { + Object elem = iter.next(); + if (elem instanceof Term) { + parentTerm = ((Term) elem); + break; + } + } } - @Override - public void dispose() { - super.dispose(); - ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); - } + InputDialog dialog = new InputDialog(this.getShell(), "Neuer Begriff", + "Please, define the new term:", "", null); - @Override - public void resourceChanged(IResourceChangeEvent event) { - initMatchers(); - this.refreshViewer(); - } + if (dialog.open() == InputDialog.OK) { + if (dialog.getValue() != null + && dialog.getValue().trim().length() > 0) { + this.glossary = ((GlossaryContentProvider) treeViewer + .getContentProvider()).getGlossary(); + + // Construct a new term + Term newTerm = new Term(); + Translation defaultTranslation = new Translation(); + defaultTranslation.id = referenceLocale; + defaultTranslation.value = dialog.getValue(); + newTerm.translations.add(defaultTranslation); + + this.glossary.addTerm(parentTerm, newTerm); + + this.manager.setGlossary(this.glossary); + try { + this.manager.saveGlossary(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + this.refreshViewer(); + } + + public void setMatchingPrecision(float value) { + matchingPrecision = value; + if (matcher instanceof FuzzyMatcher) { + ((FuzzyMatcher) matcher).setMinimumSimilarity(value); + treeViewer.refresh(); + } + } + + public float getMatchingPrecision() { + return matchingPrecision; + } + + public Control getControl() { + return treeViewer.getControl(); + } + + public Glossary getGlossary() { + return this.glossary; + } + + public void addSelectionChangedListener(ISelectionChangedListener listener) { + treeViewer.addSelectionChangedListener(listener); + } + + public String getReferenceLanguage() { + return referenceLocale; + } + + public void setReferenceLanguage(String lang) { + this.referenceLocale = lang; + } + + public void bindContentToSelection(boolean enable) { + this.selectiveViewEnabled = enable; + initMatchers(); + } + + public boolean isSelectiveViewEnabled() { + return selectiveViewEnabled; + } + + @Override + public void dispose() { + super.dispose(); + ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); + } + + @Override + public void resourceChanged(IResourceChangeEvent event) { + initMatchers(); + this.refreshViewer(); + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDragSource.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDragSource.java index 5211bff2..a37c91ec 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDragSource.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDragSource.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -24,45 +24,45 @@ public class GlossaryDragSource implements DragSourceListener { - private final TreeViewer source; - private final GlossaryManager manager; - private List<Term> selectionList; + private final TreeViewer source; + private final GlossaryManager manager; + private List<Term> selectionList; - public GlossaryDragSource(TreeViewer sourceView, GlossaryManager manager) { - source = sourceView; - this.manager = manager; - this.selectionList = new ArrayList<Term>(); - } + public GlossaryDragSource(TreeViewer sourceView, GlossaryManager manager) { + source = sourceView; + this.manager = manager; + this.selectionList = new ArrayList<Term>(); + } - @Override - public void dragFinished(DragSourceEvent event) { - GlossaryContentProvider contentProvider = ((GlossaryContentProvider) source - .getContentProvider()); - Glossary glossary = contentProvider.getGlossary(); - for (Term selectionObject : selectionList) - glossary.removeTerm(selectionObject); - manager.setGlossary(glossary); - this.source.refresh(); - try { - manager.saveGlossary(); - } catch (Exception e) { - e.printStackTrace(); - } + @Override + public void dragFinished(DragSourceEvent event) { + GlossaryContentProvider contentProvider = ((GlossaryContentProvider) source + .getContentProvider()); + Glossary glossary = contentProvider.getGlossary(); + for (Term selectionObject : selectionList) + glossary.removeTerm(selectionObject); + manager.setGlossary(glossary); + this.source.refresh(); + try { + manager.saveGlossary(); + } catch (Exception e) { + e.printStackTrace(); } + } - @Override - public void dragSetData(DragSourceEvent event) { - selectionList = new ArrayList<Term>(); - for (Object selectionObject : ((IStructuredSelection) source - .getSelection()).toList()) - selectionList.add((Term) selectionObject); + @Override + public void dragSetData(DragSourceEvent event) { + selectionList = new ArrayList<Term>(); + for (Object selectionObject : ((IStructuredSelection) source + .getSelection()).toList()) + selectionList.add((Term) selectionObject); - event.data = selectionList.toArray(new Term[selectionList.size()]); - } + event.data = selectionList.toArray(new Term[selectionList.size()]); + } - @Override - public void dragStart(DragSourceEvent event) { - event.doit = !source.getSelection().isEmpty(); - } + @Override + public void dragStart(DragSourceEvent event) { + event.doit = !source.getSelection().isEmpty(); + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDropTarget.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDropTarget.java index 46cb8805..278f2534 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDropTarget.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/GlossaryDropTarget.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -21,62 +21,62 @@ import org.eclipselabs.tapiji.translator.views.widgets.provider.GlossaryContentProvider; public class GlossaryDropTarget extends DropTargetAdapter { - private final TreeViewer target; - private final GlossaryManager manager; + private final TreeViewer target; + private final GlossaryManager manager; - public GlossaryDropTarget(TreeViewer viewer, GlossaryManager manager) { - super(); - this.target = viewer; - this.manager = manager; - } + public GlossaryDropTarget(TreeViewer viewer, GlossaryManager manager) { + super(); + this.target = viewer; + this.manager = manager; + } - public void dragEnter(DropTargetEvent event) { - if (event.detail == DND.DROP_MOVE || event.detail == DND.DROP_DEFAULT) { - if ((event.operations & DND.DROP_MOVE) != 0) - event.detail = DND.DROP_MOVE; - else - event.detail = DND.DROP_NONE; - } + public void dragEnter(DropTargetEvent event) { + if (event.detail == DND.DROP_MOVE || event.detail == DND.DROP_DEFAULT) { + if ((event.operations & DND.DROP_MOVE) != 0) + event.detail = DND.DROP_MOVE; + else + event.detail = DND.DROP_NONE; } + } - public void drop(DropTargetEvent event) { - if (TermTransfer.getInstance().isSupportedType(event.currentDataType)) { - Term parentTerm = null; + public void drop(DropTargetEvent event) { + if (TermTransfer.getInstance().isSupportedType(event.currentDataType)) { + Term parentTerm = null; - event.detail = DND.DROP_MOVE; - event.feedback = DND.FEEDBACK_INSERT_AFTER; + event.detail = DND.DROP_MOVE; + event.feedback = DND.FEEDBACK_INSERT_AFTER; - if (event.item instanceof TreeItem - && ((TreeItem) event.item).getData() instanceof Term) { - parentTerm = ((Term) ((TreeItem) event.item).getData()); - } + if (event.item instanceof TreeItem + && ((TreeItem) event.item).getData() instanceof Term) { + parentTerm = ((Term) ((TreeItem) event.item).getData()); + } - Term[] moveTerm = (Term[]) event.data; - Glossary glossary = ((GlossaryContentProvider) target - .getContentProvider()).getGlossary(); + Term[] moveTerm = (Term[]) event.data; + Glossary glossary = ((GlossaryContentProvider) target + .getContentProvider()).getGlossary(); - /* - * Remove the move term from its initial position for (Term - * selectionObject : moveTerm) glossary.removeTerm(selectionObject); - */ + /* + * Remove the move term from its initial position for (Term + * selectionObject : moveTerm) glossary.removeTerm(selectionObject); + */ - /* Insert the move term on its target position */ - if (parentTerm == null) { - for (Term t : moveTerm) - glossary.terms.add(t); - } else { - for (Term t : moveTerm) - parentTerm.subTerms.add(t); - } + /* Insert the move term on its target position */ + if (parentTerm == null) { + for (Term t : moveTerm) + glossary.terms.add(t); + } else { + for (Term t : moveTerm) + parentTerm.subTerms.add(t); + } - manager.setGlossary(glossary); - try { - manager.saveGlossary(); - } catch (Exception e) { - e.printStackTrace(); - } - target.refresh(); - } else - event.detail = DND.DROP_NONE; - } + manager.setGlossary(glossary); + try { + manager.saveGlossary(); + } catch (Exception e) { + e.printStackTrace(); + } + target.refresh(); + } else + event.detail = DND.DROP_NONE; + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/TermTransfer.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/TermTransfer.java index 2dc7c984..8b97b7f4 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/TermTransfer.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/dnd/TermTransfer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -25,91 +25,91 @@ public class TermTransfer extends ByteArrayTransfer { - private static final String TERM = "term"; + private static final String TERM = "term"; - private static final int TYPEID = registerType(TERM); + private static final int TYPEID = registerType(TERM); - private static TermTransfer transfer = new TermTransfer(); + private static TermTransfer transfer = new TermTransfer(); - public static TermTransfer getInstance() { - return transfer; - } + public static TermTransfer getInstance() { + return transfer; + } - public void javaToNative(Object object, TransferData transferData) { - if (!checkType(object) || !isSupportedType(transferData)) { - DND.error(DND.ERROR_INVALID_DATA); - } - Term[] terms = (Term[]) object; - try { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ObjectOutputStream oOut = new ObjectOutputStream(out); - for (int i = 0, length = terms.length; i < length; i++) { - oOut.writeObject(terms[i]); - } - byte[] buffer = out.toByteArray(); - oOut.close(); - - super.javaToNative(buffer, transferData); - } catch (IOException e) { - e.printStackTrace(); - } + public void javaToNative(Object object, TransferData transferData) { + if (!checkType(object) || !isSupportedType(transferData)) { + DND.error(DND.ERROR_INVALID_DATA); } + Term[] terms = (Term[]) object; + try { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ObjectOutputStream oOut = new ObjectOutputStream(out); + for (int i = 0, length = terms.length; i < length; i++) { + oOut.writeObject(terms[i]); + } + byte[] buffer = out.toByteArray(); + oOut.close(); + + super.javaToNative(buffer, transferData); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public Object nativeToJava(TransferData transferData) { + if (isSupportedType(transferData)) { + + byte[] buffer; + try { + buffer = (byte[]) super.nativeToJava(transferData); + } catch (Exception e) { + e.printStackTrace(); + buffer = null; + } + if (buffer == null) + return null; - public Object nativeToJava(TransferData transferData) { - if (isSupportedType(transferData)) { - - byte[] buffer; - try { - buffer = (byte[]) super.nativeToJava(transferData); - } catch (Exception e) { - e.printStackTrace(); - buffer = null; - } - if (buffer == null) - return null; - - List<Term> terms = new ArrayList<Term>(); - try { - ByteArrayInputStream in = new ByteArrayInputStream(buffer); - ObjectInputStream readIn = new ObjectInputStream(in); - // while (readIn.available() > 0) { - Term newTerm = (Term) readIn.readObject(); - terms.add(newTerm); - // } - readIn.close(); - } catch (Exception ex) { - ex.printStackTrace(); - return null; - } - return terms.toArray(new Term[terms.size()]); - } - + List<Term> terms = new ArrayList<Term>(); + try { + ByteArrayInputStream in = new ByteArrayInputStream(buffer); + ObjectInputStream readIn = new ObjectInputStream(in); + // while (readIn.available() > 0) { + Term newTerm = (Term) readIn.readObject(); + terms.add(newTerm); + // } + readIn.close(); + } catch (Exception ex) { + ex.printStackTrace(); return null; + } + return terms.toArray(new Term[terms.size()]); } - protected String[] getTypeNames() { - return new String[] { TERM }; - } + return null; + } - protected int[] getTypeIds() { - return new int[] { TYPEID }; - } + protected String[] getTypeNames() { + return new String[] { TERM }; + } - boolean checkType(Object object) { - if (object == null || !(object instanceof Term[]) - || ((Term[]) object).length == 0) { - return false; - } - Term[] myTypes = (Term[]) object; - for (int i = 0; i < myTypes.length; i++) { - if (myTypes[i] == null) { - return false; - } - } - return true; - } + protected int[] getTypeIds() { + return new int[] { TYPEID }; + } - protected boolean validate(Object object) { - return checkType(object); + boolean checkType(Object object) { + if (object == null || !(object instanceof Term[]) + || ((Term[]) object).length == 0) { + return false; } + Term[] myTypes = (Term[]) object; + for (int i = 0; i < myTypes.length; i++) { + if (myTypes[i] == null) { + return false; + } + } + return true; + } + + protected boolean validate(Object object) { + return checkType(object); + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/ExactMatcher.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/ExactMatcher.java index d31d6bc0..fc87eb01 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/ExactMatcher.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/ExactMatcher.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -18,61 +18,61 @@ public class ExactMatcher extends ViewerFilter { - protected final StructuredViewer viewer; - protected String pattern = ""; - protected StringMatcher matcher; + protected final StructuredViewer viewer; + protected String pattern = ""; + protected StringMatcher matcher; - public ExactMatcher(StructuredViewer viewer) { - this.viewer = viewer; - } + public ExactMatcher(StructuredViewer viewer) { + this.viewer = viewer; + } - public String getPattern() { - return pattern; - } + public String getPattern() { + return pattern; + } - public void setPattern(String p) { - boolean filtering = matcher != null; - if (p != null && p.trim().length() > 0) { - pattern = p; - matcher = new StringMatcher("*" + pattern + "*", true, false); - if (!filtering) - viewer.addFilter(this); - else - viewer.refresh(); - } else { - pattern = ""; - matcher = null; - if (filtering) { - viewer.removeFilter(this); - } - } + public void setPattern(String p) { + boolean filtering = matcher != null; + if (p != null && p.trim().length() > 0) { + pattern = p; + matcher = new StringMatcher("*" + pattern + "*", true, false); + if (!filtering) + viewer.addFilter(this); + else + viewer.refresh(); + } else { + pattern = ""; + matcher = null; + if (filtering) { + viewer.removeFilter(this); + } } + } - @Override - public boolean select(Viewer viewer, Object parentElement, Object element) { - Term term = (Term) element; - FilterInfo filterInfo = new FilterInfo(); - boolean selected = false; + @Override + public boolean select(Viewer viewer, Object parentElement, Object element) { + Term term = (Term) element; + FilterInfo filterInfo = new FilterInfo(); + boolean selected = false; - // Iterate translations - for (Translation translation : term.getAllTranslations()) { - String value = translation.value; - String locale = translation.id; - if (matcher.match(value)) { - filterInfo.addFoundInTranslation(locale); - filterInfo.addSimilarity(locale, 1d); - int start = -1; - while ((start = value.toLowerCase().indexOf( - pattern.toLowerCase(), start + 1)) >= 0) { - filterInfo.addFoundInTranslationRange(locale, start, - pattern.length()); - } - selected = true; - } + // Iterate translations + for (Translation translation : term.getAllTranslations()) { + String value = translation.value; + String locale = translation.id; + if (matcher.match(value)) { + filterInfo.addFoundInTranslation(locale); + filterInfo.addSimilarity(locale, 1d); + int start = -1; + while ((start = value.toLowerCase().indexOf( + pattern.toLowerCase(), start + 1)) >= 0) { + filterInfo.addFoundInTranslationRange(locale, start, + pattern.length()); } - - term.setInfo(filterInfo); - return selected; + selected = true; + } } + term.setInfo(filterInfo); + return selected; + } + } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FilterInfo.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FilterInfo.java index 61a718c3..90867868 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FilterInfo.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FilterInfo.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -19,49 +19,49 @@ public class FilterInfo { - private List<String> foundInTranslation = new ArrayList<String>(); - private Map<String, List<Region>> occurrences = new HashMap<String, List<Region>>(); - private Map<String, Double> localeSimilarity = new HashMap<String, Double>(); + private List<String> foundInTranslation = new ArrayList<String>(); + private Map<String, List<Region>> occurrences = new HashMap<String, List<Region>>(); + private Map<String, Double> localeSimilarity = new HashMap<String, Double>(); - public FilterInfo() { + public FilterInfo() { - } + } - public void addSimilarity(String l, Double similarity) { - localeSimilarity.put(l, similarity); - } + public void addSimilarity(String l, Double similarity) { + localeSimilarity.put(l, similarity); + } - public Double getSimilarityLevel(String l) { - return localeSimilarity.get(l); - } + public Double getSimilarityLevel(String l) { + return localeSimilarity.get(l); + } - public void addFoundInTranslation(String loc) { - foundInTranslation.add(loc); - } + public void addFoundInTranslation(String loc) { + foundInTranslation.add(loc); + } - public void removeFoundInTranslation(String loc) { - foundInTranslation.remove(loc); - } + public void removeFoundInTranslation(String loc) { + foundInTranslation.remove(loc); + } - public void clearFoundInTranslation() { - foundInTranslation.clear(); - } + public void clearFoundInTranslation() { + foundInTranslation.clear(); + } - public boolean hasFoundInTranslation(String l) { - return foundInTranslation.contains(l); - } + public boolean hasFoundInTranslation(String l) { + return foundInTranslation.contains(l); + } - public List<Region> getFoundInTranslationRanges(String locale) { - List<Region> reg = occurrences.get(locale); - return (reg == null ? new ArrayList<Region>() : reg); - } + public List<Region> getFoundInTranslationRanges(String locale) { + List<Region> reg = occurrences.get(locale); + return (reg == null ? new ArrayList<Region>() : reg); + } - public void addFoundInTranslationRange(String locale, int start, int length) { - List<Region> regions = occurrences.get(locale); - if (regions == null) - regions = new ArrayList<Region>(); - regions.add(new Region(start, length)); - occurrences.put(locale, regions); - } + public void addFoundInTranslationRange(String locale, int start, int length) { + List<Region> regions = occurrences.get(locale); + if (regions == null) + regions = new ArrayList<Region>(); + regions.add(new Region(start, length)); + occurrences.put(locale, regions); + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java index 9344aa9d..3e7e03d8 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/FuzzyMatcher.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -19,48 +19,48 @@ public class FuzzyMatcher extends ExactMatcher { - protected ILevenshteinDistanceAnalyzer lvda; - protected float minimumSimilarity = 0.75f; + protected ILevenshteinDistanceAnalyzer lvda; + protected float minimumSimilarity = 0.75f; - public FuzzyMatcher(StructuredViewer viewer) { - super(viewer); - lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer(); - } + public FuzzyMatcher(StructuredViewer viewer) { + super(viewer); + lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer(); + } - public double getMinimumSimilarity() { - return minimumSimilarity; - } + public double getMinimumSimilarity() { + return minimumSimilarity; + } - public void setMinimumSimilarity(float similarity) { - this.minimumSimilarity = similarity; - } + public void setMinimumSimilarity(float similarity) { + this.minimumSimilarity = similarity; + } - @Override - public boolean select(Viewer viewer, Object parentElement, Object element) { - boolean exactMatch = super.select(viewer, parentElement, element); - boolean match = exactMatch; + @Override + public boolean select(Viewer viewer, Object parentElement, Object element) { + boolean exactMatch = super.select(viewer, parentElement, element); + boolean match = exactMatch; - Term term = (Term) element; + Term term = (Term) element; - FilterInfo filterInfo = (FilterInfo) term.getInfo(); + FilterInfo filterInfo = (FilterInfo) term.getInfo(); - for (Translation translation : term.getAllTranslations()) { - String value = translation.value; - String locale = translation.id; - if (filterInfo.hasFoundInTranslation(locale)) - continue; - double dist = lvda.analyse(value, getPattern()); - if (dist >= minimumSimilarity) { - filterInfo.addFoundInTranslation(locale); - filterInfo.addSimilarity(locale, dist); - match = true; - filterInfo - .addFoundInTranslationRange(locale, 0, value.length()); - } - } - - term.setInfo(filterInfo); - return match; + for (Translation translation : term.getAllTranslations()) { + String value = translation.value; + String locale = translation.id; + if (filterInfo.hasFoundInTranslation(locale)) + continue; + double dist = lvda.analyse(value, getPattern()); + if (dist >= minimumSimilarity) { + filterInfo.addFoundInTranslation(locale); + filterInfo.addSimilarity(locale, dist); + match = true; + filterInfo + .addFoundInTranslationRange(locale, 0, value.length()); + } } + term.setInfo(filterInfo); + return match; + } + } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/SelectiveMatcher.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/SelectiveMatcher.java index 58b6224c..399b0f07 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/SelectiveMatcher.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/SelectiveMatcher.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -27,83 +27,83 @@ import org.eclipselabs.tapiji.translator.model.Translation; public class SelectiveMatcher extends ViewerFilter implements - ISelectionListener, ISelectionChangedListener { - - protected final StructuredViewer viewer; - protected String pattern = ""; - protected StringMatcher matcher; - protected IKeyTreeNode selectedItem; - protected IWorkbenchPage page; - - public SelectiveMatcher(StructuredViewer viewer, IWorkbenchPage page) { - this.viewer = viewer; - if (page.getActiveEditor() != null) { - this.selectedItem = EditorUtil.getSelectedKeyTreeNode(page); - } + ISelectionListener, ISelectionChangedListener { + + protected final StructuredViewer viewer; + protected String pattern = ""; + protected StringMatcher matcher; + protected IKeyTreeNode selectedItem; + protected IWorkbenchPage page; + + public SelectiveMatcher(StructuredViewer viewer, IWorkbenchPage page) { + this.viewer = viewer; + if (page.getActiveEditor() != null) { + this.selectedItem = EditorUtil.getSelectedKeyTreeNode(page); + } - this.page = page; - page.getWorkbenchWindow().getSelectionService() - .addSelectionListener(this); + this.page = page; + page.getWorkbenchWindow().getSelectionService() + .addSelectionListener(this); - viewer.addFilter(this); - viewer.refresh(); - } + viewer.addFilter(this); + viewer.refresh(); + } - @Override - public boolean select(Viewer viewer, Object parentElement, Object element) { - if (selectedItem == null) - return false; - - Term term = (Term) element; - FilterInfo filterInfo = new FilterInfo(); - boolean selected = false; - - // Iterate translations - for (Translation translation : term.getAllTranslations()) { - String value = translation.value; - - if (value.trim().length() == 0) - continue; - - String locale = translation.id; - - for (IMessage entry : selectedItem.getMessagesBundleGroup() - .getMessages(selectedItem.getMessageKey())) { - String ev = entry.getValue(); - String[] subValues = ev.split("[\\s\\p{Punct}]+"); - for (String v : subValues) { - if (v.trim().equalsIgnoreCase(value.trim())) - return true; - } - } - } + @Override + public boolean select(Viewer viewer, Object parentElement, Object element) { + if (selectedItem == null) + return false; - return false; - } + Term term = (Term) element; + FilterInfo filterInfo = new FilterInfo(); + boolean selected = false; + + // Iterate translations + for (Translation translation : term.getAllTranslations()) { + String value = translation.value; - @Override - public void selectionChanged(IWorkbenchPart part, ISelection selection) { - try { - if (selection.isEmpty()) - return; + if (value.trim().length() == 0) + continue; - if (!(selection instanceof IStructuredSelection)) - return; + String locale = translation.id; - IStructuredSelection sel = (IStructuredSelection) selection; - selectedItem = (IKeyTreeNode) sel.iterator().next(); - viewer.refresh(); - } catch (Exception e) { + for (IMessage entry : selectedItem.getMessagesBundleGroup() + .getMessages(selectedItem.getMessageKey())) { + String ev = entry.getValue(); + String[] subValues = ev.split("[\\s\\p{Punct}]+"); + for (String v : subValues) { + if (v.trim().equalsIgnoreCase(value.trim())) + return true; } + } } - @Override - public void selectionChanged(SelectionChangedEvent event) { - event.getSelection(); - } + return false; + } + + @Override + public void selectionChanged(IWorkbenchPart part, ISelection selection) { + try { + if (selection.isEmpty()) + return; + + if (!(selection instanceof IStructuredSelection)) + return; - public void dispose() { - page.getWorkbenchWindow().getSelectionService() - .removeSelectionListener(this); + IStructuredSelection sel = (IStructuredSelection) selection; + selectedItem = (IKeyTreeNode) sel.iterator().next(); + viewer.refresh(); + } catch (Exception e) { } + } + + @Override + public void selectionChanged(SelectionChangedEvent event) { + event.getSelection(); + } + + public void dispose() { + page.getWorkbenchWindow().getSelectionService() + .removeSelectionListener(this); + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/StringMatcher.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/StringMatcher.java index 39865904..d07c0aa2 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/StringMatcher.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/filter/StringMatcher.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -16,481 +16,481 @@ * A string pattern matcher, suppporting "*" and "?" wildcards. */ public class StringMatcher { - protected String fPattern; + protected String fPattern; - protected int fLength; // pattern length + protected int fLength; // pattern length - protected boolean fIgnoreWildCards; + protected boolean fIgnoreWildCards; - protected boolean fIgnoreCase; + protected boolean fIgnoreCase; - protected boolean fHasLeadingStar; + protected boolean fHasLeadingStar; - protected boolean fHasTrailingStar; + protected boolean fHasTrailingStar; - protected String fSegments[]; // the given pattern is split into * separated - // segments + protected String fSegments[]; // the given pattern is split into * separated + // segments - /* boundary value beyond which we don't need to search in the text */ - protected int fBound = 0; + /* boundary value beyond which we don't need to search in the text */ + protected int fBound = 0; - protected static final char fSingleWildCard = '\u0000'; + protected static final char fSingleWildCard = '\u0000'; - public static class Position { - int start; // inclusive + public static class Position { + int start; // inclusive - int end; // exclusive + int end; // exclusive - public Position(int start, int end) { - this.start = start; - this.end = end; - } - - public int getStart() { - return start; - } - - public int getEnd() { - return end; - } + public Position(int start, int end) { + this.start = start; + this.end = end; } - /** - * StringMatcher constructor takes in a String object that is a simple - * pattern which may contain '*' for 0 and many characters and '?' for - * exactly one character. - * - * Literal '*' and '?' characters must be escaped in the pattern e.g., - * "\*" means literal "*", etc. - * - * Escaping any other character (including the escape character itself), - * just results in that character in the pattern. e.g., "\a" means "a" and - * "\\" means "\" - * - * If invoking the StringMatcher with string literals in Java, don't forget - * escape characters are represented by "\\". - * - * @param pattern - * the pattern to match text against - * @param ignoreCase - * if true, case is ignored - * @param ignoreWildCards - * if true, wild cards and their escape sequences are ignored - * (everything is taken literally). - */ - public StringMatcher(String pattern, boolean ignoreCase, - boolean ignoreWildCards) { - if (pattern == null) { - throw new IllegalArgumentException(); - } - fIgnoreCase = ignoreCase; - fIgnoreWildCards = ignoreWildCards; - fPattern = pattern; - fLength = pattern.length(); - - if (fIgnoreWildCards) { - parseNoWildCards(); - } else { - parseWildCards(); - } + public int getStart() { + return start; } - /** - * Find the first occurrence of the pattern between <code>start</code - * )(inclusive) and <code>end</code>(exclusive). - * - * @param text - * the String object to search in - * @param start - * the starting index of the search range, inclusive - * @param end - * the ending index of the search range, exclusive - * @return an <code>StringMatcher.Position</code> object that keeps the - * starting (inclusive) and ending positions (exclusive) of the - * first occurrence of the pattern in the specified range of the - * text; return null if not found or subtext is empty (start==end). - * A pair of zeros is returned if pattern is empty string Note that - * for pattern like "*abc*" with leading and trailing stars, - * position of "abc" is returned. For a pattern like"*??*" in text - * "abcdf", (1,3) is returned - */ - public StringMatcher.Position find(String text, int start, int end) { - if (text == null) { - throw new IllegalArgumentException(); - } + public int getEnd() { + return end; + } + } + + /** + * StringMatcher constructor takes in a String object that is a simple + * pattern which may contain '*' for 0 and many characters and '?' for + * exactly one character. + * + * Literal '*' and '?' characters must be escaped in the pattern e.g., + * "\*" means literal "*", etc. + * + * Escaping any other character (including the escape character itself), + * just results in that character in the pattern. e.g., "\a" means "a" and + * "\\" means "\" + * + * If invoking the StringMatcher with string literals in Java, don't forget + * escape characters are represented by "\\". + * + * @param pattern + * the pattern to match text against + * @param ignoreCase + * if true, case is ignored + * @param ignoreWildCards + * if true, wild cards and their escape sequences are ignored + * (everything is taken literally). + */ + public StringMatcher(String pattern, boolean ignoreCase, + boolean ignoreWildCards) { + if (pattern == null) { + throw new IllegalArgumentException(); + } + fIgnoreCase = ignoreCase; + fIgnoreWildCards = ignoreWildCards; + fPattern = pattern; + fLength = pattern.length(); + + if (fIgnoreWildCards) { + parseNoWildCards(); + } else { + parseWildCards(); + } + } + + /** + * Find the first occurrence of the pattern between <code>start</code + * )(inclusive) and <code>end</code>(exclusive). + * + * @param text + * the String object to search in + * @param start + * the starting index of the search range, inclusive + * @param end + * the ending index of the search range, exclusive + * @return an <code>StringMatcher.Position</code> object that keeps the + * starting (inclusive) and ending positions (exclusive) of the + * first occurrence of the pattern in the specified range of the + * text; return null if not found or subtext is empty (start==end). + * A pair of zeros is returned if pattern is empty string Note that + * for pattern like "*abc*" with leading and trailing stars, + * position of "abc" is returned. For a pattern like"*??*" in text + * "abcdf", (1,3) is returned + */ + public StringMatcher.Position find(String text, int start, int end) { + if (text == null) { + throw new IllegalArgumentException(); + } - int tlen = text.length(); - if (start < 0) { - start = 0; - } - if (end > tlen) { - end = tlen; - } - if (end < 0 || start >= end) { - return null; - } - if (fLength == 0) { - return new Position(start, start); - } - if (fIgnoreWildCards) { - int x = posIn(text, start, end); - if (x < 0) { - return null; - } - return new Position(x, x + fLength); - } + int tlen = text.length(); + if (start < 0) { + start = 0; + } + if (end > tlen) { + end = tlen; + } + if (end < 0 || start >= end) { + return null; + } + if (fLength == 0) { + return new Position(start, start); + } + if (fIgnoreWildCards) { + int x = posIn(text, start, end); + if (x < 0) { + return null; + } + return new Position(x, x + fLength); + } - int segCount = fSegments.length; - if (segCount == 0) { - return new Position(start, end); - } + int segCount = fSegments.length; + if (segCount == 0) { + return new Position(start, end); + } - int curPos = start; - int matchStart = -1; - int i; - for (i = 0; i < segCount && curPos < end; ++i) { - String current = fSegments[i]; - int nextMatch = regExpPosIn(text, curPos, end, current); - if (nextMatch < 0) { - return null; - } - if (i == 0) { - matchStart = nextMatch; - } - curPos = nextMatch + current.length(); - } - if (i < segCount) { - return null; - } - return new Position(matchStart, curPos); - } - - /** - * match the given <code>text</code> with the pattern - * - * @return true if matched otherwise false - * @param text - * a String object - */ - public boolean match(String text) { - if (text == null) { - return false; - } - return match(text, 0, text.length()); - } - - /** - * Given the starting (inclusive) and the ending (exclusive) positions in - * the <code>text</code>, determine if the given substring matches with - * aPattern - * - * @return true if the specified portion of the text matches the pattern - * @param text - * a String object that contains the substring to match - * @param start - * marks the starting position (inclusive) of the substring - * @param end - * marks the ending index (exclusive) of the substring - */ - public boolean match(String text, int start, int end) { - if (null == text) { - throw new IllegalArgumentException(); - } + int curPos = start; + int matchStart = -1; + int i; + for (i = 0; i < segCount && curPos < end; ++i) { + String current = fSegments[i]; + int nextMatch = regExpPosIn(text, curPos, end, current); + if (nextMatch < 0) { + return null; + } + if (i == 0) { + matchStart = nextMatch; + } + curPos = nextMatch + current.length(); + } + if (i < segCount) { + return null; + } + return new Position(matchStart, curPos); + } + + /** + * match the given <code>text</code> with the pattern + * + * @return true if matched otherwise false + * @param text + * a String object + */ + public boolean match(String text) { + if (text == null) { + return false; + } + return match(text, 0, text.length()); + } + + /** + * Given the starting (inclusive) and the ending (exclusive) positions in + * the <code>text</code>, determine if the given substring matches with + * aPattern + * + * @return true if the specified portion of the text matches the pattern + * @param text + * a String object that contains the substring to match + * @param start + * marks the starting position (inclusive) of the substring + * @param end + * marks the ending index (exclusive) of the substring + */ + public boolean match(String text, int start, int end) { + if (null == text) { + throw new IllegalArgumentException(); + } - if (start > end) { - return false; - } + if (start > end) { + return false; + } - if (fIgnoreWildCards) { - return (end - start == fLength) - && fPattern.regionMatches(fIgnoreCase, 0, text, start, - fLength); - } - int segCount = fSegments.length; - if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) { - return true; - } - if (start == end) { - return fLength == 0; - } - if (fLength == 0) { - return start == end; - } + if (fIgnoreWildCards) { + return (end - start == fLength) + && fPattern.regionMatches(fIgnoreCase, 0, text, start, + fLength); + } + int segCount = fSegments.length; + if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) { + return true; + } + if (start == end) { + return fLength == 0; + } + if (fLength == 0) { + return start == end; + } - int tlen = text.length(); - if (start < 0) { - start = 0; - } - if (end > tlen) { - end = tlen; - } + int tlen = text.length(); + if (start < 0) { + start = 0; + } + if (end > tlen) { + end = tlen; + } - int tCurPos = start; - int bound = end - fBound; - if (bound < 0) { - return false; - } - int i = 0; - String current = fSegments[i]; - int segLength = current.length(); - - /* process first segment */ - if (!fHasLeadingStar) { - if (!regExpRegionMatches(text, start, current, 0, segLength)) { - return false; - } else { - ++i; - tCurPos = tCurPos + segLength; - } - } - if ((fSegments.length == 1) && (!fHasLeadingStar) - && (!fHasTrailingStar)) { - // only one segment to match, no wildcards specified - return tCurPos == end; - } - /* process middle segments */ - while (i < segCount) { - current = fSegments[i]; - int currentMatch; - int k = current.indexOf(fSingleWildCard); - if (k < 0) { - currentMatch = textPosIn(text, tCurPos, end, current); - if (currentMatch < 0) { - return false; - } - } else { - currentMatch = regExpPosIn(text, tCurPos, end, current); - if (currentMatch < 0) { - return false; - } - } - tCurPos = currentMatch + current.length(); - i++; - } + int tCurPos = start; + int bound = end - fBound; + if (bound < 0) { + return false; + } + int i = 0; + String current = fSegments[i]; + int segLength = current.length(); + + /* process first segment */ + if (!fHasLeadingStar) { + if (!regExpRegionMatches(text, start, current, 0, segLength)) { + return false; + } else { + ++i; + tCurPos = tCurPos + segLength; + } + } + if ((fSegments.length == 1) && (!fHasLeadingStar) + && (!fHasTrailingStar)) { + // only one segment to match, no wildcards specified + return tCurPos == end; + } + /* process middle segments */ + while (i < segCount) { + current = fSegments[i]; + int currentMatch; + int k = current.indexOf(fSingleWildCard); + if (k < 0) { + currentMatch = textPosIn(text, tCurPos, end, current); + if (currentMatch < 0) { + return false; + } + } else { + currentMatch = regExpPosIn(text, tCurPos, end, current); + if (currentMatch < 0) { + return false; + } + } + tCurPos = currentMatch + current.length(); + i++; + } - /* process final segment */ - if (!fHasTrailingStar && tCurPos != end) { - int clen = current.length(); - return regExpRegionMatches(text, end - clen, current, 0, clen); - } - return i == segCount; - } - - /** - * This method parses the given pattern into segments seperated by wildcard - * '*' characters. Since wildcards are not being used in this case, the - * pattern consists of a single segment. - */ - private void parseNoWildCards() { - fSegments = new String[1]; - fSegments[0] = fPattern; - fBound = fLength; - } - - /** - * Parses the given pattern into segments seperated by wildcard '*' - * characters. - * - * @param p - * , a String object that is a simple regular expression with '*' - * and/or '?' - */ - private void parseWildCards() { - if (fPattern.startsWith("*")) { //$NON-NLS-1$ - fHasLeadingStar = true; - } - if (fPattern.endsWith("*")) {//$NON-NLS-1$ - /* make sure it's not an escaped wildcard */ - if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') { - fHasTrailingStar = true; - } - } + /* process final segment */ + if (!fHasTrailingStar && tCurPos != end) { + int clen = current.length(); + return regExpRegionMatches(text, end - clen, current, 0, clen); + } + return i == segCount; + } + + /** + * This method parses the given pattern into segments seperated by wildcard + * '*' characters. Since wildcards are not being used in this case, the + * pattern consists of a single segment. + */ + private void parseNoWildCards() { + fSegments = new String[1]; + fSegments[0] = fPattern; + fBound = fLength; + } + + /** + * Parses the given pattern into segments seperated by wildcard '*' + * characters. + * + * @param p + * , a String object that is a simple regular expression with '*' + * and/or '?' + */ + private void parseWildCards() { + if (fPattern.startsWith("*")) { //$NON-NLS-1$ + fHasLeadingStar = true; + } + if (fPattern.endsWith("*")) {//$NON-NLS-1$ + /* make sure it's not an escaped wildcard */ + if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') { + fHasTrailingStar = true; + } + } - Vector temp = new Vector(); - - int pos = 0; - StringBuffer buf = new StringBuffer(); - while (pos < fLength) { - char c = fPattern.charAt(pos++); - switch (c) { - case '\\': - if (pos >= fLength) { - buf.append(c); - } else { - char next = fPattern.charAt(pos++); - /* if it's an escape sequence */ - if (next == '*' || next == '?' || next == '\\') { - buf.append(next); - } else { - /* not an escape sequence, just insert literally */ - buf.append(c); - buf.append(next); - } - } - break; - case '*': - if (buf.length() > 0) { - /* new segment */ - temp.addElement(buf.toString()); - fBound += buf.length(); - buf.setLength(0); - } - break; - case '?': - /* append special character representing single match wildcard */ - buf.append(fSingleWildCard); - break; - default: - buf.append(c); - } - } + Vector temp = new Vector(); - /* add last buffer to segment list */ + int pos = 0; + StringBuffer buf = new StringBuffer(); + while (pos < fLength) { + char c = fPattern.charAt(pos++); + switch (c) { + case '\\': + if (pos >= fLength) { + buf.append(c); + } else { + char next = fPattern.charAt(pos++); + /* if it's an escape sequence */ + if (next == '*' || next == '?' || next == '\\') { + buf.append(next); + } else { + /* not an escape sequence, just insert literally */ + buf.append(c); + buf.append(next); + } + } + break; + case '*': if (buf.length() > 0) { - temp.addElement(buf.toString()); - fBound += buf.length(); - } - - fSegments = new String[temp.size()]; - temp.copyInto(fSegments); - } - - /** - * @param text - * a string which contains no wildcard - * @param start - * the starting index in the text for search, inclusive - * @param end - * the stopping point of search, exclusive - * @return the starting index in the text of the pattern , or -1 if not - * found - */ - protected int posIn(String text, int start, int end) {// no wild card in - // pattern - int max = end - fLength; - - if (!fIgnoreCase) { - int i = text.indexOf(fPattern, start); - if (i == -1 || i > max) { - return -1; - } - return i; - } - - for (int i = start; i <= max; ++i) { - if (text.regionMatches(true, i, fPattern, 0, fLength)) { - return i; - } - } + /* new segment */ + temp.addElement(buf.toString()); + fBound += buf.length(); + buf.setLength(0); + } + break; + case '?': + /* append special character representing single match wildcard */ + buf.append(fSingleWildCard); + break; + default: + buf.append(c); + } + } - return -1; + /* add last buffer to segment list */ + if (buf.length() > 0) { + temp.addElement(buf.toString()); + fBound += buf.length(); } - /** - * @param text - * a simple regular expression that may only contain '?'(s) - * @param start - * the starting index in the text for search, inclusive - * @param end - * the stopping point of search, exclusive - * @param p - * a simple regular expression that may contains '?' - * @return the starting index in the text of the pattern , or -1 if not - * found - */ - protected int regExpPosIn(String text, int start, int end, String p) { - int plen = p.length(); - - int max = end - plen; - for (int i = start; i <= max; ++i) { - if (regExpRegionMatches(text, i, p, 0, plen)) { - return i; - } - } + fSegments = new String[temp.size()]; + temp.copyInto(fSegments); + } + + /** + * @param text + * a string which contains no wildcard + * @param start + * the starting index in the text for search, inclusive + * @param end + * the stopping point of search, exclusive + * @return the starting index in the text of the pattern , or -1 if not + * found + */ + protected int posIn(String text, int start, int end) {// no wild card in + // pattern + int max = end - fLength; + + if (!fIgnoreCase) { + int i = text.indexOf(fPattern, start); + if (i == -1 || i > max) { return -1; + } + return i; } - /** - * - * @return boolean - * @param text - * a String to match - * @param start - * int that indicates the starting index of match, inclusive - * @param end - * </code> int that indicates the ending index of match, - * exclusive - * @param p - * String, String, a simple regular expression that may contain - * '?' - * @param ignoreCase - * boolean indicating wether code>p</code> is case sensitive - */ - protected boolean regExpRegionMatches(String text, int tStart, String p, - int pStart, int plen) { - while (plen-- > 0) { - char tchar = text.charAt(tStart++); - char pchar = p.charAt(pStart++); - - /* process wild cards */ - if (!fIgnoreWildCards) { - /* skip single wild cards */ - if (pchar == fSingleWildCard) { - continue; - } - } - if (pchar == tchar) { - continue; - } - if (fIgnoreCase) { - if (Character.toUpperCase(tchar) == Character - .toUpperCase(pchar)) { - continue; - } - // comparing after converting to upper case doesn't handle all - // cases; - // also compare after converting to lower case - if (Character.toLowerCase(tchar) == Character - .toLowerCase(pchar)) { - continue; - } - } - return false; - } - return true; - } - - /** - * @param text - * the string to match - * @param start - * the starting index in the text for search, inclusive - * @param end - * the stopping point of search, exclusive - * @param p - * a pattern string that has no wildcard - * @return the starting index in the text of the pattern , or -1 if not - * found - */ - protected int textPosIn(String text, int start, int end, String p) { - - int plen = p.length(); - int max = end - plen; - - if (!fIgnoreCase) { - int i = text.indexOf(p, start); - if (i == -1 || i > max) { - return -1; - } - return i; - } - - for (int i = start; i <= max; ++i) { - if (text.regionMatches(true, i, p, 0, plen)) { - return i; - } - } + for (int i = start; i <= max; ++i) { + if (text.regionMatches(true, i, fPattern, 0, fLength)) { + return i; + } + } + return -1; + } + + /** + * @param text + * a simple regular expression that may only contain '?'(s) + * @param start + * the starting index in the text for search, inclusive + * @param end + * the stopping point of search, exclusive + * @param p + * a simple regular expression that may contains '?' + * @return the starting index in the text of the pattern , or -1 if not + * found + */ + protected int regExpPosIn(String text, int start, int end, String p) { + int plen = p.length(); + + int max = end - plen; + for (int i = start; i <= max; ++i) { + if (regExpRegionMatches(text, i, p, 0, plen)) { + return i; + } + } + return -1; + } + + /** + * + * @return boolean + * @param text + * a String to match + * @param start + * int that indicates the starting index of match, inclusive + * @param end + * </code> int that indicates the ending index of match, + * exclusive + * @param p + * String, String, a simple regular expression that may contain + * '?' + * @param ignoreCase + * boolean indicating wether code>p</code> is case sensitive + */ + protected boolean regExpRegionMatches(String text, int tStart, String p, + int pStart, int plen) { + while (plen-- > 0) { + char tchar = text.charAt(tStart++); + char pchar = p.charAt(pStart++); + + /* process wild cards */ + if (!fIgnoreWildCards) { + /* skip single wild cards */ + if (pchar == fSingleWildCard) { + continue; + } + } + if (pchar == tchar) { + continue; + } + if (fIgnoreCase) { + if (Character.toUpperCase(tchar) == Character + .toUpperCase(pchar)) { + continue; + } + // comparing after converting to upper case doesn't handle all + // cases; + // also compare after converting to lower case + if (Character.toLowerCase(tchar) == Character + .toLowerCase(pchar)) { + continue; + } + } + return false; + } + return true; + } + + /** + * @param text + * the string to match + * @param start + * the starting index in the text for search, inclusive + * @param end + * the stopping point of search, exclusive + * @param p + * a pattern string that has no wildcard + * @return the starting index in the text of the pattern , or -1 if not + * found + */ + protected int textPosIn(String text, int start, int end, String p) { + + int plen = p.length(); + int max = end - plen; + + if (!fIgnoreCase) { + int i = text.indexOf(p, start); + if (i == -1 || i > max) { return -1; + } + return i; } + + for (int i = start; i <= max; ++i) { + if (text.regionMatches(true, i, p, 0, plen)) { + return i; + } + } + + return -1; + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/model/GlossaryViewState.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/model/GlossaryViewState.java index d7781fed..c358018c 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/model/GlossaryViewState.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/model/GlossaryViewState.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -19,203 +19,203 @@ public class GlossaryViewState { - private static final String TAG_GLOSSARY_FILE = "glossary_file"; - private static final String TAG_FUZZY_MATCHING = "fuzzy_matching"; - private static final String TAG_SELECTIVE_VIEW = "selective_content"; - private static final String TAG_DISPLAYED_LOCALES = "displayed_locales"; - private static final String TAG_LOCALE = "locale"; - private static final String TAG_REFERENCE_LANG = "reference_language"; - private static final String TAG_MATCHING_PRECISION = "matching_precision"; - private static final String TAG_ENABLED = "enabled"; - private static final String TAG_VALUE = "value"; - private static final String TAG_SEARCH_STRING = "search_string"; - private static final String TAG_EDITABLE = "editable"; - - private SortInfo sortings; - private boolean fuzzyMatchingEnabled; - private boolean selectiveViewEnabled; - private float matchingPrecision = .75f; - private String searchString; - private boolean editable; - private String glossaryFile; - private String referenceLanguage; - private List<String> displayLanguages; - - public void saveState(IMemento memento) { - try { - if (memento == null) - return; - - if (sortings != null) { - sortings.saveState(memento); - } - - IMemento memFuzzyMatching = memento.createChild(TAG_FUZZY_MATCHING); - memFuzzyMatching.putBoolean(TAG_ENABLED, fuzzyMatchingEnabled); - - IMemento memSelectiveView = memento.createChild(TAG_SELECTIVE_VIEW); - memSelectiveView.putBoolean(TAG_ENABLED, selectiveViewEnabled); - - IMemento memMatchingPrec = memento - .createChild(TAG_MATCHING_PRECISION); - memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision); - - IMemento memSStr = memento.createChild(TAG_SEARCH_STRING); - memSStr.putString(TAG_VALUE, searchString); - - IMemento memEditable = memento.createChild(TAG_EDITABLE); - memEditable.putBoolean(TAG_ENABLED, editable); - - IMemento memRefLang = memento.createChild(TAG_REFERENCE_LANG); - memRefLang.putString(TAG_VALUE, referenceLanguage); - - IMemento memGlossaryFile = memento.createChild(TAG_GLOSSARY_FILE); - memGlossaryFile.putString(TAG_VALUE, glossaryFile); - - IMemento memDispLoc = memento.createChild(TAG_DISPLAYED_LOCALES); - if (displayLanguages != null) { - for (String lang : displayLanguages) { - IMemento memLoc = memDispLoc.createChild(TAG_LOCALE); - memLoc.putString(TAG_VALUE, lang); - } - } - } catch (Exception e) { - + private static final String TAG_GLOSSARY_FILE = "glossary_file"; + private static final String TAG_FUZZY_MATCHING = "fuzzy_matching"; + private static final String TAG_SELECTIVE_VIEW = "selective_content"; + private static final String TAG_DISPLAYED_LOCALES = "displayed_locales"; + private static final String TAG_LOCALE = "locale"; + private static final String TAG_REFERENCE_LANG = "reference_language"; + private static final String TAG_MATCHING_PRECISION = "matching_precision"; + private static final String TAG_ENABLED = "enabled"; + private static final String TAG_VALUE = "value"; + private static final String TAG_SEARCH_STRING = "search_string"; + private static final String TAG_EDITABLE = "editable"; + + private SortInfo sortings; + private boolean fuzzyMatchingEnabled; + private boolean selectiveViewEnabled; + private float matchingPrecision = .75f; + private String searchString; + private boolean editable; + private String glossaryFile; + private String referenceLanguage; + private List<String> displayLanguages; + + public void saveState(IMemento memento) { + try { + if (memento == null) + return; + + if (sortings != null) { + sortings.saveState(memento); + } + + IMemento memFuzzyMatching = memento.createChild(TAG_FUZZY_MATCHING); + memFuzzyMatching.putBoolean(TAG_ENABLED, fuzzyMatchingEnabled); + + IMemento memSelectiveView = memento.createChild(TAG_SELECTIVE_VIEW); + memSelectiveView.putBoolean(TAG_ENABLED, selectiveViewEnabled); + + IMemento memMatchingPrec = memento + .createChild(TAG_MATCHING_PRECISION); + memMatchingPrec.putFloat(TAG_VALUE, matchingPrecision); + + IMemento memSStr = memento.createChild(TAG_SEARCH_STRING); + memSStr.putString(TAG_VALUE, searchString); + + IMemento memEditable = memento.createChild(TAG_EDITABLE); + memEditable.putBoolean(TAG_ENABLED, editable); + + IMemento memRefLang = memento.createChild(TAG_REFERENCE_LANG); + memRefLang.putString(TAG_VALUE, referenceLanguage); + + IMemento memGlossaryFile = memento.createChild(TAG_GLOSSARY_FILE); + memGlossaryFile.putString(TAG_VALUE, glossaryFile); + + IMemento memDispLoc = memento.createChild(TAG_DISPLAYED_LOCALES); + if (displayLanguages != null) { + for (String lang : displayLanguages) { + IMemento memLoc = memDispLoc.createChild(TAG_LOCALE); + memLoc.putString(TAG_VALUE, lang); } - } + } + } catch (Exception e) { - public void init(IMemento memento) { - try { - if (memento == null) - return; + } + } - if (sortings == null) - sortings = new SortInfo(); - sortings.init(memento); + public void init(IMemento memento) { + try { + if (memento == null) + return; - IMemento mFuzzyMatching = memento.getChild(TAG_FUZZY_MATCHING); - if (mFuzzyMatching != null) - fuzzyMatchingEnabled = mFuzzyMatching.getBoolean(TAG_ENABLED); + if (sortings == null) + sortings = new SortInfo(); + sortings.init(memento); - IMemento mSelectiveView = memento.getChild(TAG_SELECTIVE_VIEW); - if (mSelectiveView != null) - selectiveViewEnabled = mSelectiveView.getBoolean(TAG_ENABLED); + IMemento mFuzzyMatching = memento.getChild(TAG_FUZZY_MATCHING); + if (mFuzzyMatching != null) + fuzzyMatchingEnabled = mFuzzyMatching.getBoolean(TAG_ENABLED); - IMemento mMP = memento.getChild(TAG_MATCHING_PRECISION); - if (mMP != null) - matchingPrecision = mMP.getFloat(TAG_VALUE); + IMemento mSelectiveView = memento.getChild(TAG_SELECTIVE_VIEW); + if (mSelectiveView != null) + selectiveViewEnabled = mSelectiveView.getBoolean(TAG_ENABLED); - IMemento mSStr = memento.getChild(TAG_SEARCH_STRING); - if (mSStr != null) - searchString = mSStr.getString(TAG_VALUE); + IMemento mMP = memento.getChild(TAG_MATCHING_PRECISION); + if (mMP != null) + matchingPrecision = mMP.getFloat(TAG_VALUE); - IMemento mEditable = memento.getChild(TAG_EDITABLE); - if (mEditable != null) - editable = mEditable.getBoolean(TAG_ENABLED); + IMemento mSStr = memento.getChild(TAG_SEARCH_STRING); + if (mSStr != null) + searchString = mSStr.getString(TAG_VALUE); - IMemento mRefLang = memento.getChild(TAG_REFERENCE_LANG); - if (mRefLang != null) - referenceLanguage = mRefLang.getString(TAG_VALUE); + IMemento mEditable = memento.getChild(TAG_EDITABLE); + if (mEditable != null) + editable = mEditable.getBoolean(TAG_ENABLED); - IMemento mGlossaryFile = memento.getChild(TAG_GLOSSARY_FILE); - if (mGlossaryFile != null) - glossaryFile = mGlossaryFile.getString(TAG_VALUE); + IMemento mRefLang = memento.getChild(TAG_REFERENCE_LANG); + if (mRefLang != null) + referenceLanguage = mRefLang.getString(TAG_VALUE); - IMemento memDispLoc = memento.getChild(TAG_DISPLAYED_LOCALES); - if (memDispLoc != null) { - displayLanguages = new ArrayList<String>(); - for (IMemento locale : memDispLoc.getChildren(TAG_LOCALE)) { - displayLanguages.add(locale.getString(TAG_VALUE)); - } - } - } catch (Exception e) { + IMemento mGlossaryFile = memento.getChild(TAG_GLOSSARY_FILE); + if (mGlossaryFile != null) + glossaryFile = mGlossaryFile.getString(TAG_VALUE); + IMemento memDispLoc = memento.getChild(TAG_DISPLAYED_LOCALES); + if (memDispLoc != null) { + displayLanguages = new ArrayList<String>(); + for (IMemento locale : memDispLoc.getChildren(TAG_LOCALE)) { + displayLanguages.add(locale.getString(TAG_VALUE)); } - } + } + } catch (Exception e) { - public GlossaryViewState(List<Locale> visibleLocales, SortInfo sortings, - boolean fuzzyMatchingEnabled, String selectedBundleId) { - super(); - this.sortings = sortings; - this.fuzzyMatchingEnabled = fuzzyMatchingEnabled; } + } - public SortInfo getSortings() { - return sortings; - } + public GlossaryViewState(List<Locale> visibleLocales, SortInfo sortings, + boolean fuzzyMatchingEnabled, String selectedBundleId) { + super(); + this.sortings = sortings; + this.fuzzyMatchingEnabled = fuzzyMatchingEnabled; + } - public void setSortings(SortInfo sortings) { - this.sortings = sortings; - } + public SortInfo getSortings() { + return sortings; + } - public boolean isFuzzyMatchingEnabled() { - return fuzzyMatchingEnabled; - } + public void setSortings(SortInfo sortings) { + this.sortings = sortings; + } - public void setFuzzyMatchingEnabled(boolean fuzzyMatchingEnabled) { - this.fuzzyMatchingEnabled = fuzzyMatchingEnabled; - } + public boolean isFuzzyMatchingEnabled() { + return fuzzyMatchingEnabled; + } - public void setSearchString(String searchString) { - this.searchString = searchString; - } + public void setFuzzyMatchingEnabled(boolean fuzzyMatchingEnabled) { + this.fuzzyMatchingEnabled = fuzzyMatchingEnabled; + } - public String getSearchString() { - return searchString; - } + public void setSearchString(String searchString) { + this.searchString = searchString; + } - public boolean isEditable() { - return editable; - } + public String getSearchString() { + return searchString; + } - public void setEditable(boolean editable) { - this.editable = editable; - } + public boolean isEditable() { + return editable; + } - public float getMatchingPrecision() { - return matchingPrecision; - } + public void setEditable(boolean editable) { + this.editable = editable; + } - public void setMatchingPrecision(float value) { - this.matchingPrecision = value; - } + public float getMatchingPrecision() { + return matchingPrecision; + } - public String getReferenceLanguage() { - return this.referenceLanguage; - } + public void setMatchingPrecision(float value) { + this.matchingPrecision = value; + } - public void setReferenceLanguage(String refLang) { - this.referenceLanguage = refLang; - } + public String getReferenceLanguage() { + return this.referenceLanguage; + } - public List<String> getDisplayLanguages() { - return displayLanguages; - } + public void setReferenceLanguage(String refLang) { + this.referenceLanguage = refLang; + } - public void setDisplayLanguages(List<String> displayLanguages) { - this.displayLanguages = displayLanguages; - } + public List<String> getDisplayLanguages() { + return displayLanguages; + } - public void setDisplayLangArr(String[] displayLanguages) { - this.displayLanguages = new ArrayList<String>(); - for (String dl : displayLanguages) { - this.displayLanguages.add(dl); - } - } + public void setDisplayLanguages(List<String> displayLanguages) { + this.displayLanguages = displayLanguages; + } - public void setGlossaryFile(String absolutePath) { - this.glossaryFile = absolutePath; + public void setDisplayLangArr(String[] displayLanguages) { + this.displayLanguages = new ArrayList<String>(); + for (String dl : displayLanguages) { + this.displayLanguages.add(dl); } + } - public String getGlossaryFile() { - return glossaryFile; - } + public void setGlossaryFile(String absolutePath) { + this.glossaryFile = absolutePath; + } - public void setSelectiveViewEnabled(boolean selectiveViewEnabled) { - this.selectiveViewEnabled = selectiveViewEnabled; - } + public String getGlossaryFile() { + return glossaryFile; + } - public boolean isSelectiveViewEnabled() { - return selectiveViewEnabled; - } + public void setSelectiveViewEnabled(boolean selectiveViewEnabled) { + this.selectiveViewEnabled = selectiveViewEnabled; + } + + public boolean isSelectiveViewEnabled() { + return selectiveViewEnabled; + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryContentProvider.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryContentProvider.java index 0546c7ad..a86cbf89 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryContentProvider.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryContentProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -20,88 +20,88 @@ public class GlossaryContentProvider implements ITreeContentProvider { - private Glossary glossary; - private boolean grouped = false; + private Glossary glossary; + private boolean grouped = false; - public GlossaryContentProvider(Glossary glossary) { - this.glossary = glossary; - } + public GlossaryContentProvider(Glossary glossary) { + this.glossary = glossary; + } - public Glossary getGlossary() { - return glossary; - } + public Glossary getGlossary() { + return glossary; + } - public void setGrouped(boolean grouped) { - this.grouped = grouped; - } + public void setGrouped(boolean grouped) { + this.grouped = grouped; + } - @Override - public void dispose() { - this.glossary = null; - } + @Override + public void dispose() { + this.glossary = null; + } - @Override - public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { - if (newInput instanceof Glossary) - this.glossary = (Glossary) newInput; - } + @Override + public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { + if (newInput instanceof Glossary) + this.glossary = (Glossary) newInput; + } - @Override - public Object[] getElements(Object inputElement) { - if (!grouped) - return getAllElements(glossary.terms).toArray( - new Term[glossary.terms.size()]); + @Override + public Object[] getElements(Object inputElement) { + if (!grouped) + return getAllElements(glossary.terms).toArray( + new Term[glossary.terms.size()]); - if (glossary != null) - return glossary.getAllTerms(); + if (glossary != null) + return glossary.getAllTerms(); - return null; - } + return null; + } - @Override - public Object[] getChildren(Object parentElement) { - if (!grouped) - return null; + @Override + public Object[] getChildren(Object parentElement) { + if (!grouped) + return null; - if (parentElement instanceof Term) { - Term t = (Term) parentElement; - return t.getAllSubTerms(); - } - return null; + if (parentElement instanceof Term) { + Term t = (Term) parentElement; + return t.getAllSubTerms(); } - - @Override - public Object getParent(Object element) { - if (element instanceof Term) { - Term t = (Term) element; - return t.getParentTerm(); - } - return null; + return null; + } + + @Override + public Object getParent(Object element) { + if (element instanceof Term) { + Term t = (Term) element; + return t.getParentTerm(); } + return null; + } - @Override - public boolean hasChildren(Object element) { - if (!grouped) - return false; + @Override + public boolean hasChildren(Object element) { + if (!grouped) + return false; - if (element instanceof Term) { - Term t = (Term) element; - return t.hasChildTerms(); - } - return false; + if (element instanceof Term) { + Term t = (Term) element; + return t.hasChildTerms(); } + return false; + } - public List<Term> getAllElements(List<Term> terms) { - List<Term> allTerms = new ArrayList<Term>(); + public List<Term> getAllElements(List<Term> terms) { + List<Term> allTerms = new ArrayList<Term>(); - if (terms != null) { - for (Term term : terms) { - allTerms.add(term); - allTerms.addAll(getAllElements(term.subTerms)); - } - } - - return allTerms; + if (terms != null) { + for (Term term : terms) { + allTerms.add(term); + allTerms.addAll(getAllElements(term.subTerms)); + } } + return allTerms; + } + } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java index ed11626d..9c6044f8 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/provider/GlossaryLabelProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -36,155 +36,155 @@ import org.eclipselabs.tapiji.translator.views.widgets.filter.FilterInfo; public class GlossaryLabelProvider extends StyledCellLabelProvider implements - ISelectionListener, ISelectionChangedListener { - - private boolean searchEnabled = false; - private int referenceColumn = 0; - private List<String> translations; - private IKeyTreeNode selectedItem; - - /*** COLORS ***/ - private Color gray = FontUtils.getSystemColor(SWT.COLOR_GRAY); - private Color black = FontUtils.getSystemColor(SWT.COLOR_BLACK); - private Color info_color = FontUtils.getSystemColor(SWT.COLOR_YELLOW); - private Color info_crossref = FontUtils - .getSystemColor(SWT.COLOR_INFO_BACKGROUND); - private Color info_crossref_foreground = FontUtils - .getSystemColor(SWT.COLOR_INFO_FOREGROUND); - private Color transparent = FontUtils.getSystemColor(SWT.COLOR_WHITE); - - /*** FONTS ***/ - private Font bold = FontUtils.createFont(SWT.BOLD); - private Font bold_italic = FontUtils.createFont(SWT.ITALIC); - - public void setSearchEnabled(boolean b) { - this.searchEnabled = b; + ISelectionListener, ISelectionChangedListener { + + private boolean searchEnabled = false; + private int referenceColumn = 0; + private List<String> translations; + private IKeyTreeNode selectedItem; + + /*** COLORS ***/ + private Color gray = FontUtils.getSystemColor(SWT.COLOR_GRAY); + private Color black = FontUtils.getSystemColor(SWT.COLOR_BLACK); + private Color info_color = FontUtils.getSystemColor(SWT.COLOR_YELLOW); + private Color info_crossref = FontUtils + .getSystemColor(SWT.COLOR_INFO_BACKGROUND); + private Color info_crossref_foreground = FontUtils + .getSystemColor(SWT.COLOR_INFO_FOREGROUND); + private Color transparent = FontUtils.getSystemColor(SWT.COLOR_WHITE); + + /*** FONTS ***/ + private Font bold = FontUtils.createFont(SWT.BOLD); + private Font bold_italic = FontUtils.createFont(SWT.ITALIC); + + public void setSearchEnabled(boolean b) { + this.searchEnabled = b; + } + + public GlossaryLabelProvider(int referenceColumn, + List<String> translations, IWorkbenchPage page) { + this.referenceColumn = referenceColumn; + this.translations = translations; + if (page.getActiveEditor() != null) { + selectedItem = EditorUtil.getSelectedKeyTreeNode(page); } - - public GlossaryLabelProvider(int referenceColumn, - List<String> translations, IWorkbenchPage page) { - this.referenceColumn = referenceColumn; - this.translations = translations; - if (page.getActiveEditor() != null) { - selectedItem = EditorUtil.getSelectedKeyTreeNode(page); - } + } + + public String getColumnText(Object element, int columnIndex) { + try { + Term term = (Term) element; + if (term != null) { + Translation transl = term.getTranslation(this.translations + .get(columnIndex)); + return transl != null ? transl.value : ""; + } + } catch (Exception e) { + e.printStackTrace(); } + return ""; + } - public String getColumnText(Object element, int columnIndex) { - try { - Term term = (Term) element; - if (term != null) { - Translation transl = term.getTranslation(this.translations - .get(columnIndex)); - return transl != null ? transl.value : ""; - } - } catch (Exception e) { - e.printStackTrace(); - } - return ""; - } + public boolean isSearchEnabled() { + return this.searchEnabled; + } - public boolean isSearchEnabled() { - return this.searchEnabled; - } + protected boolean isMatchingToPattern(Object element, int columnIndex) { + boolean matching = false; - protected boolean isMatchingToPattern(Object element, int columnIndex) { - boolean matching = false; + if (element instanceof Term) { + Term term = (Term) element; - if (element instanceof Term) { - Term term = (Term) element; - - if (term.getInfo() == null) - return false; - - FilterInfo filterInfo = (FilterInfo) term.getInfo(); + if (term.getInfo() == null) + return false; - matching = filterInfo.hasFoundInTranslation(translations - .get(columnIndex)); - } + FilterInfo filterInfo = (FilterInfo) term.getInfo(); - return matching; + matching = filterInfo.hasFoundInTranslation(translations + .get(columnIndex)); } - @Override - public void update(ViewerCell cell) { - Object element = cell.getElement(); - int columnIndex = cell.getColumnIndex(); - cell.setText(this.getColumnText(element, columnIndex)); - - if (isCrossRefRegion(cell.getText())) { - cell.setFont(bold); - cell.setBackground(info_crossref); - cell.setForeground(info_crossref_foreground); - } else { - cell.setFont(this.getColumnFont(element, columnIndex)); - cell.setBackground(transparent); - } - - if (isSearchEnabled()) { - if (isMatchingToPattern(element, columnIndex)) { - List<StyleRange> styleRanges = new ArrayList<StyleRange>(); - FilterInfo filterInfo = (FilterInfo) ((Term) element).getInfo(); - - for (Region reg : filterInfo - .getFoundInTranslationRanges(translations - .get(columnIndex < referenceColumn ? columnIndex + 1 - : columnIndex))) { - styleRanges.add(new StyleRange(reg.getOffset(), reg - .getLength(), black, info_color, SWT.BOLD)); - } - - cell.setStyleRanges(styleRanges - .toArray(new StyleRange[styleRanges.size()])); - } else { - cell.setForeground(gray); - } - } + return matching; + } + + @Override + public void update(ViewerCell cell) { + Object element = cell.getElement(); + int columnIndex = cell.getColumnIndex(); + cell.setText(this.getColumnText(element, columnIndex)); + + if (isCrossRefRegion(cell.getText())) { + cell.setFont(bold); + cell.setBackground(info_crossref); + cell.setForeground(info_crossref_foreground); + } else { + cell.setFont(this.getColumnFont(element, columnIndex)); + cell.setBackground(transparent); } - private boolean isCrossRefRegion(String cellText) { - if (selectedItem != null) { - for (IMessage entry : selectedItem.getMessagesBundleGroup() - .getMessages(selectedItem.getMessageKey())) { - String value = entry.getValue(); - String[] subValues = value.split("[\\s\\p{Punct}]+"); - for (String v : subValues) { - if (v.trim().equalsIgnoreCase(cellText.trim())) - return true; - } - } + if (isSearchEnabled()) { + if (isMatchingToPattern(element, columnIndex)) { + List<StyleRange> styleRanges = new ArrayList<StyleRange>(); + FilterInfo filterInfo = (FilterInfo) ((Term) element).getInfo(); + + for (Region reg : filterInfo + .getFoundInTranslationRanges(translations + .get(columnIndex < referenceColumn ? columnIndex + 1 + : columnIndex))) { + styleRanges.add(new StyleRange(reg.getOffset(), reg + .getLength(), black, info_color, SWT.BOLD)); } - return false; + cell.setStyleRanges(styleRanges + .toArray(new StyleRange[styleRanges.size()])); + } else { + cell.setForeground(gray); + } } - - private Font getColumnFont(Object element, int columnIndex) { - if (columnIndex == 0) { - return bold_italic; + } + + private boolean isCrossRefRegion(String cellText) { + if (selectedItem != null) { + for (IMessage entry : selectedItem.getMessagesBundleGroup() + .getMessages(selectedItem.getMessageKey())) { + String value = entry.getValue(); + String[] subValues = value.split("[\\s\\p{Punct}]+"); + for (String v : subValues) { + if (v.trim().equalsIgnoreCase(cellText.trim())) + return true; } - return null; + } } - @Override - public void selectionChanged(IWorkbenchPart part, ISelection selection) { - try { - if (selection.isEmpty()) - return; + return false; + } - if (!(selection instanceof IStructuredSelection)) - return; - - IStructuredSelection sel = (IStructuredSelection) selection; - selectedItem = (IKeyTreeNode) sel.iterator().next(); - this.getViewer().refresh(); - } catch (Exception e) { - // silent catch - } + private Font getColumnFont(Object element, int columnIndex) { + if (columnIndex == 0) { + return bold_italic; } - - @Override - public void selectionChanged(SelectionChangedEvent event) { - event.getSelection(); + return null; + } + + @Override + public void selectionChanged(IWorkbenchPart part, ISelection selection) { + try { + if (selection.isEmpty()) + return; + + if (!(selection instanceof IStructuredSelection)) + return; + + IStructuredSelection sel = (IStructuredSelection) selection; + selectedItem = (IKeyTreeNode) sel.iterator().next(); + this.getViewer().refresh(); + } catch (Exception e) { + // silent catch } + } + + @Override + public void selectionChanged(SelectionChangedEvent event) { + event.getSelection(); + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/GlossaryEntrySorter.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/GlossaryEntrySorter.java index 30e603f0..85ecd929 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/GlossaryEntrySorter.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/GlossaryEntrySorter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -20,78 +20,78 @@ public class GlossaryEntrySorter extends ViewerSorter { - private StructuredViewer viewer; - private SortInfo sortInfo; - private int referenceCol; - private List<String> translations; - - public GlossaryEntrySorter(StructuredViewer viewer, SortInfo sortInfo, - int referenceCol, List<String> translations) { - this.viewer = viewer; - this.referenceCol = referenceCol; - this.translations = translations; - - if (sortInfo != null) - this.sortInfo = sortInfo; - else - this.sortInfo = new SortInfo(); - } - - public StructuredViewer getViewer() { - return viewer; - } - - public void setViewer(StructuredViewer viewer) { - this.viewer = viewer; - } - - public SortInfo getSortInfo() { - return sortInfo; - } - - public void setSortInfo(SortInfo sortInfo) { - this.sortInfo = sortInfo; - } - - @Override - public int compare(Viewer viewer, Object e1, Object e2) { - try { - if (!(e1 instanceof Term && e2 instanceof Term)) - return super.compare(viewer, e1, e2); - Term comp1 = (Term) e1; - Term comp2 = (Term) e2; - - int result = 0; - - if (sortInfo == null) - return 0; - - if (sortInfo.getColIdx() == 0) { - Translation transComp1 = comp1.getTranslation(translations - .get(referenceCol)); - Translation transComp2 = comp2.getTranslation(translations - .get(referenceCol)); - if (transComp1 != null && transComp2 != null) - result = transComp1.value.compareTo(transComp2.value); - } else { - int col = sortInfo.getColIdx() < referenceCol ? sortInfo - .getColIdx() + 1 : sortInfo.getColIdx(); - Translation transComp1 = comp1.getTranslation(translations - .get(col)); - Translation transComp2 = comp2.getTranslation(translations - .get(col)); - - if (transComp1 == null) - transComp1 = new Translation(); - if (transComp2 == null) - transComp2 = new Translation(); - result = transComp1.value.compareTo(transComp2.value); - } - - return result * (sortInfo.isDESC() ? -1 : 1); - } catch (Exception e) { - return 0; - } + private StructuredViewer viewer; + private SortInfo sortInfo; + private int referenceCol; + private List<String> translations; + + public GlossaryEntrySorter(StructuredViewer viewer, SortInfo sortInfo, + int referenceCol, List<String> translations) { + this.viewer = viewer; + this.referenceCol = referenceCol; + this.translations = translations; + + if (sortInfo != null) + this.sortInfo = sortInfo; + else + this.sortInfo = new SortInfo(); + } + + public StructuredViewer getViewer() { + return viewer; + } + + public void setViewer(StructuredViewer viewer) { + this.viewer = viewer; + } + + public SortInfo getSortInfo() { + return sortInfo; + } + + public void setSortInfo(SortInfo sortInfo) { + this.sortInfo = sortInfo; + } + + @Override + public int compare(Viewer viewer, Object e1, Object e2) { + try { + if (!(e1 instanceof Term && e2 instanceof Term)) + return super.compare(viewer, e1, e2); + Term comp1 = (Term) e1; + Term comp2 = (Term) e2; + + int result = 0; + + if (sortInfo == null) + return 0; + + if (sortInfo.getColIdx() == 0) { + Translation transComp1 = comp1.getTranslation(translations + .get(referenceCol)); + Translation transComp2 = comp2.getTranslation(translations + .get(referenceCol)); + if (transComp1 != null && transComp2 != null) + result = transComp1.value.compareTo(transComp2.value); + } else { + int col = sortInfo.getColIdx() < referenceCol ? sortInfo + .getColIdx() + 1 : sortInfo.getColIdx(); + Translation transComp1 = comp1.getTranslation(translations + .get(col)); + Translation transComp2 = comp2.getTranslation(translations + .get(col)); + + if (transComp1 == null) + transComp1 = new Translation(); + if (transComp2 == null) + transComp2 = new Translation(); + result = transComp1.value.compareTo(transComp2.value); + } + + return result * (sortInfo.isDESC() ? -1 : 1); + } catch (Exception e) { + return 0; } + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/SortInfo.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/SortInfo.java index 1118283e..8674734e 100644 --- a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/SortInfo.java +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/widgets/sorter/SortInfo.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 TapiJI. + * 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 @@ -17,49 +17,49 @@ public class SortInfo { - public static final String TAG_SORT_INFO = "sort_info"; - public static final String TAG_COLUMN_INDEX = "col_idx"; - public static final String TAG_ORDER = "order"; + public static final String TAG_SORT_INFO = "sort_info"; + public static final String TAG_COLUMN_INDEX = "col_idx"; + public static final String TAG_ORDER = "order"; - private int colIdx; - private boolean DESC; - private List<Locale> visibleLocales; + private int colIdx; + private boolean DESC; + private List<Locale> visibleLocales; - public void setDESC(boolean dESC) { - DESC = dESC; - } + public void setDESC(boolean dESC) { + DESC = dESC; + } - public boolean isDESC() { - return DESC; - } + public boolean isDESC() { + return DESC; + } - public void setColIdx(int colIdx) { - this.colIdx = colIdx; - } + public void setColIdx(int colIdx) { + this.colIdx = colIdx; + } - public int getColIdx() { - return colIdx; - } + public int getColIdx() { + return colIdx; + } - public void setVisibleLocales(List<Locale> visibleLocales) { - this.visibleLocales = visibleLocales; - } + public void setVisibleLocales(List<Locale> visibleLocales) { + this.visibleLocales = visibleLocales; + } - public List<Locale> getVisibleLocales() { - return visibleLocales; - } + public List<Locale> getVisibleLocales() { + return visibleLocales; + } - public void saveState(IMemento memento) { - IMemento mCI = memento.createChild(TAG_SORT_INFO); - mCI.putInteger(TAG_COLUMN_INDEX, colIdx); - mCI.putBoolean(TAG_ORDER, DESC); - } + public void saveState(IMemento memento) { + IMemento mCI = memento.createChild(TAG_SORT_INFO); + mCI.putInteger(TAG_COLUMN_INDEX, colIdx); + mCI.putBoolean(TAG_ORDER, DESC); + } - public void init(IMemento memento) { - IMemento mCI = memento.getChild(TAG_SORT_INFO); - if (mCI == null) - return; - colIdx = mCI.getInteger(TAG_COLUMN_INDEX); - DESC = mCI.getBoolean(TAG_ORDER); - } + public void init(IMemento memento) { + IMemento mCI = memento.getChild(TAG_SORT_INFO); + if (mCI == null) + return; + colIdx = mCI.getInteger(TAG_COLUMN_INDEX); + DESC = mCI.getBoolean(TAG_ORDER); + } }
9e5a33c1b36cae7a7541251509bf032455838fdf
spring-framework
Add a ResourceResolver implementation for WebJars--Prior to this commit
a
https://github.com/spring-projects/spring-framework
diff --git a/build.gradle b/build.gradle index d56a60228112..c17f5bd3c188 100644 --- a/build.gradle +++ b/build.gradle @@ -895,6 +895,7 @@ project("spring-webmvc") { exclude group: "org.slf4j", module: "jcl-over-slf4j" exclude group: "org.springframework", module: "spring-web" } + optional 'org.webjars:webjars-locator:0.22' testCompile(project(":spring-aop")) testCompile("rhino:js:1.7R1") testCompile("xmlunit:xmlunit:${xmlunitVersion}") @@ -921,6 +922,7 @@ project("spring-webmvc") { testCompile("org.slf4j:slf4j-jcl:${slf4jVersion}") testCompile("org.jruby:jruby:${jrubyVersion}") testCompile("org.python:jython-standalone:2.5.3") + testCompile("org.webjars:underscorejs:1.8.2") } } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/ResourcesBeanDefinitionParser.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/ResourcesBeanDefinitionParser.java index 9d0001964628..02fbde892201 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/ResourcesBeanDefinitionParser.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/ResourcesBeanDefinitionParser.java @@ -33,6 +33,7 @@ import org.springframework.beans.factory.xml.ParserContext; import org.springframework.cache.concurrent.ConcurrentMapCache; import org.springframework.core.Ordered; +import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; import org.springframework.util.xml.DomUtils; import org.springframework.http.CacheControl; @@ -51,6 +52,7 @@ import org.springframework.web.servlet.resource.ResourceUrlProvider; import org.springframework.web.servlet.resource.ResourceUrlProviderExposingInterceptor; import org.springframework.web.servlet.resource.VersionResourceResolver; +import org.springframework.web.servlet.resource.WebJarsResourceResolver; /** * {@link org.springframework.beans.factory.xml.BeanDefinitionParser} that parses a @@ -78,6 +80,9 @@ class ResourcesBeanDefinitionParser implements BeanDefinitionParser { private static final String RESOURCE_URL_PROVIDER = "mvcResourceUrlProvider"; + private static final boolean isWebJarsAssetLocatorPresent = ClassUtils.isPresent( + "org.webjars.WebJarAssetLocator", ResourcesBeanDefinitionParser.class.getClassLoader()); + @Override public BeanDefinition parse(Element element, ParserContext parserContext) { @@ -302,6 +307,12 @@ private void parseResourceResolversTransformers(boolean isAutoRegistration, } if (isAutoRegistration) { + if(isWebJarsAssetLocatorPresent) { + RootBeanDefinition webJarsResolverDef = new RootBeanDefinition(WebJarsResourceResolver.class); + webJarsResolverDef.setSource(source); + webJarsResolverDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + resourceResolvers.add(webJarsResolverDef); + } RootBeanDefinition pathResolverDef = new RootBeanDefinition(PathResourceResolver.class); pathResolverDef.setSource(source); pathResolverDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceChainRegistration.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceChainRegistration.java index 7749491f94f5..fea0fd805804 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceChainRegistration.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceChainRegistration.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. @@ -22,6 +22,7 @@ import org.springframework.cache.Cache; import org.springframework.cache.concurrent.ConcurrentMapCache; import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; import org.springframework.web.servlet.resource.CachingResourceResolver; import org.springframework.web.servlet.resource.CachingResourceTransformer; import org.springframework.web.servlet.resource.CssLinkResourceTransformer; @@ -29,6 +30,7 @@ import org.springframework.web.servlet.resource.ResourceResolver; import org.springframework.web.servlet.resource.ResourceTransformer; import org.springframework.web.servlet.resource.VersionResourceResolver; +import org.springframework.web.servlet.resource.WebJarsResourceResolver; /** * Assists with the registration of resource resolvers and transformers. @@ -40,6 +42,9 @@ public class ResourceChainRegistration { private static final String DEFAULT_CACHE_NAME = "spring-resource-chain-cache"; + private static final boolean isWebJarsAssetLocatorPresent = ClassUtils.isPresent( + "org.webjars.WebJarAssetLocator", ResourceChainRegistration.class.getClassLoader()); + private final List<ResourceResolver> resolvers = new ArrayList<ResourceResolver>(4); private final List<ResourceTransformer> transformers = new ArrayList<ResourceTransformer>(4); @@ -98,6 +103,9 @@ public ResourceChainRegistration addTransformer(ResourceTransformer transformer) protected List<ResourceResolver> getResourceResolvers() { if (!this.hasPathResolver) { List<ResourceResolver> result = new ArrayList<ResourceResolver>(this.resolvers); + if(isWebJarsAssetLocatorPresent) { + result.add(new WebJarsResourceResolver()); + } result.add(new PathResourceResolver()); return result; } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/WebJarsResourceResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/WebJarsResourceResolver.java new file mode 100644 index 000000000000..206d3fc271e2 --- /dev/null +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/WebJarsResourceResolver.java @@ -0,0 +1,90 @@ +/* + * 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. + * 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.web.servlet.resource; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.webjars.MultipleMatchesException; +import org.webjars.WebJarAssetLocator; + +import org.springframework.core.io.Resource; + +/** + * A {@code ResourceResolver} that delegates to the chain to locate a resource + * and then attempts to find a matching versioned resource contained in a WebJar JAR file. + * + * <p>This allows WabJar users to use version-less paths in their templates, like {@code "/jquery/jquery.min.js"} + * while this path is resolved to the unique version {@code "/jquery/1.2.0/jquery.min.js"}, which is a better fit + * for HTTP caching and version management in applications. + * + * <p>This resolver requires the "org.webjars:webjars-locator" library on classpath, and is automatically + * registered if that library is present. + * + * @author Brian Clozel + * @since 4.2 + * @see <a href="http://www.webjars.org">webjars.org</a> + */ +public class WebJarsResourceResolver extends AbstractResourceResolver { + + private final static String WEBJARS_LOCATION = "META-INF/resources/webjars"; + + private final static int WEBJARS_LOCATION_LENGTH = WEBJARS_LOCATION.length(); + + private final WebJarAssetLocator webJarAssetLocator; + + public WebJarsResourceResolver() { + this.webJarAssetLocator = new WebJarAssetLocator(); + } + + @Override + protected Resource resolveResourceInternal(HttpServletRequest request, String requestPath, + List<? extends Resource> locations, ResourceResolverChain chain) { + + return chain.resolveResource(request, requestPath, locations); + } + + @Override + protected String resolveUrlPathInternal(String resourceUrlPath, + List<? extends Resource> locations, ResourceResolverChain chain) { + + String path = chain.resolveUrlPath(resourceUrlPath, locations); + if (path == null) { + try { + int startOffset = resourceUrlPath.startsWith("/") ? 1 : 0; + int endOffset = resourceUrlPath.indexOf("/", 1); + if (endOffset != -1) { + String webjar = resourceUrlPath.substring(startOffset, endOffset); + String partialPath = resourceUrlPath.substring(endOffset); + String webJarPath = webJarAssetLocator.getFullPath(webjar, partialPath); + return chain.resolveUrlPath(webJarPath.substring(WEBJARS_LOCATION_LENGTH), locations); + } + } + catch (MultipleMatchesException ex) { + logger.warn("WebJar version conflict for \"" + resourceUrlPath + "\"", ex); + } + catch (IllegalArgumentException ex) { + if (logger.isTraceEnabled()) { + logger.trace("No WebJar resource found for \"" + resourceUrlPath + "\""); + } + } + } + return path; + } + +} diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java index fa3bc94ddfc7..92032a319615 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java @@ -119,6 +119,7 @@ import org.springframework.web.servlet.resource.ResourceUrlProvider; import org.springframework.web.servlet.resource.ResourceUrlProviderExposingInterceptor; import org.springframework.web.servlet.resource.VersionResourceResolver; +import org.springframework.web.servlet.resource.WebJarsResourceResolver; import org.springframework.web.servlet.theme.ThemeChangeInterceptor; import org.springframework.web.servlet.view.BeanNameViewResolver; import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; @@ -409,10 +410,11 @@ public void testResourcesWithResolversTransformers() throws Exception { assertNotNull(handler); List<ResourceResolver> resolvers = handler.getResourceResolvers(); - assertThat(resolvers, Matchers.hasSize(3)); + assertThat(resolvers, Matchers.hasSize(4)); assertThat(resolvers.get(0), Matchers.instanceOf(CachingResourceResolver.class)); assertThat(resolvers.get(1), Matchers.instanceOf(VersionResourceResolver.class)); - assertThat(resolvers.get(2), Matchers.instanceOf(PathResourceResolver.class)); + assertThat(resolvers.get(2), Matchers.instanceOf(WebJarsResourceResolver.class)); + assertThat(resolvers.get(3), Matchers.instanceOf(PathResourceResolver.class)); CachingResourceResolver cachingResolver = (CachingResourceResolver) resolvers.get(0); assertThat(cachingResolver.getCache(), Matchers.instanceOf(ConcurrentMapCache.class)); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java index 101a3135e1d9..d1d0df7a447b 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java @@ -40,6 +40,7 @@ import org.springframework.web.servlet.resource.ResourceResolver; import org.springframework.web.servlet.resource.ResourceTransformer; import org.springframework.web.servlet.resource.VersionResourceResolver; +import org.springframework.web.servlet.resource.WebJarsResourceResolver; import static org.junit.Assert.*; @@ -125,12 +126,13 @@ public void resourceChain() throws Exception { ResourceHttpRequestHandler handler = getHandler("/resources/**"); List<ResourceResolver> resolvers = handler.getResourceResolvers(); - assertThat(resolvers.toString(), resolvers, Matchers.hasSize(3)); + assertThat(resolvers.toString(), resolvers, Matchers.hasSize(4)); assertThat(resolvers.get(0), Matchers.instanceOf(CachingResourceResolver.class)); CachingResourceResolver cachingResolver = (CachingResourceResolver) resolvers.get(0); assertThat(cachingResolver.getCache(), Matchers.instanceOf(ConcurrentMapCache.class)); assertThat(resolvers.get(1), Matchers.equalTo(mockResolver)); - assertThat(resolvers.get(2), Matchers.instanceOf(PathResourceResolver.class)); + assertThat(resolvers.get(2), Matchers.instanceOf(WebJarsResourceResolver.class)); + assertThat(resolvers.get(3), Matchers.instanceOf(PathResourceResolver.class)); List<ResourceTransformer> transformers = handler.getResourceTransformers(); assertThat(transformers, Matchers.hasSize(2)); @@ -144,8 +146,9 @@ public void resourceChainWithoutCaching() throws Exception { ResourceHttpRequestHandler handler = getHandler("/resources/**"); List<ResourceResolver> resolvers = handler.getResourceResolvers(); - assertThat(resolvers, Matchers.hasSize(1)); - assertThat(resolvers.get(0), Matchers.instanceOf(PathResourceResolver.class)); + assertThat(resolvers, Matchers.hasSize(2)); + assertThat(resolvers.get(0), Matchers.instanceOf(WebJarsResourceResolver.class)); + assertThat(resolvers.get(1), Matchers.instanceOf(PathResourceResolver.class)); List<ResourceTransformer> transformers = handler.getResourceTransformers(); assertThat(transformers, Matchers.hasSize(0)); @@ -162,10 +165,11 @@ public void resourceChainWithVersionResolver() throws Exception { ResourceHttpRequestHandler handler = getHandler("/resources/**"); List<ResourceResolver> resolvers = handler.getResourceResolvers(); - assertThat(resolvers.toString(), resolvers, Matchers.hasSize(3)); + assertThat(resolvers.toString(), resolvers, Matchers.hasSize(4)); assertThat(resolvers.get(0), Matchers.instanceOf(CachingResourceResolver.class)); assertThat(resolvers.get(1), Matchers.sameInstance(versionResolver)); - assertThat(resolvers.get(2), Matchers.instanceOf(PathResourceResolver.class)); + assertThat(resolvers.get(2), Matchers.instanceOf(WebJarsResourceResolver.class)); + assertThat(resolvers.get(3), Matchers.instanceOf(PathResourceResolver.class)); List<ResourceTransformer> transformers = handler.getResourceTransformers(); assertThat(transformers, Matchers.hasSize(3)); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/WebJarsResourceResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/WebJarsResourceResolverTests.java new file mode 100644 index 000000000000..3af4aea72cc9 --- /dev/null +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/resource/WebJarsResourceResolverTests.java @@ -0,0 +1,107 @@ +/* + * 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. + * 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.web.servlet.resource; + +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.util.Collections; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +/** + * Unit tests for + * {@link org.springframework.web.servlet.resource.WebJarsResourceResolver}. + * + * @author Brian Clozel + */ +public class WebJarsResourceResolverTests { + + private List<Resource> locations; + + private WebJarsResourceResolver resolver; + + private ResourceResolverChain chain; + + @Before + public void setup() { + // for this to work, an actual WebJar must be on the test classpath + this.locations = Collections.singletonList(new ClassPathResource("/META-INF/resources/webjars/")); + this.resolver = new WebJarsResourceResolver(); + this.chain = mock(ResourceResolverChain.class); + } + + @Test + public void resolveUrlExisting() { + this.locations = Collections.singletonList(new ClassPathResource("/META-INF/resources/webjars/", getClass())); + String file = "/foo/2.3/foo.txt"; + given(this.chain.resolveUrlPath(file, this.locations)).willReturn(file); + + String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain); + + assertEquals(file, actual); + verify(this.chain, times(1)).resolveUrlPath(file, this.locations); + } + + @Test + public void resolveUrlExistingNotInJarFile() { + this.locations = Collections.singletonList(new ClassPathResource("/META-INF/resources/webjars/", getClass())); + String file = "/foo/foo.txt"; + given(this.chain.resolveUrlPath(file, this.locations)).willReturn(null); + + String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain); + + assertNull(actual); + verify(this.chain, times(1)).resolveUrlPath(file, this.locations); + verify(this.chain, never()).resolveUrlPath("/foo/2.3/foo.txt", this.locations); + } + + @Test + public void resolveUrlWebJarResource() { + String file = "/underscorejs/underscore.js"; + String expected = "/underscorejs/1.8.2/underscore.js"; + given(this.chain.resolveUrlPath(file, this.locations)).willReturn(null); + given(this.chain.resolveUrlPath(expected, this.locations)).willReturn(expected); + + String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain); + + assertEquals(expected, actual); + verify(this.chain, times(1)).resolveUrlPath(file, this.locations); + verify(this.chain, times(1)).resolveUrlPath(expected, this.locations); + } + + @Test + public void resolverUrlWebJarResourceNotFound() { + String file = "/something/something.js"; + given(this.chain.resolveUrlPath(file, this.locations)).willReturn(null); + + String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain); + + assertNull(actual); + verify(this.chain, times(1)).resolveUrlPath(file, this.locations); + } + +} diff --git a/spring-webmvc/src/test/resources/org/springframework/web/servlet/resource/META-INF/resources/webjars/foo/2.3/foo.txt b/spring-webmvc/src/test/resources/org/springframework/web/servlet/resource/META-INF/resources/webjars/foo/2.3/foo.txt new file mode 100644 index 000000000000..a9ed77c8dd53 --- /dev/null +++ b/spring-webmvc/src/test/resources/org/springframework/web/servlet/resource/META-INF/resources/webjars/foo/2.3/foo.txt @@ -0,0 +1 @@ +Some text. \ No newline at end of file
f8936831eb13d17932a7f871faba0acbdfeb14bf
Delta Spike
[maven-release-plugin] prepare for next development iteration
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/cdictrl/api/pom.xml b/deltaspike/cdictrl/api/pom.xml index f7dc8cc31..1146dfd2e 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.5</version> + <version>0.6-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/cdictrl/impl-openejb/pom.xml b/deltaspike/cdictrl/impl-openejb/pom.xml index 21bbd7173..d15aac0b3 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.5</version> + <version>0.6-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/cdictrl/impl-owb/pom.xml b/deltaspike/cdictrl/impl-owb/pom.xml index 87b494209..15629a959 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.5</version> + <version>0.6-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/cdictrl/impl-weld/pom.xml b/deltaspike/cdictrl/impl-weld/pom.xml index 3a69b080b..3568219a8 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.5</version> + <version>0.6-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/cdictrl/pom.xml b/deltaspike/cdictrl/pom.xml index d305fda8f..54f072621 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.5</version> + <version>0.6-SNAPSHOT</version> <relativePath>../parent/pom.xml</relativePath> </parent> diff --git a/deltaspike/cdictrl/tck/pom.xml b/deltaspike/cdictrl/tck/pom.xml index 2e286017c..a2da22bb8 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.5</version> + <version>0.6-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/checkstyle-rules/pom.xml b/deltaspike/checkstyle-rules/pom.xml index 22b30783e..5413620c2 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.5</version> + <version>0.6-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/core/api/pom.xml b/deltaspike/core/api/pom.xml index bf3afbc9a..12e6ed47c 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.5</version> + <version>0.6-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/core/impl/pom.xml b/deltaspike/core/impl/pom.xml index 223e53602..d203e499d 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.5</version> + <version>0.6-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/core/pom.xml b/deltaspike/core/pom.xml index d825cde78..1d3859197 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.5</version> + <version>0.6-SNAPSHOT</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 5adde3fbf..88fee8c20 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.5</version> + <version>0.6-SNAPSHOT</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 e4b94a9e7..6d982ae32 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.5</version> + <version>0.6-SNAPSHOT</version> </parent> <artifactId>deltaspike-jsf-example</artifactId> diff --git a/deltaspike/examples/pom.xml b/deltaspike/examples/pom.xml index 35436f83e..851da8097 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.5</version> + <version>0.6-SNAPSHOT</version> <relativePath>../parent/pom.xml</relativePath> </parent> diff --git a/deltaspike/modules/bean-validation/api/pom.xml b/deltaspike/modules/bean-validation/api/pom.xml index a71386bf7..5d3ee0ec4 100644 --- a/deltaspike/modules/bean-validation/api/pom.xml +++ b/deltaspike/modules/bean-validation/api/pom.xml @@ -15,7 +15,7 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>bean-validation-module-project</artifactId> - <version>0.5</version> + <version>0.6-SNAPSHOT</version> </parent> <artifactId>deltaspike-bean-validation-module-api</artifactId> diff --git a/deltaspike/modules/bean-validation/impl/pom.xml b/deltaspike/modules/bean-validation/impl/pom.xml index d41c44927..9dd7e66ba 100644 --- a/deltaspike/modules/bean-validation/impl/pom.xml +++ b/deltaspike/modules/bean-validation/impl/pom.xml @@ -15,7 +15,7 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>bean-validation-module-project</artifactId> - <version>0.5</version> + <version>0.6-SNAPSHOT</version> </parent> <artifactId>deltaspike-bean-validation-module-impl</artifactId> diff --git a/deltaspike/modules/bean-validation/pom.xml b/deltaspike/modules/bean-validation/pom.xml index f95e654bb..86558d8e2 100644 --- a/deltaspike/modules/bean-validation/pom.xml +++ b/deltaspike/modules/bean-validation/pom.xml @@ -23,12 +23,12 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>modules-project</artifactId> - <version>0.5</version> + <version>0.6-SNAPSHOT</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>bean-validation-module-project</artifactId> - <version>0.5</version> + <version>0.6-SNAPSHOT</version> <packaging>pom</packaging> <name>Apache DeltaSpike BeanValidation-Module</name> diff --git a/deltaspike/modules/data/api/pom.xml b/deltaspike/modules/data/api/pom.xml index f331ccfd0..efb224341 100755 --- a/deltaspike/modules/data/api/pom.xml +++ b/deltaspike/modules/data/api/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>data-module-project</artifactId> - <version>0.5</version> + <version>0.6-SNAPSHOT</version> </parent> <artifactId>deltaspike-data-module-api</artifactId> diff --git a/deltaspike/modules/data/impl/pom.xml b/deltaspike/modules/data/impl/pom.xml index 3ca03f0b8..3538bb7fb 100755 --- a/deltaspike/modules/data/impl/pom.xml +++ b/deltaspike/modules/data/impl/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>data-module-project</artifactId> - <version>0.5</version> + <version>0.6-SNAPSHOT</version> </parent> <artifactId>deltaspike-data-module-impl</artifactId> diff --git a/deltaspike/modules/data/pom.xml b/deltaspike/modules/data/pom.xml index 2ef9788ad..9c2dfe932 100755 --- a/deltaspike/modules/data/pom.xml +++ b/deltaspike/modules/data/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>modules-project</artifactId> - <version>0.5</version> + <version>0.6-SNAPSHOT</version> </parent> <artifactId>data-module-project</artifactId> diff --git a/deltaspike/modules/jpa/api/pom.xml b/deltaspike/modules/jpa/api/pom.xml index a4d691fb9..b859b542e 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.5</version> + <version>0.6-SNAPSHOT</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 85f09cf5b..41fc13f4b 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.5</version> + <version>0.6-SNAPSHOT</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> diff --git a/deltaspike/modules/jpa/pom.xml b/deltaspike/modules/jpa/pom.xml index 8015e0cc9..dd5dfd4af 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.5</version> + <version>0.6-SNAPSHOT</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>jpa-module-project</artifactId> - <version>0.5</version> + <version>0.6-SNAPSHOT</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 22eecb295..037bcf450 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.5</version> + <version>0.6-SNAPSHOT</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 67162998f..e34d9c74c 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.5</version> + <version>0.6-SNAPSHOT</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> diff --git a/deltaspike/modules/jsf/pom.xml b/deltaspike/modules/jsf/pom.xml index 77c09cdb8..214eeabd3 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.5</version> + <version>0.6-SNAPSHOT</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>jsf-module-project</artifactId> - <version>0.5</version> + <version>0.6-SNAPSHOT</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 02ce4174c..1c95be7f5 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.5</version> + <version>0.6-SNAPSHOT</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 16dc45e51..faf802be5 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.5</version> + <version>0.6-SNAPSHOT</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 16d08531f..148add1ac 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.5</version> + <version>0.6-SNAPSHOT</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>partial-bean-module-project</artifactId> - <version>0.5</version> + <version>0.6-SNAPSHOT</version> <packaging>pom</packaging> <name>Apache DeltaSpike Partial-Bean-Module</name> diff --git a/deltaspike/modules/pom.xml b/deltaspike/modules/pom.xml index 793c61258..54239101a 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.5</version> + <version>0.6-SNAPSHOT</version> <relativePath>../parent/code/pom.xml</relativePath> </parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>modules-project</artifactId> - <version>0.5</version> + <version>0.6-SNAPSHOT</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 d4459c8f0..cc7383cc1 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.5</version> + <version>0.6-SNAPSHOT</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 79fa93475..e43cc5f7c 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.5</version> + <version>0.6-SNAPSHOT</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> diff --git a/deltaspike/modules/security/pom.xml b/deltaspike/modules/security/pom.xml index 2432d63cc..ec3728cb9 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.5</version> + <version>0.6-SNAPSHOT</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>security-module-project</artifactId> - <version>0.5</version> + <version>0.6-SNAPSHOT</version> <packaging>pom</packaging> <name>Apache DeltaSpike Security-Module</name> diff --git a/deltaspike/modules/servlet/api/pom.xml b/deltaspike/modules/servlet/api/pom.xml index bcfbfe6c3..ab8f8f76b 100644 --- a/deltaspike/modules/servlet/api/pom.xml +++ b/deltaspike/modules/servlet/api/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>servlet-module-project</artifactId> - <version>0.5</version> + <version>0.6-SNAPSHOT</version> </parent> <artifactId>deltaspike-servlet-module-api</artifactId> diff --git a/deltaspike/modules/servlet/impl/pom.xml b/deltaspike/modules/servlet/impl/pom.xml index 8b2a09cf5..d4857fa29 100644 --- a/deltaspike/modules/servlet/impl/pom.xml +++ b/deltaspike/modules/servlet/impl/pom.xml @@ -23,7 +23,7 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>servlet-module-project</artifactId> - <version>0.5</version> + <version>0.6-SNAPSHOT</version> </parent> <artifactId>deltaspike-servlet-module-impl</artifactId> diff --git a/deltaspike/modules/servlet/pom.xml b/deltaspike/modules/servlet/pom.xml index 496361a8a..b7fb1642f 100644 --- a/deltaspike/modules/servlet/pom.xml +++ b/deltaspike/modules/servlet/pom.xml @@ -23,12 +23,12 @@ <parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>modules-project</artifactId> - <version>0.5</version> + <version>0.6-SNAPSHOT</version> </parent> <groupId>org.apache.deltaspike.modules</groupId> <artifactId>servlet-module-project</artifactId> - <version>0.5</version> + <version>0.6-SNAPSHOT</version> <packaging>pom</packaging> <name>Apache DeltaSpike Servlet-Module</name> diff --git a/deltaspike/parent/code/pom.xml b/deltaspike/parent/code/pom.xml index 89e61cdf4..ca1596044 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.5</version> + <version>0.6-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/parent/pom.xml b/deltaspike/parent/pom.xml index c4110e168..2da886fa4 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.5</version> + <version>0.6-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> diff --git a/deltaspike/pom.xml b/deltaspike/pom.xml index d75c7cf8f..7fbb5220b 100644 --- a/deltaspike/pom.xml +++ b/deltaspike/pom.xml @@ -36,7 +36,7 @@ --> <groupId>org.apache.deltaspike</groupId> <artifactId>deltaspike-project</artifactId> - <version>0.5</version> + <version>0.6-SNAPSHOT</version> <packaging>pom</packaging> <name>Apache DeltaSpike</name> @@ -49,7 +49,7 @@ <connection>scm:git:https://git-wip-us.apache.org/repos/asf/deltaspike.git</connection> <developerConnection>scm:git:https://git-wip-us.apache.org/repos/asf/deltaspike.git</developerConnection> <url>https://git-wip-us.apache.org/repos/asf/deltaspike.git</url> - <tag>deltaspike-project-0.5</tag> + <tag>HEAD</tag> </scm> <modules> diff --git a/deltaspike/test-utils/pom.xml b/deltaspike/test-utils/pom.xml index c7fb3ae50..eaefef4a4 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.5</version> + <version>0.6-SNAPSHOT</version> <relativePath>../parent/pom.xml</relativePath> </parent>
53fbd0069652cfe101a2eba1c0f0849b35ff28c1
Delta Spike
DELTASPIKE-60 minor JavaDoc tweaks
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/modules/data/api/src/main/java/org/apache/deltaspike/data/api/EntityManagerResolver.java b/deltaspike/modules/data/api/src/main/java/org/apache/deltaspike/data/api/EntityManagerResolver.java index 80ebdb17d..de10da307 100644 --- a/deltaspike/modules/data/api/src/main/java/org/apache/deltaspike/data/api/EntityManagerResolver.java +++ b/deltaspike/modules/data/api/src/main/java/org/apache/deltaspike/data/api/EntityManagerResolver.java @@ -22,7 +22,7 @@ /** * Resolve the EntityManager used for a specific repository. - * Only necessary if there are more than one persistence unit. + * Only necessary if there is more than one persistence unit. */ public interface EntityManagerResolver { diff --git a/deltaspike/modules/data/api/src/main/java/org/apache/deltaspike/data/spi/DelegateQueryHandler.java b/deltaspike/modules/data/api/src/main/java/org/apache/deltaspike/data/spi/DelegateQueryHandler.java index 781b3a17f..a84237b4a 100644 --- a/deltaspike/modules/data/api/src/main/java/org/apache/deltaspike/data/spi/DelegateQueryHandler.java +++ b/deltaspike/modules/data/api/src/main/java/org/apache/deltaspike/data/spi/DelegateQueryHandler.java @@ -20,20 +20,21 @@ /** * A marker interface. Used for writing custom query methods: - * + * <pre> * public interface RepositoryExtension<E> { * E saveAndFlushAndRefresh(E entity); * } * * public class DelegateRepositoryExtension<E> implements RepositoryExtension<E>, DelegateQueryHandler { - * @Inject + * &#064;Inject * private QueryInvocationContext context; * - * @Override + * &#064;Override * public E saveAndFlushAndRefresh(E entity) { * ... * } * } + * </pre> * * The extension is now usable with: *
e4f90dae4475d245a05eeb43e48e1c6c8f7c53f2
griddynamics$jagger
+ generify little bit MetricGroupNode + extract AbstractTree from ControlTree with "cascade check - one event" functionality + create LegendTree with specific cell (LegendNodeCell)
p
https://github.com/griddynamics/jagger
diff --git a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/model/MetricGroupNode.java b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/model/MetricGroupNode.java index 009822b18..bfa779826 100644 --- a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/model/MetricGroupNode.java +++ b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/model/MetricGroupNode.java @@ -8,7 +8,7 @@ public class MetricGroupNode<M extends MetricNode> extends AbstractIdentifyNode { private List<M> metrics = null; - private List<MetricGroupNode> metricGroupNodeList = null; + private List<MetricGroupNode<M>> metricGroupNodeList = null; public MetricGroupNode(MetricGroupNode<M> that) { super(that); @@ -20,7 +20,7 @@ public MetricGroupNode(String displayName) { } public MetricGroupNode() {} - public void setMetricGroupNodeList(List<MetricGroupNode> metricGroupNodeList) { + public void setMetricGroupNodeList(List<MetricGroupNode<M>> metricGroupNodeList) { this.metricGroupNodeList = metricGroupNodeList; } @@ -31,7 +31,7 @@ public void setMetrics(List<M> metrics) { public List<M> getMetricsWithoutChildren() { return metrics; } - public List<MetricGroupNode> getMetricGroupNodeList() { + public List<MetricGroupNode<M>> getMetricGroupNodeList() { return metricGroupNodeList; } @@ -44,7 +44,7 @@ public List<M> getMetrics() { } if (metricGroupNodeList != null) { - for (MetricGroupNode metricGroupNode : metricGroupNodeList) { + for (MetricGroupNode<M> metricGroupNode : metricGroupNodeList) { List<M> metricNodeList = metricGroupNode.getMetrics(); if (metricNodeList != null) { allMetrics.addAll(metricNodeList); diff --git a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/model/rules/TreeViewGroupRule.java b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/model/rules/TreeViewGroupRule.java index d6f889b4a..741b566f9 100644 --- a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/model/rules/TreeViewGroupRule.java +++ b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/model/rules/TreeViewGroupRule.java @@ -50,10 +50,10 @@ public <M extends MetricNode> MetricGroupNode<M> filter(String parentId, List<M> result.setId(id); // first ask all children to filter - List<MetricGroupNode> metricGroupNodeListFromChildren = new ArrayList<MetricGroupNode>(); + List<MetricGroupNode<M>> metricGroupNodeListFromChildren = new ArrayList<MetricGroupNode<M>>(); if (children != null) { for (TreeViewGroupRule child : children) { - MetricGroupNode childResult = child.filter(id,metricNodeList); + MetricGroupNode<M> childResult = child.filter(id,metricNodeList); if (childResult != null) { metricGroupNodeListFromChildren.add(childResult); } diff --git a/webclient/src/main/java/com/griddynamics/jagger/webclient/client/components/AbstractTree.java b/webclient/src/main/java/com/griddynamics/jagger/webclient/client/components/AbstractTree.java new file mode 100644 index 000000000..61c961d52 --- /dev/null +++ b/webclient/src/main/java/com/griddynamics/jagger/webclient/client/components/AbstractTree.java @@ -0,0 +1,230 @@ +package com.griddynamics.jagger.webclient.client.components; + +import com.google.gwt.resources.client.ImageResource; +import com.sencha.gxt.core.client.ValueProvider; +import com.sencha.gxt.data.shared.TreeStore; +import com.sencha.gxt.widget.core.client.event.BeforeCheckChangeEvent; +import com.sencha.gxt.widget.core.client.event.BeforeCollapseItemEvent; +import com.sencha.gxt.widget.core.client.event.BeforeExpandItemEvent; +import com.sencha.gxt.widget.core.client.event.CheckChangeEvent; +import com.sencha.gxt.widget.core.client.tree.Tree; + +/** + * Abstract tree that allows check all children, check parent with no additional events. + * @param <M> the model type + * @param <C> the cell data type + */ +public abstract class AbstractTree<M, C> extends Tree<M, C> { + + /** + * boolean disabled tree or not + * uses for canceling events + */ + protected boolean disabled; + + + /** + * Constructor matches super class + */ + public AbstractTree(TreeStore<M> store, ValueProvider<? super M, C> valueProvider) { + super(store, valueProvider); + } + + + public boolean isDisabled() { + return disabled; + } + + public void setDisabled(boolean disabled) { + this.disabled = disabled; + } + + { + // runs after any constructor + + this.setCheckable(true); + this.setCheckStyle(Tree.CheckCascade.NONE); + this.setCheckNodes(Tree.CheckNodes.BOTH); + + this.addBeforeExpandHandler(new BeforeExpandItemEvent.BeforeExpandItemHandler<M>() { + @Override + public void onBeforeExpand(BeforeExpandItemEvent<M> event) { + if (disabled) + event.setCancelled(true); + } + }); + + this.addBeforeCollapseHandler(new BeforeCollapseItemEvent.BeforeCollapseItemHandler<M>() { + @Override + public void onBeforeCollapse(BeforeCollapseItemEvent<M> event) { + if (disabled) + event.setCancelled(true); + } + }); + + this.addBeforeCheckChangeHandler(new BeforeCheckChangeEvent.BeforeCheckChangeHandler<M>() { + @Override + public void onBeforeCheckChange(BeforeCheckChangeEvent<M> event) { + if (disabled) + event.setCancelled(true); + } + }); + + this.addCheckChangeHandler(new CheckChangeEvent.CheckChangeHandler<M>() { + @Override + public void onCheckChange(CheckChangeEvent<M> event) { + + AbstractTree.this.disableEvents(); + + CheckState state = event.getChecked(); + M item = event.getItem(); + + AbstractTree.this.setStateToSubTree(item, state); + if (state.equals(CheckState.CHECKED)) { + AbstractTree.this.checkParent(item); + AbstractTree.this.setExpanded(item, true, false); + } else { + unCheckParent(item); + } + + AbstractTree.this.enableEvents(); + check(item, state); + } + }); + } + + /** + * SetCheckState without firing any events + * @param item model + * @param state check state + */ + public void setCheckedNoEvents(M item, CheckState state) { + disableEvents(); + setChecked(item, state); + enableEvents(); + } + + /** + * Check subtree + * @param item root ir=tem for subtree + * @param state state to be set to subtree + */ + protected void setStateToSubTree(M item, CheckState state) { + if (store.hasChildren(item)) + for (M child : store.getChildren(item)) { + setChecked(child, state); + setStateToSubTree(child, state); + } + } + + /** + * Check parent. + * Check state of parent = PARTIAL if parent has unchecked or partial checked children, and CHECKED otherwise. + * @param item item witch parent should be checked + */ + protected void checkParent(M item) { + M parent = store.getParent(item); + if (parent == null) return; + + boolean hasUnchecked = false; + + for (M ch : store.getChildren(parent)) { + if (!isChecked(ch) || CheckState.PARTIAL.equals(getChecked(ch))) { + setChecked(parent, CheckState.PARTIAL); + hasUnchecked = true; + break; + } + } + + if (!hasUnchecked) + setChecked(parent, CheckState.CHECKED); + + checkParent(parent); + } + + /** + * Uncheck parent. + * Check state of parent = PARTIAL if parent has checked or partial checked children, and UNCHECKED otherwise. + * @param item item witch parent should be checked + */ + protected void unCheckParent(M item) { + M parent = store.getParent(item); + if (parent == null) return; + boolean hasChecked = false; + for (M ch : store.getChildren(parent)) { + if (AbstractTree.this.getChecked(ch).equals(CheckState.CHECKED) || this.getChecked(ch).equals(CheckState.PARTIAL)) { + this.setChecked(parent, CheckState.PARTIAL); + hasChecked = true; + break; + } + } + if (!hasChecked) + this.setChecked(parent, CheckState.UNCHECKED); + + unCheckParent(parent); + } + + + /** + * No images in tree + */ + @Override + protected ImageResource calculateIconStyle(M model) { + return null; + } + + /** + * disable ability to check/unCheck, collapse/expand actions + */ + @Override + public void disable() { + super.disable(); + setDisabled(true); + } + + /** + * disable ability to check/unCheck, collapse/expand actions + */ + @Override + public void enable() { + super.enable(); + setDisabled(false); + } + + public void enableTree() { + this.enable(); + this.enableEvents(); + } + + public void clearStore() { + store.clear(); + } + + /** + * return false if CheckState = Tree.CheckState.UNCHECKED + * true in other cases + * @param model tree model + * @return bool + */ + public boolean isChosen(M model) { + return !CheckState.UNCHECKED.equals(getChecked(model)); + } + + /** + * Set check state for item with specified id + * @param elementId id of item to set check state + * @param checkState state to set + */ + public void setCheckState(String elementId, CheckState checkState) { + + M model = getStore().findModelWithKey(elementId); + setChecked(model, checkState); + } + + /** + * Check event can goes here + * @param item item that has been checked + * @param state new check state of item in the tree + */ + protected abstract void check(M item, CheckState state); +} diff --git a/webclient/src/main/java/com/griddynamics/jagger/webclient/client/components/ControlTree.java b/webclient/src/main/java/com/griddynamics/jagger/webclient/client/components/ControlTree.java index 529f78476..b6dd9f40a 100644 --- a/webclient/src/main/java/com/griddynamics/jagger/webclient/client/components/ControlTree.java +++ b/webclient/src/main/java/com/griddynamics/jagger/webclient/client/components/ControlTree.java @@ -1,15 +1,11 @@ package com.griddynamics.jagger.webclient.client.components; -import com.google.gwt.resources.client.ImageResource; import com.google.gwt.uibinder.client.UiConstructor; import com.griddynamics.jagger.dbapi.dto.TaskDataDto; import com.griddynamics.jagger.webclient.client.components.control.CheckHandlerMap; import com.griddynamics.jagger.dbapi.model.*; import com.sencha.gxt.core.client.ValueProvider; import com.sencha.gxt.data.shared.TreeStore; -import com.sencha.gxt.widget.core.client.event.BeforeCheckChangeEvent; -import com.sencha.gxt.widget.core.client.event.BeforeCollapseItemEvent; -import com.sencha.gxt.widget.core.client.event.BeforeExpandItemEvent; import com.sencha.gxt.widget.core.client.event.CheckChangeEvent; import com.sencha.gxt.widget.core.client.tree.Tree; @@ -24,15 +20,7 @@ * * @param <C> cell data type */ -public class ControlTree<C> extends Tree <AbstractIdentifyNode, C> { - - - /** - * boolean disabled tree or not - * uses for canceling events - */ - private boolean disabled; - +public class ControlTree<C> extends AbstractTree<AbstractIdentifyNode, C> { /** * Model helps to fetch all data at once @@ -47,130 +35,24 @@ public void setRootNode(RootNode rootNode) { this.rootNode = rootNode; } - public boolean isDisabled() { - return disabled; - } - - public void setDisabled(boolean disabled) { - this.disabled = disabled; - } - - { - - this.addBeforeExpandHandler(new BeforeExpandItemEvent.BeforeExpandItemHandler<AbstractIdentifyNode>() { - @Override - public void onBeforeExpand(BeforeExpandItemEvent<AbstractIdentifyNode> event) { - if (disabled) - event.setCancelled(true); - } - }); - - this.addBeforeCollapseHandler(new BeforeCollapseItemEvent.BeforeCollapseItemHandler<AbstractIdentifyNode>() { - @Override - public void onBeforeCollapse(BeforeCollapseItemEvent<AbstractIdentifyNode> event) { - if (disabled) - event.setCancelled(true); - } - }); - - this.addBeforeCheckChangeHandler(new BeforeCheckChangeEvent.BeforeCheckChangeHandler<AbstractIdentifyNode>() { - @Override - public void onBeforeCheckChange(BeforeCheckChangeEvent<AbstractIdentifyNode> event) { - if (disabled) - event.setCancelled(true); - } - }); - - this.addCheckChangeHandler(new CheckChangeEvent.CheckChangeHandler<AbstractIdentifyNode>() { - @Override - public void onCheckChange(CheckChangeEvent<AbstractIdentifyNode> event) { - - tree.disableEvents(); - check(event.getItem(), event.getChecked()); - } - - private void check(AbstractIdentifyNode item, CheckState state) { - checkSubTree(item, state); - if (state.equals(CheckState.CHECKED)) { - checkParent(item); - tree.setExpanded(item, true, false); - } else { - unCheckParent(item); - } - - tree.enableEvents(); - if (CheckHandlerMap.getHandler(item.getClass()) != null) { - CheckHandlerMap.getHandler(item.getClass()) - .onCheckChange(new CheckChangeEvent(item, state)); - } - } - - private Tree<AbstractIdentifyNode, C> tree = ControlTree.this; - private TreeStore<AbstractIdentifyNode> treeStore = ControlTree.this.getStore(); - - - - private void unCheckParent(AbstractIdentifyNode item) { - AbstractIdentifyNode parent = treeStore.getParent(item); - if (parent == null) return; - boolean hasChecked = false; - for (AbstractIdentifyNode ch : treeStore.getChildren(parent)) { - if (tree.getChecked(ch).equals(CheckState.CHECKED) || tree.getChecked(ch).equals(CheckState.PARTIAL)) { - tree.setChecked(parent, CheckState.PARTIAL); - hasChecked = true; - break; - } - } - if (!hasChecked) - tree.setChecked(parent, CheckState.UNCHECKED); - - unCheckParent(parent); - } - - - }); - } - - private void checkSubTree(AbstractIdentifyNode item, CheckState state) { - if (store.hasChildren(item)) - for (AbstractIdentifyNode child : store.getChildren(item)) { - setChecked(child, state); - checkSubTree(child, state); - } - } - public void checkParent(AbstractIdentifyNode item) { - AbstractIdentifyNode parent = store.getParent(item); - if (parent == null) return; - - boolean hasUnchecked = false; - - for (AbstractIdentifyNode ch : store.getChildren(parent)) { - if (!isChecked(ch) || CheckState.PARTIAL.equals(getChecked(ch))) { - setChecked(parent, CheckState.PARTIAL); - hasUnchecked = true; - break; - } - } - - if (!hasUnchecked) - setChecked(parent, CheckState.CHECKED); - - checkParent(parent); + @Override + protected void check(AbstractIdentifyNode item, CheckState state) { + CheckHandlerMap.getHandler(item.getClass()) + .onCheckChange(new CheckChangeEvent(item, state)); } - public void setCheckedWithParent (AbstractIdentifyNode item) { setChecked(item, Tree.CheckState.CHECKED); - checkSubTree(item, Tree.CheckState.CHECKED); + setStateToSubTree(item, Tree.CheckState.CHECKED); checkParent(item); } public void setCheckedExpandedWithParent (AbstractIdentifyNode item) { setChecked(item, Tree.CheckState.CHECKED); - checkSubTree(item, Tree.CheckState.CHECKED); + setStateToSubTree(item, Tree.CheckState.CHECKED); checkParent(item); setExpanded(item, true, false); } @@ -180,38 +62,6 @@ public ControlTree(TreeStore<AbstractIdentifyNode> store, ValueProvider<? super super(store, valueProvider); } - @Override - protected ImageResource calculateIconStyle(AbstractIdentifyNode model) { - return null; - } - - /** - * disable ability to check/unCheck, collapse/expand actions - */ - @Override - public void disable() { - super.disable(); - setDisabled(true); - } - - /** - * disable ability to check/unCheck, collapse/expand actions - */ - @Override - public void enable() { - super.enable(); - setDisabled(false); - } - - public void enableTree() { - this.enable(); - this.enableEvents(); - } - - public void clearStore() { - store.clear(); - } - /** * results should be chosen from both Summary and Details subtree * @return List<TaskDataDto> to use the same link creator. @@ -254,11 +104,11 @@ public Set<MetricNode> getCheckedMetrics() { public Set<MetricNode> getCheckedMetrics(TestNode testNode) { Set<MetricNode> resultSet = new HashSet<MetricNode>(); - for (MetricNode metricNode : testNode.getMetrics()) { - if (isChecked(metricNode)) { - resultSet.add(metricNode); - } + for (MetricNode metricNode : testNode.getMetrics()) { + if (isChecked(metricNode)) { + resultSet.add(metricNode); } + } return resultSet; } @@ -293,16 +143,6 @@ public Set<MetricNode> getCheckedPlots() { } - /** - * return false if CheckState = Tree.CheckState.UNCHECKED - * true in other cases - * @param model tree model - * @return bool - */ - public boolean isChosen(AbstractIdentifyNode model) { - return !CheckState.UNCHECKED.equals(getChecked(model)); - } - public void onSummaryTrendsTab() { onMetricsTab(false); } @@ -317,10 +157,4 @@ private void onMetricsTab(boolean boo) { setExpanded(rootNode.getDetailsNode(), boo); } } - - public void setCheckState(String elementId, CheckState checkState) { - - AbstractIdentifyNode abstractIdentifyNode = getStore().findModelWithKey(elementId); - setChecked(abstractIdentifyNode, checkState); - } } \ No newline at end of file diff --git a/webclient/src/main/java/com/griddynamics/jagger/webclient/client/components/LegendTree.java b/webclient/src/main/java/com/griddynamics/jagger/webclient/client/components/LegendTree.java new file mode 100644 index 000000000..a8cd431ab --- /dev/null +++ b/webclient/src/main/java/com/griddynamics/jagger/webclient/client/components/LegendTree.java @@ -0,0 +1,141 @@ +package com.griddynamics.jagger.webclient.client.components; + +import com.google.gwt.core.client.JsArray; +import com.googlecode.gflot.client.DataPoint; +import com.googlecode.gflot.client.Series; +import com.googlecode.gflot.client.SeriesHandler; +import com.googlecode.gflot.client.SimplePlot; +import com.griddynamics.jagger.dbapi.dto.PlotSingleDto; +import com.griddynamics.jagger.dbapi.dto.PointDto; +import com.griddynamics.jagger.dbapi.model.LegendNode; +import com.griddynamics.jagger.webclient.client.components.control.LegendNodeCell; +import com.sencha.gxt.core.client.ValueProvider; +import com.sencha.gxt.data.shared.ModelKeyProvider; +import com.sencha.gxt.data.shared.TreeStore; + +/** + * Implementation of AbstractTree that represents interactive legend as tree. + */ +public class LegendTree extends AbstractTree<LegendNode, LegendNode> { + + /** + * Plot that would controlled with Legend tree + */ + private SimplePlot plot; + + /** + * Plots panel where plot is situated + */ + private PlotsPanel plotsPanel; + + + private final static ValueProvider<LegendNode, LegendNode> VALUE_PROVIDER = new ValueProvider<LegendNode, LegendNode>() { + + @Override + public LegendNode getValue(LegendNode object) { + return object; + } + + @Override + public void setValue(LegendNode object, LegendNode value) { + object.setDisplayName(value.getDisplayName()); + object.setMetricNameDtoList(value.getMetricNameDtoList()); + object.setId(value.getId()); + object.setLine(value.getLine()); + } + + @Override + public String getPath() { + return "legend"; + } + }; + + /** + * Constructor matches super class + */ + public LegendTree(SimplePlot plot, PlotsPanel plotsPanel) { + super( + new TreeStore<LegendNode>(new ModelKeyProvider<LegendNode>() { + @Override + public String getKey(LegendNode item) { + return item.getId(); + } + }), + VALUE_PROVIDER); + this.plot = plot; + this.plotsPanel = plotsPanel; + + this.setAutoExpand(true); + this.setCell(LegendNodeCell.getInstance()); + } + + @Override + protected void check(LegendNode item, CheckState state) { + noRedrawCheck(item, state); + redrawPlot(); + } + + /** + * Adds or removes lines without redrawing plot. Changes can't be seen. + * @param item chosen item + * @param state check state + */ + private void noRedrawCheck(LegendNode item, CheckState state) { + PlotSingleDto plotSingleDto = item.getLine(); + + if (plotSingleDto != null) { + + if (state == CheckState.CHECKED) { + + Series series = Series.create().setId(item.getId()).setColor(plotSingleDto.getColor()); + SeriesHandler sh = plot.getModel().addSeries(series); + for (PointDto point: plotSingleDto.getPlotData()) { + sh.add(DataPoint.of(point.getX(), point.getY())); + } + + } else if (state == CheckState.UNCHECKED) { + + // remove curve from view + JsArray<Series> seriesArray = plot.getModel().getSeries(); + int k; + for (k = 0; k < seriesArray.length(); k++) { + Series curSeries = seriesArray.get(k); + // label used as id + if (curSeries.getId().equals(item.getId())) { + // found + break; + } + } + if (k < seriesArray.length()) { + plot.getModel().removeSeries(k); + } + } + } else { + for (LegendNode child : store.getAllChildren(item)) { + noRedrawCheck(child, state); + } + } + } + + /** + * Redraw plot with specific axis ranges + */ + private void redrawPlot() { + if (!plotsPanel.isEmpty()) { + double minXVisible = plotsPanel.getMinXAxisVisibleValue(); + double maxXVisible = plotsPanel.getMaxXAxisVisibleValue(); + + if (plot.isAttached()) { + double minYVisible = plot.getAxes().getY().getMinimumValue(); + double maxYVisible = plot.getAxes().getY().getMaximumValue(); + + // save y axis range for plot from very start + plot.getOptions().getYAxisOptions().setMinimum(minYVisible).setMaximum(maxYVisible); + } + + // set x axis in range as all other plots + plot.getOptions().getXAxisOptions().setMinimum(minXVisible).setMaximum(maxXVisible); + plot.redraw(); + } + } +} diff --git a/webclient/src/main/java/com/griddynamics/jagger/webclient/client/components/control/LegendNodeCell.java b/webclient/src/main/java/com/griddynamics/jagger/webclient/client/components/control/LegendNodeCell.java new file mode 100644 index 000000000..56c076a2e --- /dev/null +++ b/webclient/src/main/java/com/griddynamics/jagger/webclient/client/components/control/LegendNodeCell.java @@ -0,0 +1,26 @@ +package com.griddynamics.jagger.webclient.client.components.control; + +import com.google.gwt.cell.client.AbstractCell; +import com.google.gwt.safehtml.shared.SafeHtmlBuilder; +import com.griddynamics.jagger.dbapi.model.LegendNode; + +public class LegendNodeCell extends AbstractCell<LegendNode> { + @Override + public void render(Context context, LegendNode value, SafeHtmlBuilder sb) { + sb.appendHtmlConstant( + (value.getLine() != null ? "<font color=\'" + value.getLine().getColor() + "\'>&#9604;&#9604;</font>" : "") + + "<font> " + value.getDisplayName() + "</font>"); + } + + private static LegendNodeCell cell; + + private LegendNodeCell() {} + + public static LegendNodeCell getInstance() { + if (cell == null) { + cell = new LegendNodeCell(); + } + + return cell; + } +} \ No newline at end of file diff --git a/webclient/src/main/java/com/griddynamics/jagger/webclient/client/trends/Trends.java b/webclient/src/main/java/com/griddynamics/jagger/webclient/client/trends/Trends.java index f5a9559ed..97f7b8990 100644 --- a/webclient/src/main/java/com/griddynamics/jagger/webclient/client/trends/Trends.java +++ b/webclient/src/main/java/com/griddynamics/jagger/webclient/client/trends/Trends.java @@ -640,6 +640,7 @@ public String formatTickValue(double tickValue, Axis axis) { }) .setZoomRange(false).setMinimum(yMinimum)); + // todo : setShow(false) plotOptions.setLegendOptions(LegendOptions.create().setPosition(LegendOptions.LegendPosition.NORTH_EAST) .setNumOfColumns(2) .setBackgroundOpacity(0.7) @@ -1047,7 +1048,6 @@ private void renderPlots(final PlotsPanel panel, List<PlotIntegratedDto> plotSer } final SimplePlot plot; - PlotModel plotModel; if (isMetric) { List<Integer> sessionIds = new ArrayList<Integer>(); for (PlotSingleDto plotDatasetDto : plotSeriesDto.getPlotSeries()) { @@ -1060,31 +1060,17 @@ private void renderPlots(final PlotsPanel panel, List<PlotIntegratedDto> plotSer } } Collections.sort(sessionIds); - plot = createPlot(panel, id, markings, plotSeriesDto.getXAxisLabel(), yMinimum, isMetric, sessionIds); - plotModel = plot.getModel(); - redrawingPlot = plot; - for (PlotSingleDto plotDatasetDto : plotSeriesDto.getPlotSeries()) { - Series se = Series.create().setLabel(plotDatasetDto.getLegend()).setColor(plotDatasetDto.getColor()); - SeriesHandler handler = plotModel.addSeries(se); - // Populate plot with data - for (PointDto pointDto : plotDatasetDto.getPlotData()) { - handler.add(DataPoint.of(sessionIds.indexOf((int) pointDto.getX()), pointDto.getY())); - } - } + plot = createPlot(panel, id, markings, plotSeriesDto.getXAxisLabel(), yMinimum, true, sessionIds); } else { - plot = createPlot(panel, id, markings, plotSeriesDto.getXAxisLabel(), yMinimum, isMetric, null); - plotModel = plot.getModel(); - redrawingPlot = plot; - for (PlotSingleDto plotDatasetDto : plotSeriesDto.getPlotSeries()) { - Series se = Series.create().setLabel(plotDatasetDto.getLegend()).setColor(plotDatasetDto.getColor()); - SeriesHandler handler = plotModel.addSeries(se); - - // Populate plot with data - for (PointDto pointDto : plotDatasetDto.getPlotData()) { - handler.add(DataPoint.of(pointDto.getX(), pointDto.getY())); - } - } + plot = createPlot(panel, id, markings, plotSeriesDto.getXAxisLabel(), yMinimum, false, null); } + redrawingPlot = plot; + + LegendTree legendTree = new LegendTree(plot, panel); + MetricGroupNode<LegendNode> inTree = plotSeriesDto.getLegendTree(); + + // populate legend tree with data + translateIntoLegendTree(inTree, legendTree, null); // Add X axis label final String xAxisLabel = plotSeriesDto.getXAxisLabel(); @@ -1127,7 +1113,6 @@ public void onClick(ClickEvent event) { zoomPanel.add(zoomOutLabel); zoomPanel.add(zoomBack); - ControlTree legendTree = createLegendTree(plotSeriesDto); SimplePanel sp = new SimplePanel(); sp.setWidget(legendTree); @@ -1145,55 +1130,53 @@ public void onClick(ClickEvent event) { } } - private ControlTree createLegendTree(PlotIntegratedDto plotSeriesDto) { - if (plotSeriesDto.getLegendTree() == null) - return null; + /** + * Populate legend tree with data. + * @param inTree model of tree with data + * @param tree legend tree that will be populated with data + * @param parent parent legend node. Pass 'null' to add legend nodes, in current level, as root items. + */ + private void translateIntoLegendTree( + MetricGroupNode<LegendNode> inTree, + LegendTree tree, + LegendNode parent) { - return createControlTree(plotSeriesDto.getLegendTree()); - } + if (inTree == null) + return; + // child groups + if (inTree.getMetricGroupNodeList() != null) { + for (MetricGroupNode<LegendNode> metricGroup : inTree.getMetricGroupNodeList()) { - private ControlTree<String> createControlTree(AbstractIdentifyNode result) { + // create LegendNode that will represent group node + LegendNode metricNodeAsGroup = new LegendNode(); + metricNodeAsGroup.setId(metricGroup.getId()); + metricNodeAsGroup.setDisplayName(metricGroup.getDisplayName()); - TreeStore<AbstractIdentifyNode> temporaryStore = new TreeStore<AbstractIdentifyNode>(new ModelKeyProvider<AbstractIdentifyNode>() { + if (parent == null) { + // add as root node + tree.getStore().add(metricNodeAsGroup); + } else { + tree.getStore().add(parent, metricNodeAsGroup); + } + tree.setCheckedNoEvents(metricNodeAsGroup, Tree.CheckState.CHECKED); - @Override - public String getKey(AbstractIdentifyNode item) { - return item.getId(); + translateIntoLegendTree(metricGroup, tree, metricNodeAsGroup); } - }); - ControlTree<String> newTree = new ControlTree<String>(temporaryStore, new SimpleNodeValueProvider()); - - for (AbstractIdentifyNode node : result.getChildren()) { - addToStore(temporaryStore, node); } - newTree.setCheckable(true); - newTree.setCheckStyle(Tree.CheckCascade.NONE); - newTree.setCheckNodes(Tree.CheckNodes.BOTH); - - return newTree; - } - - private void addToStore(TreeStore<AbstractIdentifyNode> store, AbstractIdentifyNode node) { - store.add(node); - - for (AbstractIdentifyNode child : node.getChildren()) { - addToStore(store, child, node); - } - } - - private void addToStore(TreeStore<AbstractIdentifyNode> store, AbstractIdentifyNode node, AbstractIdentifyNode parent) { - store.add(parent, node); - for (AbstractIdentifyNode child : node.getChildren()) { + // metrics in group + if (inTree.getMetricsWithoutChildren() != null) { + for (LegendNode metricNode : inTree.getMetricsWithoutChildren()) { + if (parent == null) { + // add as root nodes + tree.getStore().add(metricNode); + } else { + tree.getStore().add(parent, metricNode); + } - try { - addToStore(store, child, node); - } - catch (AssertionError e) { - new ExceptionPanel(place, "Was not able to insert node with id '" + child.getId() + "' and name '" - + child.getDisplayName() + "' into control tree. Id is already in use. Error message:\n" + e.getMessage()); + tree.setChecked(metricNode, Tree.CheckState.CHECKED); } } } @@ -1538,6 +1521,41 @@ private void fetchSessionInfoData(SessionInfoNode sessionInfoNode) { summaryPanel.getSessionComparisonPanel().addSessionInfo(); } } + + private ControlTree<String> createControlTree(RootNode result) { + + TreeStore<AbstractIdentifyNode> temporaryStore = new TreeStore<AbstractIdentifyNode>(modelKeyProvider); + ControlTree<String> newTree = new ControlTree<String>(temporaryStore, new SimpleNodeValueProvider()); + setupControlTree(newTree); + + for (AbstractIdentifyNode node : result.getChildren()) { + addToStore(temporaryStore, node); + } + + return newTree; + } + + private void addToStore(TreeStore<AbstractIdentifyNode> store, AbstractIdentifyNode node) { + store.add(node); + + for (AbstractIdentifyNode child : node.getChildren()) { + addToStore(store, child, node); + } + } + + private void addToStore(TreeStore<AbstractIdentifyNode> store, AbstractIdentifyNode node, AbstractIdentifyNode parent) { + store.add(parent, node); + for (AbstractIdentifyNode child : node.getChildren()) { + + try { + addToStore(store, child, node); + } + catch (AssertionError e) { + new ExceptionPanel(place, "Was not able to insert node with id '" + child.getId() + "' and name '" + + child.getDisplayName() + "' into control tree. Id is already in use. Error message:\n" + e.getMessage()); + } + } + } }
079039e5531a152388776c637884c891974008e5
restlet-framework-java
Fixed generation of cache directives in the- cache-control header.--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet/src/org/restlet/data/CacheDirective.java b/modules/org.restlet/src/org/restlet/data/CacheDirective.java index ea761871b3..d76af1d136 100644 --- a/modules/org.restlet/src/org/restlet/data/CacheDirective.java +++ b/modules/org.restlet/src/org/restlet/data/CacheDirective.java @@ -65,7 +65,7 @@ public final class CacheDirective extends Parameter { */ public static CacheDirective maxAge(int maxAge) { return new CacheDirective(HttpConstants.CACHE_MAX_AGE, Integer - .toString(maxAge)); + .toString(maxAge), true); } /** @@ -100,7 +100,7 @@ public static CacheDirective maxStale() { */ public static CacheDirective maxStale(int maxStale) { return new CacheDirective(HttpConstants.CACHE_MAX_STALE, Integer - .toString(maxStale)); + .toString(maxStale), true); } /** @@ -121,7 +121,7 @@ public static CacheDirective maxStale(int maxStale) { */ public static CacheDirective minFresh(int minFresh) { return new CacheDirective(HttpConstants.CACHE_MIN_FRESH, Integer - .toString(minFresh)); + .toString(minFresh), true); } /** @@ -366,9 +366,12 @@ public static CacheDirective publicInfo() { */ public static CacheDirective sharedMaxAge(int sharedMaxAge) { return new CacheDirective(HttpConstants.CACHE_SHARED_MAX_AGE, Integer - .toString(sharedMaxAge)); + .toString(sharedMaxAge), true); } + /** Indicates if the directive is a digit value. */ + private boolean digit; + /** * Constructor for directives with no value. * @@ -388,7 +391,40 @@ public CacheDirective(String name) { * The directive value. */ public CacheDirective(String name, String value) { + this(name, value, false); + } + + /** + * Constructor for directives with a value. + * + * @param name + * The directive name. + * @param value + * The directive value. + * @param digit + * The kind of value (true for a digit value, false otherwise). + */ + public CacheDirective(String name, String value, boolean digit) { super(name, value); + this.digit = digit; + } + + /** + * Returns true if the directive contains a digit value. + * + * @return True if the directive contains a digit value. + */ + public boolean isDigit() { + return digit; } + /** + * Indicates if the directive is a digit value. + * + * @param digit + * True if the directive contains a digit value. + */ + public void setDigit(boolean digit) { + this.digit = digit; + } } \ No newline at end of file diff --git a/modules/org.restlet/src/org/restlet/engine/http/CacheControlUtils.java b/modules/org.restlet/src/org/restlet/engine/http/CacheControlUtils.java index 2cb24cb23c..fa03ab607a 100644 --- a/modules/org.restlet/src/org/restlet/engine/http/CacheControlUtils.java +++ b/modules/org.restlet/src/org/restlet/engine/http/CacheControlUtils.java @@ -84,7 +84,12 @@ public static void format(CacheDirective directive, Appendable destination) destination.append(directive.getName()); if ((directive.getValue() != null) && (directive.getValue().length() > 0)) { - destination.append("=\"").append(directive.getValue()).append('\"'); + if (directive.isDigit()) { + destination.append("=").append(directive.getValue()); + } else { + destination.append("=\"").append(directive.getValue()).append( + '\"'); + } } } }
c875e8e95e946a84128f141afb22e449cbb1a024
sanity$quickml
added flexibility to pass in a PredictiveModelBuilder to a StaticBuilder method
p
https://github.com/sanity/quickml
diff --git a/pom.xml b/pom.xml index a14482ec..6877efa7 100644 --- a/pom.xml +++ b/pom.xml @@ -32,7 +32,7 @@ be accompanied by a bump in version number, regardless of how minor the change. --> - <version>0.7.2</version> + <version>0.7.3</version> <repositories> diff --git a/src/main/java/quickml/supervised/classifier/StaticBuilders.java b/src/main/java/quickml/supervised/classifier/StaticBuilders.java index 51789c96..52820a1c 100644 --- a/src/main/java/quickml/supervised/classifier/StaticBuilders.java +++ b/src/main/java/quickml/supervised/classifier/StaticBuilders.java @@ -48,7 +48,7 @@ public class StaticBuilders { private static final Logger logger = LoggerFactory.getLogger(StaticBuilders.class); - public static <T extends ClassifierInstance> Pair<Map<String, Object>, DownsamplingClassifier> getOptimizedDownsampledRandomForest(List<T> trainingData, int rebuildsPerValidation, double fractionOfDataForValidation, ClassifierLossFunction lossFunction, DateTimeExtractor dateTimeExtractor, Map<String, FieldValueRecommender> config) { + public static <T extends ClassifierInstance> Pair<Map<String, Object>, DownsamplingClassifier> getOptimizedDownsampledRandomForest(List<T> trainingData, int rebuildsPerValidation, double fractionOfDataForValidation, ClassifierLossFunction lossFunction, DateTimeExtractor dateTimeExtractor, DownsamplingClassifierBuilder<ClassifierInstance> modelBuilder, Map<String, FieldValueRecommender> config) { /** * @param rebuildsPerValidation is the number of times the model will be rebuilt with a new training set while estimating the loss of a model * with a prarticular set of hyperparameters @@ -60,8 +60,9 @@ public static <T extends ClassifierInstance> Pair<Map<String, Object>, Downsampl double crossValidationFraction = 0.2; TrainingDataCycler<T> outOfTimeData = new OutOfTimeData<T>(trainingData, crossValidationFraction, timeSliceHours, dateTimeExtractor); ClassifierLossChecker<T> classifierInstanceClassifierLossChecker = new ClassifierLossChecker<>(lossFunction); + PredictiveModelOptimizer optimizer= new PredictiveModelOptimizerBuilder<Classifier, T>() - .modelBuilder(new RandomForestBuilder<>()) + .modelBuilder(modelBuilder) .dataCycler(outOfTimeData) .lossChecker(classifierInstanceClassifierLossChecker) .valuesToTest(config) @@ -75,7 +76,13 @@ public static <T extends ClassifierInstance> Pair<Map<String, Object>, Downsampl DownsamplingClassifier downsamplingClassifier = downsamplingClassifierBuilder.buildPredictiveModel(trainingData); return new Pair<Map<String, Object>, DownsamplingClassifier>(bestParams, downsamplingClassifier); } - public static Pair<Map<String, Object>, DownsamplingClassifier> getOptimizedDownsampledRandomForest(List<? extends ClassifierInstance> trainingData, int rebuildsPerValidation, double fractionOfDataForValidation, ClassifierLossFunction lossFunction, DateTimeExtractor dateTimeExtractor) { + + public static <T extends ClassifierInstance> Pair<Map<String, Object>, DownsamplingClassifier> getOptimizedDownsampledRandomForest(List<T> trainingData, int rebuildsPerValidation, double fractionOfDataForValidation, ClassifierLossFunction lossFunction, DateTimeExtractor dateTimeExtractor, Map<String, FieldValueRecommender> config) { + DownsamplingClassifierBuilder<ClassifierInstance> modelBuilder = new DownsamplingClassifierBuilder<>(new RandomForestBuilder<>(), .1); + return getOptimizedDownsampledRandomForest(trainingData, rebuildsPerValidation, fractionOfDataForValidation, lossFunction, dateTimeExtractor, modelBuilder, config); + + } + public static Pair<Map<String, Object>, DownsamplingClassifier> getOptimizedDownsampledRandomForest(List<? extends ClassifierInstance> trainingData, int rebuildsPerValidation, double fractionOfDataForValidation, ClassifierLossFunction lossFunction, DateTimeExtractor dateTimeExtractor) { Map<String, FieldValueRecommender> config = createConfig(); return getOptimizedDownsampledRandomForest(trainingData, rebuildsPerValidation, fractionOfDataForValidation, lossFunction, dateTimeExtractor, config); }
208ea0a6b87fd52c4e8f7515af2f3546ff8758a5
Vala
libnl-2.0: add linux as a dependency
c
https://github.com/GNOME/vala/
diff --git a/vapi/Makefile.am b/vapi/Makefile.am index d11c93c757..5c33e6e205 100644 --- a/vapi/Makefile.am +++ b/vapi/Makefile.am @@ -130,6 +130,7 @@ dist_vapi_DATA = \ libgvc.vapi \ libmagic.vapi \ libnl-1.vapi \ + libnl-2.0.deps \ libnl-2.0.vapi \ libnotify.deps \ libnotify.vapi \ diff --git a/vapi/libnl-2.0.deps b/vapi/libnl-2.0.deps new file mode 100644 index 0000000000..a08e1f35eb --- /dev/null +++ b/vapi/libnl-2.0.deps @@ -0,0 +1 @@ +linux
cc19d3029ab0db137da0e95cc55c20b131241cf1
jhy$jsoup
Reverted Node.equals() and Node.hashCode() Back to identity (object) comparisons, as deep content inspection had negative performance impacts and hashkey stability problems. Functionality replaced with Node.hasSameContent().
p
https://github.com/jhy/jsoup
diff --git a/CHANGES b/CHANGES index 6ec4df62bf..e9b93d5ac2 100644 --- a/CHANGES +++ b/CHANGES @@ -32,6 +32,10 @@ jsoup changelog incorrectly, leading to the original loads being lost. <https://github.com/jhy/jsoup/issues/689> + * Reverted Node.equals() and Node.hashCode() back to identity (object) comparisons, as deep content inspection + had negative performance impacts and hashkey stability problems. Functionality replaced with Node.hasSameContent(). + <https://github.com/jhy/jsoup/issues/688> + *** Release 1.8.3 [2015-Aug-02] * Added support for custom boolean attributes. <https://github.com/jhy/jsoup/pull/555> diff --git a/src/main/java/org/jsoup/nodes/Element.java b/src/main/java/org/jsoup/nodes/Element.java index cb6bf14d2f..1761026989 100644 --- a/src/main/java/org/jsoup/nodes/Element.java +++ b/src/main/java/org/jsoup/nodes/Element.java @@ -1198,24 +1198,6 @@ public String toString() { return outerHtml(); } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; - - Element element = (Element) o; - - return tag.equals(element.tag); - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (tag != null ? tag.hashCode() : 0); - return result; - } - @Override public Element clone() { return (Element) super.clone(); diff --git a/src/main/java/org/jsoup/nodes/Node.java b/src/main/java/org/jsoup/nodes/Node.java index b6bdb93b61..8f09a7f013 100644 --- a/src/main/java/org/jsoup/nodes/Node.java +++ b/src/main/java/org/jsoup/nodes/Node.java @@ -574,34 +574,30 @@ protected void indent(StringBuilder accum, int depth, Document.OutputSettings ou } /** - * Check if this node is equal to another node. A node is considered equal if its attributes and content equal the - * other node; particularly its position in the tree does not influence its equality. + * Check if this node is the same instance of another (object identity test). * @param o other object to compare to * @return true if the content of this node is the same as the other + * @see Node#hasSameValue(Object) to compare nodes by their value */ @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Node node = (Node) o; - - if (childNodes != null ? !childNodes.equals(node.childNodes) : node.childNodes != null) return false; - return !(attributes != null ? !attributes.equals(node.attributes) : node.attributes != null); + // implemented just so that javadoc is clear this is an identity test + return this == o; } /** - * Calculates a hash code for this node, which includes iterating all its attributes, and recursing into any child - * nodes. This means that a node's hashcode is based on it and its child content, and not its parent or place in the - * tree. So two nodes with the same content, regardless of their position in the tree, will have the same hashcode. - * @return the calculated hashcode - * @see Node#equals(Object) + * Check if this node is has the same content as another node. A node is considered the same if its name, attributes and content match the + * other node; particularly its position in the tree does not influence its similarity. + * @param o other object to compare to + * @return true if the content of this node is the same as the other */ - @Override - public int hashCode() { - int result = childNodes != null ? childNodes.hashCode() : 0; - result = 31 * result + (attributes != null ? attributes.hashCode() : 0); - return result; + + public boolean hasSameValue(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Node node = (Node) o; + return this.outerHtml().equals(((Node) o).outerHtml()); } /** diff --git a/src/main/java/org/jsoup/nodes/TextNode.java b/src/main/java/org/jsoup/nodes/TextNode.java index e9055d4257..2eebe31606 100644 --- a/src/main/java/org/jsoup/nodes/TextNode.java +++ b/src/main/java/org/jsoup/nodes/TextNode.java @@ -172,22 +172,4 @@ public String absUrl(String attributeKey) { ensureAttributes(); return super.absUrl(attributeKey); } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; - - TextNode textNode = (TextNode) o; - - return !(text != null ? !text.equals(textNode.text) : textNode.text != null); - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (text != null ? text.hashCode() : 0); - return result; - } } diff --git a/src/test/java/org/jsoup/nodes/DocumentTest.java b/src/test/java/org/jsoup/nodes/DocumentTest.java index 4ed2b36247..207dc6ff6f 100644 --- a/src/test/java/org/jsoup/nodes/DocumentTest.java +++ b/src/test/java/org/jsoup/nodes/DocumentTest.java @@ -156,11 +156,20 @@ public class DocumentTest { Document docB = Jsoup.parse("<div/>One"); Document docC = Jsoup.parse("<div/>Two"); - assertEquals(docA, docB); - assertFalse(docA.equals(docC)); - assertEquals(docA.hashCode(), docB.hashCode()); + assertFalse(docA.equals(docB)); + assertTrue(docA.equals(docA)); + assertEquals(docA.hashCode(), docA.hashCode()); assertFalse(docA.hashCode() == docC.hashCode()); } + + @Test public void DocumentsWithSameContentAreVerifialbe() throws Exception { + Document docA = Jsoup.parse("<div/>One"); + Document docB = Jsoup.parse("<div/>One"); + Document docC = Jsoup.parse("<div/>Two"); + + assertTrue(docA.hasSameValue(docB)); + assertFalse(docA.hasSameValue(docC)); + } @Test public void testMetaCharsetUpdateUtf8() { diff --git a/src/test/java/org/jsoup/nodes/ElementTest.java b/src/test/java/org/jsoup/nodes/ElementTest.java index ec223ab4d8..73e4db7715 100644 --- a/src/test/java/org/jsoup/nodes/ElementTest.java +++ b/src/test/java/org/jsoup/nodes/ElementTest.java @@ -798,7 +798,9 @@ public void testClassNames() { } @Test - public void testHashAndEquals() { + public void testHashAndEqualsAndValue() { + // .equals and hashcode are identity. value is content. + String doc1 = "<div id=1><p class=one>One</p><p class=one>One</p><p class=one>Two</p><p class=two>One</p></div>" + "<div id=2><p class=one>One</p><p class=one>One</p><p class=one>Two</p><p class=two>One</p></div>"; @@ -829,17 +831,17 @@ public void testHashAndEquals() { Element e6 = els.get(6); Element e7 = els.get(7); - assertEquals(e0, e1); - assertEquals(e0, e4); - assertEquals(e0, e5); + assertEquals(e0, e0); + assertTrue(e0.hasSameValue(e1)); + assertTrue(e0.hasSameValue(e4)); + assertTrue(e0.hasSameValue(e5)); assertFalse(e0.equals(e2)); - assertFalse(e0.equals(e3)); - assertFalse(e0.equals(e6)); - assertFalse(e0.equals(e7)); + assertFalse(e0.hasSameValue(e2)); + assertFalse(e0.hasSameValue(e3)); + assertFalse(e0.hasSameValue(e6)); + assertFalse(e0.hasSameValue(e7)); - assertEquals(e0.hashCode(), e1.hashCode()); - assertEquals(e0.hashCode(), e4.hashCode()); - assertEquals(e0.hashCode(), e5.hashCode()); + assertEquals(e0.hashCode(), e0.hashCode()); assertFalse(e0.hashCode() == (e2.hashCode())); assertFalse(e0.hashCode() == (e3).hashCode()); assertFalse(e0.hashCode() == (e6).hashCode()); @@ -876,6 +878,17 @@ public void appendMustCorrectlyMoveChildrenInsideOneParentElement() { String result = doc.toString().replaceAll("\\s+", ""); assertEquals("<body><div3>Check</div3><div4></div4><div1></div1><div2></div2></body>", result); + } + + @Test + public void testHashcodeIsStableWithContentChanges() { + Element root = new Element(Tag.valueOf("root"), ""); + + HashSet<Element> set = new HashSet<Element>(); + // Add root node: + set.add(root); + root.appendChild(new Element(Tag.valueOf("a"), "")); + assertTrue(set.contains(root)); } }
fdc7205adae52d9e2d928d06faacf9cc9f216b55
camel
CAMEL-4176: Fixed fallback to use http4 or http4s- for proxy scheme when configured as property on CamelContext properties.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1144310 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/camel
diff --git a/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpComponent.java b/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpComponent.java index f6431545bdbd1..d90a257eddac2 100644 --- a/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpComponent.java +++ b/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpComponent.java @@ -22,6 +22,7 @@ import org.apache.camel.Endpoint; import org.apache.camel.ResolveEndpointFailedException; +import org.apache.camel.component.http4.helper.HttpHelper; import org.apache.camel.impl.HeaderFilterStrategyComponent; import org.apache.camel.util.CastUtils; import org.apache.camel.util.IntrospectionSupport; @@ -182,7 +183,7 @@ protected Endpoint createEndpoint(String uri, String remaining, Map<String, Obje sslContextParameters = this.sslContextParameters; } - boolean secure = isSecureConnection(uri); + boolean secure = HttpHelper.isSecureConnection(uri); // create the configurer to use for this endpoint HttpClientConfigurer configurer = createHttpClientConfigurer(parameters, secure); @@ -301,10 +302,6 @@ protected HttpParams configureHttpParams(Map<String, Object> parameters) throws return clientParams; } - private boolean isSecureConnection(String uri) { - return uri.startsWith("https"); - } - @Override protected boolean useIntrospectionOnEndpoint() { return false; diff --git a/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpEndpoint.java b/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpEndpoint.java index 4ba78fba70a5b..c0a87d5da7e98 100644 --- a/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpEndpoint.java +++ b/components/camel-http4/src/main/java/org/apache/camel/component/http4/HttpEndpoint.java @@ -21,6 +21,7 @@ import org.apache.camel.PollingConsumer; import org.apache.camel.Producer; +import org.apache.camel.component.http4.helper.HttpHelper; import org.apache.camel.impl.DefaultPollingEndpoint; import org.apache.camel.spi.HeaderFilterStrategy; import org.apache.camel.spi.HeaderFilterStrategyAware; @@ -117,6 +118,10 @@ protected HttpClient createHttpClient() { String host = getCamelContext().getProperties().get("http.proxyHost"); int port = Integer.parseInt(getCamelContext().getProperties().get("http.proxyPort")); String scheme = getCamelContext().getProperties().get("http.proxyScheme"); + // fallback and use either http4 or https4 depending on secure + if (scheme == null) { + scheme = HttpHelper.isSecureConnection(getEndpointUri()) ? "https4" : "http4"; + } LOG.debug("CamelContext properties http.proxyHost, http.proxyPort, and http.proxyScheme detected. Using http proxy host: {} port: {} scheme: {}", new Object[]{host, port, scheme}); HttpHost proxy = new HttpHost(host, port, scheme); diff --git a/components/camel-http4/src/main/java/org/apache/camel/component/http4/helper/HttpHelper.java b/components/camel-http4/src/main/java/org/apache/camel/component/http4/helper/HttpHelper.java index 0da9eca33d46b..775d25a36b9da 100644 --- a/components/camel-http4/src/main/java/org/apache/camel/component/http4/helper/HttpHelper.java +++ b/components/camel-http4/src/main/java/org/apache/camel/component/http4/helper/HttpHelper.java @@ -265,6 +265,10 @@ public static HttpVersion parserHttpVersion(String s) throws ProtocolException { throw new ProtocolException("Invalid HTTP minor version number: " + s); } return new HttpVersion(major, minor); + } + public static boolean isSecureConnection(String uri) { + return uri.startsWith("https"); } + }
8de9caa985fa3e79348c1c88b9313a4bce4d92e6
Valadoc
libvaladoc: Add support for SourceCode attributes
a
https://github.com/GNOME/vala/
diff --git a/src/libvaladoc/content/sourcecode.vala b/src/libvaladoc/content/sourcecode.vala index 338d23b24f..e7cfe7b3fa 100755 --- a/src/libvaladoc/content/sourcecode.vala +++ b/src/libvaladoc/content/sourcecode.vala @@ -23,19 +23,38 @@ using Gee; -public class Valadoc.Content.SourceCode : ContentElement, Inline{ +public class Valadoc.Content.SourceCode : ContentElement, Inline { public enum Language { GENIE, VALA, C; - public static Language? from_string (string str) { + public static Language? from_path (string path) { + int pos = path.last_index_of ("."); + if (pos < 0) { + return null; + } + + string ext = path.substring (pos + 1); + return from_string (ext, true); + } + + public static Language? from_string (string str, bool is_extension = false) { switch (str) { - case "Genie": + case "genie": + if (is_extension) { + return null; + } return Language.GENIE; - case "Vala": + + case "gs": + return Language.GENIE; + + case "vala": return Language.VALA; - case "C": + + case "c": + case "h": return Language.C; } @@ -45,11 +64,13 @@ public class Valadoc.Content.SourceCode : ContentElement, Inline{ public unowned string to_string () { switch (this) { case Language.GENIE: - return "Genie"; + return "genie"; + case Language.VALA: - return "Vala"; + return "vala"; + case Language.C: - return "C"; + return "c"; } assert (true); @@ -58,14 +79,68 @@ public class Valadoc.Content.SourceCode : ContentElement, Inline{ } public string code { get; set; } - public Language language { get; set; } + public Language? language { get; set; } internal SourceCode () { base (); _language = Language.VALA; } + private string? get_path (string path, string source_file_path, ErrorReporter reporter) { + // search relative to our file + if (!Path.is_absolute (path)) { + string relative_to_file = Path.build_path (Path.DIR_SEPARATOR_S, Path.get_dirname (source_file_path), path); + if (FileUtils.test (relative_to_file, FileTest.EXISTS | FileTest.IS_REGULAR)) { + return (owned) relative_to_file; + } + } + + // search relative to the current directory / absoulte path + if (!FileUtils.test (path, FileTest.EXISTS | FileTest.IS_REGULAR)) { + code = "File %s does not exist".printf (path); + reporter.simple_warning (code); + return null; + } + + return path; + } + + private void load_source_code (string _path, string source_file_path, ErrorReporter reporter) { + string? path = get_path (_path, source_file_path, reporter); + if (path == null) { + return ; + } + + try { + string content = null; + FileUtils.get_contents (path, out content); + _language = Language.from_path (path); + code = (owned) content; + } catch (FileError err) { + reporter.simple_error ("Can't read file: '%s': ", path, err.message); + } + } + public override void check (Api.Tree api_root, Api.Node container, string file_path, ErrorReporter reporter, Settings settings) { + string[] splitted = code.split ("\n", 2); + if (splitted[0].strip () == "") { + code = splitted[1] ?? ""; + } else if (splitted[0].has_prefix ("#!")) { + unowned string start = (string) (((char*) splitted[0]) + 2); + if (start.has_prefix ("include:")) { + start = (string) (((char*) start) + 8); + string path = start.strip (); + load_source_code (path, file_path, reporter); + } else { + string name = start._strip ().down (); + _language = Language.from_string (name); + code = splitted[1] ?? ""; + if (_language == null && name != "none") { + reporter.simple_warning ("Unsupported programming language '%s'", name); + return ; + } + } + } } public override void accept (ContentVisitor visitor) {
67e2a30687c80776e00b36c94b79589be95a6d06
drools
[DROOLS-601] fix queries when used in combination- with agenda-groups--
c
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/main/java/org/drools/compiler/rule/builder/PatternBuilder.java b/drools-compiler/src/main/java/org/drools/compiler/rule/builder/PatternBuilder.java index 353bf79b9ea..25d2763e52d 100644 --- a/drools-compiler/src/main/java/org/drools/compiler/rule/builder/PatternBuilder.java +++ b/drools-compiler/src/main/java/org/drools/compiler/rule/builder/PatternBuilder.java @@ -198,11 +198,7 @@ public RuleConditionElement build( RuleBuildContext context, // it might be a recursive query, so check for same names if ( context.getRule().getName().equals( patternDescr.getObjectType() ) ) { // it's a query so delegate to the QueryElementBuilder - QueryElementBuilder qeBuilder = QueryElementBuilder.getInstance(); - rce = qeBuilder.build( context, - descr, - prefixPattern, - (QueryImpl) context.getRule() ); + rce = buildQueryElement(context, descr, prefixPattern, (QueryImpl) context.getRule()); } if ( rce == null ) { @@ -210,11 +206,7 @@ public RuleConditionElement build( RuleBuildContext context, RuleImpl rule = context.getPkg().getRule( patternDescr.getObjectType() ); if ( rule instanceof QueryImpl ) { // it's a query so delegate to the QueryElementBuilder - QueryElementBuilder qeBuilder = QueryElementBuilder.getInstance(); - rce = qeBuilder.build( context, - descr, - prefixPattern, - (QueryImpl) rule ); + rce = buildQueryElement(context, descr, prefixPattern, (QueryImpl) rule); } } @@ -231,11 +223,7 @@ public RuleConditionElement build( RuleBuildContext context, RuleImpl rule = pkgReg.getPackage().getRule( patternDescr.getObjectType() ); if ( rule instanceof QueryImpl) { // it's a query so delegate to the QueryElementBuilder - QueryElementBuilder qeBuilder = QueryElementBuilder.getInstance(); - rce = qeBuilder.build( context, - descr, - prefixPattern, - (QueryImpl) rule ); + rce = buildQueryElement(context, descr, prefixPattern, (QueryImpl) rule); break; } } @@ -354,6 +342,13 @@ public RuleConditionElement build( RuleBuildContext context, return pattern; } + private RuleConditionElement buildQueryElement(RuleBuildContext context, BaseDescr descr, Pattern prefixPattern, QueryImpl rule) { + if (context.getRule() != rule) { + context.getRule().addUsedQuery(rule); + } + return QueryElementBuilder.getInstance().build( context, descr, prefixPattern, rule ); + } + protected void processDuplicateBindings( boolean isUnification, PatternDescr patternDescr, Pattern pattern, diff --git a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/Misc2Test.java b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/Misc2Test.java index 0857a2778ec..d0ca3a515b9 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/integrationtests/Misc2Test.java +++ b/drools-compiler/src/test/java/org/drools/compiler/integrationtests/Misc2Test.java @@ -82,6 +82,7 @@ import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.StatelessKieSession; +import org.kie.api.runtime.rule.Agenda; import org.kie.api.runtime.rule.FactHandle; import org.kie.internal.KnowledgeBase; import org.kie.internal.KnowledgeBaseFactory; @@ -6652,4 +6653,134 @@ public void testGenericsInRHSWithModify() { ksession.insert("1"); ksession.fireAllRules(); } + + @Test + public void testQueryWithAgendaGroup() { + // DROOLS-601 + String drl = + "package org.drools.test; " + + "global java.util.List list; " + + + "query foo( Integer $i ) " + + " $i := Integer() " + + "end " + + + "rule Detect " + + "agenda-group 'one' " + + "when " + + " foo( $i ; ) " + + "then " + + " list.add( $i ); " + + "end " + + + "rule OnceMore " + + "agenda-group 'two' " + + "no-loop " + + "when " + + " $i : Integer() " + + "then " + + " update( $i );" + + "end " + + ""; + + KieHelper helper = new KieHelper(); + helper.addContent( drl, ResourceType.DRL ); + KieSession kieSession = helper.build().newKieSession(); + + List<Integer> list = new ArrayList<Integer>(); + kieSession.setGlobal( "list", list ); + + FactHandle handle = kieSession.insert( 42 ); + + Agenda agenda = kieSession.getAgenda(); + agenda.getAgendaGroup("two").setFocus(); + agenda.getAgendaGroup("one").setFocus(); + + kieSession.fireAllRules(); + assertEquals( Arrays.asList( 42 ), list ); + + kieSession.delete( handle ); + + kieSession.insert( 99 ); + + agenda.getAgendaGroup("two").setFocus(); + agenda.getAgendaGroup("one").setFocus(); + + kieSession.fireAllRules(); + assertEquals( Arrays.asList( 42, 99 ), list ); + } + + @Test + public void testQueryUsingQueryWithAgendaGroup() { + // DROOLS-601 + String drl = + "package org.drools.test; " + + "global java.util.List list; " + + + "query bar( String $s ) " + + " $s := String() " + + "end " + + "query foo( Integer $i, String $s ) " + + " bar( $s ; ) " + + " $i := Integer( toString() == $s ) " + + "end " + + + "rule Detect " + + "agenda-group 'one' " + + "when " + + " foo( $i, $s ; ) " + + "then " + + " list.add( $i ); " + + "end " + + + "rule UpdateInt " + + "agenda-group 'two' " + + "no-loop " + + "when " + + " $i : Integer() " + + "then " + + " update( $i );" + + "end " + + + "rule UpdateString " + + "agenda-group 'three' " + + "no-loop " + + "when " + + " $s : String() " + + "then " + + " update( $s );" + + "end " + + ""; + + KieHelper helper = new KieHelper(); + helper.addContent( drl, ResourceType.DRL ); + KieSession kieSession = helper.build().newKieSession(); + + List<Integer> list = new ArrayList<Integer>(); + kieSession.setGlobal( "list", list ); + + FactHandle iFH = kieSession.insert( 42 ); + FactHandle sFH = kieSession.insert( "42" ); + + Agenda agenda = kieSession.getAgenda(); + agenda.getAgendaGroup("three").setFocus(); + agenda.getAgendaGroup("two").setFocus(); + agenda.getAgendaGroup("one").setFocus(); + + kieSession.fireAllRules(); + assertEquals( Arrays.asList( 42 ), list ); + + //kieSession.delete( iFH ); + kieSession.delete( sFH ); + + kieSession.insert( 99 ); + kieSession.insert( "99" ); + + agenda.getAgendaGroup("three").setFocus(); + agenda.getAgendaGroup("two").setFocus(); + agenda.getAgendaGroup("one").setFocus(); + + kieSession.fireAllRules(); + assertEquals( Arrays.asList( 42, 99 ), list ); + } } \ No newline at end of file diff --git a/drools-compiler/src/test/java/org/drools/compiler/rule/builder/dialect/mvel/MVELConsequenceBuilderTest.java b/drools-compiler/src/test/java/org/drools/compiler/rule/builder/dialect/mvel/MVELConsequenceBuilderTest.java index e05a6002688..da2117408ad 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/rule/builder/dialect/mvel/MVELConsequenceBuilderTest.java +++ b/drools-compiler/src/test/java/org/drools/compiler/rule/builder/dialect/mvel/MVELConsequenceBuilderTest.java @@ -109,7 +109,7 @@ public void testSimpleExpression() throws Exception { final AgendaItem item = new AgendaItemImpl( 0, tuple, 10, pctxFactory.createPropagationContext(1, 1, null, tuple, null), - new RuleTerminalNode(0, new CompositeObjectSinkAdapterTest.MockBetaNode(), context.getRule(), subrule, 0, new BuildContext( kBase, null )), null, null); + new RuleTerminalNode(0, new CompositeObjectSinkAdapterTest.MockBetaNode(), context.getRule(), subrule, 0, new BuildContext( kBase, null )), null); final DefaultKnowledgeHelper kbHelper = new DefaultKnowledgeHelper( ksession ); kbHelper.setActivation( item ); ((MVELConsequence) context.getRule().getConsequence()).compile( (MVELDialectRuntimeData) pkgBuilder.getPackageRegistry( pkg.getName() ).getDialectRuntimeRegistry().getDialectData( "mvel" )); @@ -177,7 +177,6 @@ public void testImperativeCodeError() throws Exception { final AgendaItem item = new AgendaItemImpl( 0, tuple, 10, - null, null, null, null); final DefaultKnowledgeHelper kbHelper = new DefaultKnowledgeHelper( ksession ); kbHelper.setActivation( item ); diff --git a/drools-compiler/src/test/java/org/drools/compiler/rule/builder/dialect/mvel/MVELSalienceBuilderTest.java b/drools-compiler/src/test/java/org/drools/compiler/rule/builder/dialect/mvel/MVELSalienceBuilderTest.java index 886eefa3317..b06765483f6 100644 --- a/drools-compiler/src/test/java/org/drools/compiler/rule/builder/dialect/mvel/MVELSalienceBuilderTest.java +++ b/drools-compiler/src/test/java/org/drools/compiler/rule/builder/dialect/mvel/MVELSalienceBuilderTest.java @@ -1,42 +1,40 @@ package org.drools.compiler.rule.builder.dialect.mvel; -import java.util.HashMap; -import java.util.Map; - +import org.drools.compiler.Person; import org.drools.compiler.builder.impl.KnowledgeBuilderImpl; import org.drools.compiler.compiler.DialectCompiletimeRegistry; +import org.drools.compiler.lang.descr.AttributeDescr; +import org.drools.compiler.lang.descr.RuleDescr; +import org.drools.compiler.rule.builder.SalienceBuilder; import org.drools.core.WorkingMemory; -import org.drools.core.common.AgendaItemImpl; -import org.drools.core.common.InternalWorkingMemory; -import org.drools.core.definitions.InternalKnowledgePackage; -import org.drools.core.definitions.impl.KnowledgePackageImpl; -import org.drools.core.impl.InternalKnowledgeBase; -import org.drools.core.impl.StatefulKnowledgeSessionImpl; -import org.junit.Before; -import org.junit.Test; -import org.kie.api.definition.rule.Rule; - -import static org.junit.Assert.*; - -import org.drools.compiler.Person; import org.drools.core.base.ClassObjectType; import org.drools.core.base.DefaultKnowledgeHelper; import org.drools.core.base.mvel.MVELSalienceExpression; import org.drools.core.common.AgendaItem; +import org.drools.core.common.AgendaItemImpl; import org.drools.core.common.InternalFactHandle; -import org.drools.compiler.lang.descr.AttributeDescr; -import org.drools.compiler.lang.descr.RuleDescr; +import org.drools.core.definitions.InternalKnowledgePackage; +import org.drools.core.definitions.impl.KnowledgePackageImpl; +import org.drools.core.impl.InternalKnowledgeBase; +import org.drools.core.impl.StatefulKnowledgeSessionImpl; import org.drools.core.reteoo.LeftTupleImpl; import org.drools.core.reteoo.RuleTerminalNode; import org.drools.core.rule.Declaration; import org.drools.core.rule.MVELDialectRuntimeData; import org.drools.core.rule.Pattern; -import org.drools.compiler.rule.builder.SalienceBuilder; import org.drools.core.spi.ObjectType; import org.drools.core.spi.PatternExtractor; import org.drools.core.spi.Salience; +import org.junit.Before; +import org.junit.Test; +import org.kie.api.definition.rule.Rule; import org.kie.internal.KnowledgeBaseFactory; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + public class MVELSalienceBuilderTest { private InstrumentedBuildContent context; private InternalKnowledgeBase kBase ; @@ -100,7 +98,7 @@ public void testSimpleExpression() { RuleTerminalNode rtn = new RuleTerminalNode(); rtn.setSalienceDeclarations( context.getDeclarationResolver().getDeclarations( context.getRule() ).values().toArray( new Declaration[1] ) ); - AgendaItem item = new AgendaItemImpl(0, tuple, 0, null, rtn, null, null); + AgendaItem item = new AgendaItemImpl(0, tuple, 0, null, rtn, null); assertEquals( 25, @@ -182,7 +180,7 @@ public SalienceEvaluator(InternalKnowledgeBase kBase, RuleTerminalNode rtn = new RuleTerminalNode(); rtn.setSalienceDeclarations( context.getDeclarationResolver().getDeclarations( context.getRule() ).values().toArray( new Declaration[1] ) ); - item = new AgendaItemImpl(0, tuple, 0, null, rtn, null, null); + item = new AgendaItemImpl(0, tuple, 0, null, rtn, null); } public void run() { diff --git a/drools-core/src/main/java/org/drools/core/common/AgendaItemImpl.java b/drools-core/src/main/java/org/drools/core/common/AgendaItemImpl.java index f23164d134b..5f3d6bbbcdf 100644 --- a/drools-core/src/main/java/org/drools/core/common/AgendaItemImpl.java +++ b/drools-core/src/main/java/org/drools/core/common/AgendaItemImpl.java @@ -16,11 +16,6 @@ package org.drools.core.common; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.kie.api.runtime.rule.FactHandle; import org.drools.core.definitions.rule.impl.RuleImpl; import org.drools.core.phreak.RuleAgendaItem; import org.drools.core.reteoo.LeftTuple; @@ -32,8 +27,13 @@ import org.drools.core.spi.PropagationContext; import org.drools.core.util.LinkedList; import org.drools.core.util.LinkedListEntry; +import org.kie.api.runtime.rule.FactHandle; import org.kie.internal.event.rule.ActivationUnMatchListener; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + /** * Item entry in the <code>Agenda</code>. */ @@ -78,7 +78,6 @@ public class AgendaItemImpl private boolean matched; private boolean active; private ActivationUnMatchListener activationUnMatchListener; - private RuleAgendaItem ruleAgendaItem; // ------------------------------------------------------------ // Constructors @@ -92,7 +91,6 @@ public AgendaItemImpl() { * Construct. * * @param tuple The tuple. - * @param ruleAgendaItem * @param agendaGroup */ public AgendaItemImpl(final long activationNumber, @@ -100,7 +98,6 @@ public AgendaItemImpl(final long activationNumber, final int salience, final PropagationContext context, final TerminalNode rtn, - final RuleAgendaItem ruleAgendaItem, final InternalAgendaGroup agendaGroup) { this.tuple = tuple; this.context = context; @@ -109,7 +106,6 @@ public AgendaItemImpl(final long activationNumber, this.activationNumber = activationNumber; this.index = -1; this.matched = true; - this.ruleAgendaItem = ruleAgendaItem; this.agendaGroup = agendaGroup; } @@ -171,7 +167,7 @@ public void setFactHandle(InternalFactHandle factHandle) { @Override public RuleAgendaItem getRuleAgendaItem() { - return ruleAgendaItem; + return null; } /* @@ -221,7 +217,7 @@ public void removeAllBlockersAndBlocked(InternalAgenda agenda) { removeBlocked(dep); AgendaItem justified = (AgendaItem) dep.getJustified(); if (justified.getBlockers().isEmpty()) { - agenda.stageLeftTuple(ruleAgendaItem,justified); + agenda.stageLeftTuple(null,justified); } dep = tmp; } diff --git a/drools-core/src/main/java/org/drools/core/common/DefaultAgenda.java b/drools-core/src/main/java/org/drools/core/common/DefaultAgenda.java index 73695080370..5fee77d0794 100644 --- a/drools-core/src/main/java/org/drools/core/common/DefaultAgenda.java +++ b/drools-core/src/main/java/org/drools/core/common/DefaultAgenda.java @@ -18,6 +18,7 @@ import org.drools.core.RuleBaseConfiguration; import org.drools.core.WorkingMemory; +import org.drools.core.definitions.rule.impl.RuleImpl; import org.drools.core.impl.InternalKnowledgeBase; import org.drools.core.impl.StatefulKnowledgeSessionImpl; import org.drools.core.phreak.RuleAgendaItem; @@ -30,6 +31,7 @@ import org.drools.core.reteoo.TerminalNode; import org.drools.core.rule.Declaration; import org.drools.core.rule.EntryPointId; +import org.drools.core.rule.QueryImpl; import org.drools.core.spi.Activation; import org.drools.core.spi.AgendaGroup; import org.drools.core.spi.ConsequenceException; @@ -61,7 +63,8 @@ import java.util.List; import java.util.Map; import java.util.Set; - +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; /** @@ -102,7 +105,9 @@ public class DefaultAgenda private InternalAgendaGroup main; - private final LinkedList<RuleAgendaItem> eager = new LinkedList<RuleAgendaItem>(); + private final org.drools.core.util.LinkedList<RuleAgendaItem> eager = new org.drools.core.util.LinkedList<RuleAgendaItem>(); + + private final ConcurrentMap<QueryImpl, RuleAgendaItem> queries = new ConcurrentHashMap<QueryImpl, RuleAgendaItem>(); private AgendaGroupFactory agendaGroupFactory; @@ -265,7 +270,7 @@ public WorkingMemory getWorkingMemory() { } @Override - public void addEagerRuleAgendaItem(final RuleAgendaItem item) { + public void addEagerRuleAgendaItem(RuleAgendaItem item) { if ( workingMemory.getSessionConfiguration().getForceEagerActivationFilter().accept(item.getRule()) ) { item.getRuleExecutor().evaluateNetwork(workingMemory); return; @@ -298,6 +303,22 @@ public void removeEagerRuleAgendaItem(RuleAgendaItem item) { } } + @Override + public void addQueryAgendaItem(RuleAgendaItem item) { + queries.putIfAbsent( (QueryImpl) item.getRule(), item ); + if ( log.isTraceEnabled() ) { + log.trace("Added {} to query evaluation list.", item.getRule().getName() ); + } + } + + @Override + public void removeQueryAgendaItem(RuleAgendaItem item) { + queries.remove( (QueryImpl) item.getRule() ); + if ( log.isTraceEnabled() ) { + log.trace("Removed {} from query evaluation list.", item.getRule().getName() ); + } + } + public void scheduleItem(final ScheduledAgendaItem item, final InternalWorkingMemory wm) { throw new UnsupportedOperationException("rete only"); @@ -961,6 +982,7 @@ public int fireNextItem(final AgendaFilter filter, garbageCollector.remove(item); } + evaluateQueriesForRule(item); localFireCount = item.getRuleExecutor().evaluateNetworkAndFire(this.workingMemory, filter, fireCount, fireLimit); if ( localFireCount == 0 ) { @@ -985,13 +1007,29 @@ public int fireNextItem(final AgendaFilter filter, public void evaluateEagerList() { synchronized (eager) { while ( !eager.isEmpty() ) { - RuleExecutor ruleExecutor = eager.removeFirst().getRuleExecutor(); + RuleAgendaItem item = eager.removeFirst(); + evaluateQueriesForRule(item); + RuleExecutor ruleExecutor = item.getRuleExecutor(); ruleExecutor.flushTupleQueue(ruleExecutor.getPathMemory().getStreamQueue()); ruleExecutor.evaluateNetwork(this.workingMemory); } } } + private void evaluateQueriesForRule(RuleAgendaItem item) { + RuleImpl rule = item.getRule(); + if (!rule.isQuery()) { + for (QueryImpl query : rule.getDependingQueries()) { + RuleAgendaItem queryAgendaItem = queries.remove(query); + if (queryAgendaItem != null) { + RuleExecutor ruleExecutor = queryAgendaItem.getRuleExecutor(); + ruleExecutor.flushTupleQueue(ruleExecutor.getPathMemory().getStreamQueue()); + ruleExecutor.evaluateNetwork(this.workingMemory); + } + } + } + } + public int sizeOfRuleFlowGroup(String name) { InternalAgendaGroup group = agendaGroups.get(name); if (group == null) { @@ -1145,7 +1183,7 @@ private boolean checkProcessInstance(Activation activation, long processInstanceId) { final Map<String, Declaration> declarations = activation.getSubRule().getOuterDeclarations(); for ( Declaration declaration : declarations.values() ) { - if ( "processInstance".equals( declaration.getIdentifier() ) ) { + if ( "processInstance".equals(declaration.getIdentifier()) ) { Object value = declaration.getValue( workingMemory, activation.getTuple().get( declaration ).getObject() ); if ( value instanceof ProcessInstance ) { @@ -1176,7 +1214,7 @@ public void stageLeftTuple(RuleAgendaItem ruleAgendaItem, AgendaItem justified) } public void fireUntilHalt() { - fireUntilHalt( null ); + fireUntilHalt(null); } public void fireUntilHalt(final AgendaFilter agendaFilter) { diff --git a/drools-core/src/main/java/org/drools/core/common/InternalAgenda.java b/drools-core/src/main/java/org/drools/core/common/InternalAgenda.java index 50e33e85cf1..5bbc459b16b 100644 --- a/drools-core/src/main/java/org/drools/core/common/InternalAgenda.java +++ b/drools-core/src/main/java/org/drools/core/common/InternalAgenda.java @@ -289,9 +289,11 @@ RuleAgendaItem createRuleAgendaItem(final int salience, void addAgendaItemToGroup(AgendaItem item); void addEagerRuleAgendaItem(RuleAgendaItem item); - void removeEagerRuleAgendaItem(RuleAgendaItem item); + void addQueryAgendaItem(final RuleAgendaItem item); + void removeQueryAgendaItem(final RuleAgendaItem item); + long getNextActivationCounter(); /* diff --git a/drools-core/src/main/java/org/drools/core/definitions/rule/impl/RuleImpl.java b/drools-core/src/main/java/org/drools/core/definitions/rule/impl/RuleImpl.java index bb0240e0c97..f157250f6ec 100644 --- a/drools-core/src/main/java/org/drools/core/definitions/rule/impl/RuleImpl.java +++ b/drools-core/src/main/java/org/drools/core/definitions/rule/impl/RuleImpl.java @@ -28,6 +28,7 @@ import org.drools.core.rule.InvalidPatternException; import org.drools.core.rule.LogicTransformer; import org.drools.core.rule.Pattern; +import org.drools.core.rule.QueryImpl; import org.drools.core.rule.RuleConditionElement; import org.drools.core.spi.AgendaGroup; import org.drools.core.spi.CompiledInvoker; @@ -53,10 +54,13 @@ import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; +import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; import java.util.Map; public class RuleImpl implements Externalizable, @@ -136,6 +140,10 @@ public class RuleImpl implements Externalizable, private ConsequenceMetaData consequenceMetaData = new ConsequenceMetaData(); + private List<QueryImpl> usedQueries; + + private List<QueryImpl> dependingQueries; + public RuleImpl() { } @@ -159,7 +167,6 @@ public RuleImpl(final String name, this.salience = SalienceInteger.DEFAULT_SALIENCE; this.metaAttributes = new HashMap<String, Object>(); setActivationListener( "agenda" ); - } /** @@ -219,6 +226,7 @@ public void writeExternal(ObjectOutput out) throws IOException { out.writeObject( activationListener ); out.writeObject( consequenceMetaData ); out.writeBoolean( eager ); + out.writeObject( usedQueries ); } @SuppressWarnings("unchecked") @@ -256,6 +264,39 @@ public void readExternal(ObjectInput in) throws IOException, activationListener = ( String ) in.readObject(); consequenceMetaData = ( ConsequenceMetaData ) in.readObject(); eager = in.readBoolean(); + usedQueries = (List<QueryImpl>) in.readObject(); + } + + public void addUsedQuery(QueryImpl query) { + if (usedQueries == null) { + usedQueries = new ArrayList<QueryImpl>(); + } + usedQueries.add(query); + } + + /** + * Returns the lists of queries from which this rule (or query) depends on ordered + * by their relative dependencies, e.g. if R1 -> A -> B -> C (where the letter are queries) + * it will return [C, B, A] + */ + public List<QueryImpl> getDependingQueries() { + if (dependingQueries == null) { + dependingQueries = usedQueries == null ? Collections.<QueryImpl>emptyList() : collectDependingQueries(new LinkedList<QueryImpl>()); + } + return dependingQueries; + } + + protected List<QueryImpl> collectDependingQueries(LinkedList<QueryImpl> accumulator) { + if (usedQueries == null) { + return accumulator; + } + for (QueryImpl query : usedQueries) { + if (!accumulator.contains(query)) { + accumulator.offerFirst(query); + query.collectDependingQueries(accumulator); + } + } + return accumulator; } public Resource getResource() { diff --git a/drools-core/src/main/java/org/drools/core/phreak/RuleAgendaItem.java b/drools-core/src/main/java/org/drools/core/phreak/RuleAgendaItem.java index 581cde7042c..73181307928 100644 --- a/drools-core/src/main/java/org/drools/core/phreak/RuleAgendaItem.java +++ b/drools-core/src/main/java/org/drools/core/phreak/RuleAgendaItem.java @@ -30,7 +30,7 @@ public RuleAgendaItem(final long activationNumber, final TerminalNode rtn, boolean declarativeAgendaEnabled, InternalAgendaGroup agendaGroup) { - super(activationNumber, tuple, salience, context, rtn, null, agendaGroup); + super(activationNumber, tuple, salience, context, rtn, agendaGroup); executor = new RuleExecutor(pmem, this, declarativeAgendaEnabled); } diff --git a/drools-core/src/main/java/org/drools/core/phreak/RuleExecutor.java b/drools-core/src/main/java/org/drools/core/phreak/RuleExecutor.java index 6f8143b94ce..7e5f266e6cb 100644 --- a/drools-core/src/main/java/org/drools/core/phreak/RuleExecutor.java +++ b/drools-core/src/main/java/org/drools/core/phreak/RuleExecutor.java @@ -206,7 +206,9 @@ public void removeRuleAgendaItemWhenEmpty(InternalWorkingMemory wm) { log.trace("Removing RuleAgendaItem " + ruleAgendaItem); } ruleAgendaItem.remove(); - if (ruleAgendaItem.getRule().isEager()) { + if ( ruleAgendaItem.getRule().isQuery() ) { + ((InternalAgenda)wm.getAgenda()).removeQueryAgendaItem( ruleAgendaItem ); + } else if ( ruleAgendaItem.getRule().isEager() ) { ((InternalAgenda) wm.getAgenda()).removeEagerRuleAgendaItem(ruleAgendaItem); } } diff --git a/drools-core/src/main/java/org/drools/core/reteoo/PathMemory.java b/drools-core/src/main/java/org/drools/core/reteoo/PathMemory.java index 698696e3e6f..524defd1d85 100644 --- a/drools-core/src/main/java/org/drools/core/reteoo/PathMemory.java +++ b/drools-core/src/main/java/org/drools/core/reteoo/PathMemory.java @@ -140,7 +140,7 @@ public void queueRuleAgendaItem(InternalWorkingMemory wm) { return; } - if (!agendaItem.isQueued() && !agendaItem.isBlocked()) { + if ( !agendaItem.isQueued() && !agendaItem.isBlocked() ) { if ( isLogTraceEnabled ) { log.trace("Queue RuleAgendaItem {}", agendaItem); } @@ -148,10 +148,13 @@ public void queueRuleAgendaItem(InternalWorkingMemory wm) { ag.add( agendaItem ); } } - if ( agendaItem.getRule().isEager() ) { - // will return if already added + + if ( agendaItem.getRule().isQuery() ) { + ((InternalAgenda)wm.getAgenda()).addQueryAgendaItem( agendaItem ); + } else if ( agendaItem.getRule().isEager() ) { ((InternalAgenda)wm.getAgenda()).addEagerRuleAgendaItem( agendaItem ); } + agenda.notifyHalt(); } diff --git a/drools-reteoo/src/main/java/org/drools/reteoo/common/ReteAgenda.java b/drools-reteoo/src/main/java/org/drools/reteoo/common/ReteAgenda.java index 23e9b288661..433f7a6f754 100644 --- a/drools-reteoo/src/main/java/org/drools/reteoo/common/ReteAgenda.java +++ b/drools-reteoo/src/main/java/org/drools/reteoo/common/ReteAgenda.java @@ -324,6 +324,16 @@ public void removeEagerRuleAgendaItem(RuleAgendaItem item) { eager.remove(item); } + @Override + public void addQueryAgendaItem(final RuleAgendaItem item) { + throw new UnsupportedOperationException(); + } + + @Override + public void removeQueryAgendaItem(RuleAgendaItem item) { + throw new UnsupportedOperationException(); + } + /** * Schedule an agenda item for delayed firing. *
7384d25cb3975a7fdc522ff8f84ab3dadcaba03a
kotlin
Prohibit Array<Nothing>--
c
https://github.com/JetBrains/kotlin
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/TargetPlatform.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/TargetPlatform.kt index 57fb5757a3c37..685c35a4d7cfe 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/TargetPlatform.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/TargetPlatform.kt @@ -25,7 +25,10 @@ import org.jetbrains.kotlin.descriptors.ModuleParameters import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.calls.checkers.* -import org.jetbrains.kotlin.resolve.validation.* +import org.jetbrains.kotlin.resolve.validation.DeprecatedSymbolValidator +import org.jetbrains.kotlin.resolve.validation.InfixValidator +import org.jetbrains.kotlin.resolve.validation.OperatorValidator +import org.jetbrains.kotlin.resolve.validation.SymbolUsageValidator import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.types.DynamicTypesSettings @@ -58,7 +61,7 @@ private val DEFAULT_DECLARATION_CHECKERS = listOf( InfixModifierChecker()) private val DEFAULT_CALL_CHECKERS = listOf(CapturingInClosureChecker(), InlineCheckerWrapper(), ReifiedTypeParameterSubstitutionChecker(), - SafeCallChecker(), InvokeConventionChecker()) + SafeCallChecker(), InvokeConventionChecker(), CallReturnsArrayOfNothingChecker()) private val DEFAULT_TYPE_CHECKERS = emptyList<AdditionalTypeChecker>() private val DEFAULT_VALIDATORS = listOf(DeprecatedSymbolValidator(), OperatorValidator(), InfixValidator()) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeResolver.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeResolver.kt index 47332c1695db4..2ac29920c942e 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeResolver.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/TypeResolver.kt @@ -33,14 +33,15 @@ import org.jetbrains.kotlin.resolve.bindingContextUtil.recordScope import org.jetbrains.kotlin.resolve.calls.tasks.DynamicCallableDescriptors import org.jetbrains.kotlin.resolve.lazy.ForceResolveUtil import org.jetbrains.kotlin.resolve.lazy.LazyEntity -import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.resolve.scopes.LazyScopeAdapter import org.jetbrains.kotlin.resolve.scopes.LexicalScope +import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier import org.jetbrains.kotlin.storage.LockBasedStorageManager import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.Variance.* +import org.jetbrains.kotlin.types.typeUtil.isArrayOfNothing public class TypeResolver( private val annotationResolver: AnnotationResolver, @@ -349,6 +350,10 @@ public class TypeResolver( } } + if (resultingType.isArrayOfNothing()) { + c.trace.report(UNSUPPORTED.on(type, "Array<Nothing> is illegal")) + } + return type(resultingType) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/CallReturnsArrayOfNothingChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/CallReturnsArrayOfNothingChecker.kt new file mode 100644 index 0000000000000..b49ddb37e26fe --- /dev/null +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/checkers/CallReturnsArrayOfNothingChecker.kt @@ -0,0 +1,48 @@ +/* + * Copyright 2010-2015 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.resolve.calls.checkers + +import org.jetbrains.kotlin.descriptors.CallableDescriptor +import org.jetbrains.kotlin.diagnostics.Errors +import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext +import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall +import org.jetbrains.kotlin.types.DeferredType +import org.jetbrains.kotlin.types.KotlinType +import org.jetbrains.kotlin.types.typeUtil.isArrayOfNothing + +class CallReturnsArrayOfNothingChecker : CallChecker { + override fun <F : CallableDescriptor> check(resolvedCall: ResolvedCall<F>, context: BasicCallResolutionContext) { + val returnType = resolvedCall.resultingDescriptor.returnType + + if (returnType.containsArrayOfNothing()) { + val callElement = resolvedCall.call.callElement + val diagnostic = Errors.UNSUPPORTED.on(callElement, "Array<Nothing> in return type is illegal") + context.trace.report(diagnostic) + } + } + + private fun KotlinType?.containsArrayOfNothing(): Boolean { + // if this.isComputing is true, it means that resolve + // has run into recursion, so checking for Array<Nothing> is meaningless anyway, + // and error about recursion will be reported later + if (this == null || this is DeferredType && this.isComputing) return false + + if (isArrayOfNothing()) return true + + return arguments.any { !it.isStarProjection && it.type.containsArrayOfNothing() } + } +} diff --git a/compiler/testData/diagnostics/testsWithStdLib/ArrayOfNothing.kt b/compiler/testData/diagnostics/testsWithStdLib/ArrayOfNothing.kt new file mode 100644 index 0000000000000..7046e50f6db44 --- /dev/null +++ b/compiler/testData/diagnostics/testsWithStdLib/ArrayOfNothing.kt @@ -0,0 +1,54 @@ +// !DIAGNOSTICS: -UNUSED_PARAMETER -UNUSED_VARIABLE -UNCHECKED_CAST -USELESS_CAST +class A<T> + +fun test1( + a: <!UNSUPPORTED!>Array<Nothing><!>, + b: <!UNSUPPORTED!>Array<Nothing?><!>, + c: <!UNSUPPORTED!>Array<in Nothing><!>, + d: <!UNSUPPORTED!>Array<in Nothing?><!>, + e: <!UNSUPPORTED!>Array<out Nothing><!>, + f: <!UNSUPPORTED!>Array<out Nothing?><!> +) {} + +fun test2( + a: <!UNSUPPORTED!>Array<Nothing><!>?, + b: <!UNSUPPORTED!>Array<Nothing?><!>?, + c: <!UNSUPPORTED!>Array<in Nothing><!>?, + d: <!UNSUPPORTED!>Array<in Nothing?><!>?, + e: <!UNSUPPORTED!>Array<out Nothing><!>?, + f: <!UNSUPPORTED!>Array<out Nothing?><!>? +) {} + +fun test3( + a: A<<!UNSUPPORTED!>Array<Nothing><!>>, + b: A<<!UNSUPPORTED!>Array<Nothing?><!>>, + c: A<<!UNSUPPORTED!>Array<in Nothing><!>>, + d: A<<!UNSUPPORTED!>Array<in Nothing?><!>>, + e: A<<!UNSUPPORTED!>Array<out Nothing><!>>, + f: A<<!UNSUPPORTED!>Array<out Nothing?><!>> +) {} + +fun test4( + a: Array<A<Nothing>>, + b: Array<A<Nothing?>>, + c: Array<A<in Nothing>>, + d: Array<A<in Nothing?>>, + e: Array<A<out Nothing>>, + f: Array<A<out Nothing?>> +) {} + +fun test5() { + <!UNSUPPORTED!><!REIFIED_TYPE_FORBIDDEN_SUBSTITUTION!>arrayOf<!><Nothing>()<!> + <!UNSUPPORTED!><!REIFIED_TYPE_FORBIDDEN_SUBSTITUTION!>Array<!><Nothing>(10) { throw Exception() }<!> +} + +fun <T> foo(): Array<T> = (object {} as Any) as Array<T> + +fun test6() = <!UNSUPPORTED!>foo<Nothing>()<!> + + +class B<T>(val array: Array<T>) + +fun <T> bar() = B<Array<T>>(arrayOf()) + +fun test7() = <!UNSUPPORTED!>bar<Nothing>()<!> diff --git a/compiler/testData/diagnostics/testsWithStdLib/ArrayOfNothing.txt b/compiler/testData/diagnostics/testsWithStdLib/ArrayOfNothing.txt new file mode 100644 index 0000000000000..b905373803d71 --- /dev/null +++ b/compiler/testData/diagnostics/testsWithStdLib/ArrayOfNothing.txt @@ -0,0 +1,26 @@ +package + +public fun </*0*/ T> bar(): B<kotlin.Array<T>> +public fun </*0*/ T> foo(): kotlin.Array<T> +public fun test1(/*0*/ a: kotlin.Array<kotlin.Nothing>, /*1*/ b: kotlin.Array<kotlin.Nothing?>, /*2*/ c: kotlin.Array<in kotlin.Nothing>, /*3*/ d: kotlin.Array<in kotlin.Nothing?>, /*4*/ e: kotlin.Array<out kotlin.Nothing>, /*5*/ f: kotlin.Array<out kotlin.Nothing?>): kotlin.Unit +public fun test2(/*0*/ a: kotlin.Array<kotlin.Nothing>?, /*1*/ b: kotlin.Array<kotlin.Nothing?>?, /*2*/ c: kotlin.Array<in kotlin.Nothing>?, /*3*/ d: kotlin.Array<in kotlin.Nothing?>?, /*4*/ e: kotlin.Array<out kotlin.Nothing>?, /*5*/ f: kotlin.Array<out kotlin.Nothing?>?): kotlin.Unit +public fun test3(/*0*/ a: A<kotlin.Array<kotlin.Nothing>>, /*1*/ b: A<kotlin.Array<kotlin.Nothing?>>, /*2*/ c: A<kotlin.Array<in kotlin.Nothing>>, /*3*/ d: A<kotlin.Array<in kotlin.Nothing?>>, /*4*/ e: A<kotlin.Array<out kotlin.Nothing>>, /*5*/ f: A<kotlin.Array<out kotlin.Nothing?>>): kotlin.Unit +public fun test4(/*0*/ a: kotlin.Array<A<kotlin.Nothing>>, /*1*/ b: kotlin.Array<A<kotlin.Nothing?>>, /*2*/ c: kotlin.Array<A<in kotlin.Nothing>>, /*3*/ d: kotlin.Array<A<in kotlin.Nothing?>>, /*4*/ e: kotlin.Array<A<out kotlin.Nothing>>, /*5*/ f: kotlin.Array<A<out kotlin.Nothing?>>): kotlin.Unit +public fun test5(): kotlin.Unit +public fun test6(): kotlin.Array<kotlin.Nothing> +public fun test7(): B<kotlin.Array<kotlin.Nothing>> + +public final class A</*0*/ T> { + public constructor A</*0*/ T>() + public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean + public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int + public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String +} + +public final class B</*0*/ T> { + public constructor B</*0*/ T>(/*0*/ array: kotlin.Array<T>) + public final val array: kotlin.Array<T> + public open override /*1*/ /*fake_override*/ fun equals(/*0*/ other: kotlin.Any?): kotlin.Boolean + public open override /*1*/ /*fake_override*/ fun hashCode(): kotlin.Int + public open override /*1*/ /*fake_override*/ fun toString(): kotlin.String +} diff --git a/compiler/testData/diagnostics/testsWithStdLib/reified/reifiedNothingSubstitution.kt b/compiler/testData/diagnostics/testsWithStdLib/reified/reifiedNothingSubstitution.kt index f409857d53da4..70f3b60482b40 100644 --- a/compiler/testData/diagnostics/testsWithStdLib/reified/reifiedNothingSubstitution.kt +++ b/compiler/testData/diagnostics/testsWithStdLib/reified/reifiedNothingSubstitution.kt @@ -3,8 +3,8 @@ inline fun<reified T> foo(block: () -> T): String = block().toString() fun box() { - val a = <!REIFIED_TYPE_FORBIDDEN_SUBSTITUTION!>arrayOf<!>(null!!) - val b = <!REIFIED_TYPE_FORBIDDEN_SUBSTITUTION!>Array<!><Nothing?>(5) { null!! } + val a = <!UNSUPPORTED!><!REIFIED_TYPE_FORBIDDEN_SUBSTITUTION!>arrayOf<!>(null!!)<!> + val b = <!UNSUPPORTED!><!REIFIED_TYPE_FORBIDDEN_SUBSTITUTION!>Array<!><Nothing?>(5) { null!! }<!> val c = <!REIFIED_TYPE_FORBIDDEN_SUBSTITUTION!>foo<!>() { null!! } val d = foo<Any> { null!! } val e = <!REIFIED_TYPE_FORBIDDEN_SUBSTITUTION!>foo<!> { "1" as Nothing } diff --git a/compiler/tests/org/jetbrains/kotlin/checkers/DiagnosticsTestWithStdLibGenerated.java b/compiler/tests/org/jetbrains/kotlin/checkers/DiagnosticsTestWithStdLibGenerated.java index 6ca79d2990ae9..0e3176d846b3c 100644 --- a/compiler/tests/org/jetbrains/kotlin/checkers/DiagnosticsTestWithStdLibGenerated.java +++ b/compiler/tests/org/jetbrains/kotlin/checkers/DiagnosticsTestWithStdLibGenerated.java @@ -35,6 +35,12 @@ public void testAllFilesPresentInTestsWithStdLib() throws Exception { KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("compiler/testData/diagnostics/testsWithStdLib"), Pattern.compile("^(.+)\\.kt$"), true); } + @TestMetadata("ArrayOfNothing.kt") + public void testArrayOfNothing() throws Exception { + String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/diagnostics/testsWithStdLib/ArrayOfNothing.kt"); + doTest(fileName); + } + @TestMetadata("CallCompanionProtectedNonStatic.kt") public void testCallCompanionProtectedNonStatic() throws Exception { String fileName = KotlinTestUtils.navigationMetadata("compiler/testData/diagnostics/testsWithStdLib/CallCompanionProtectedNonStatic.kt"); diff --git a/core/descriptors/src/org/jetbrains/kotlin/types/TypeUtils.kt b/core/descriptors/src/org/jetbrains/kotlin/types/TypeUtils.kt index ba37ec5a1e73e..eaf153ad5d3e8 100644 --- a/core/descriptors/src/org/jetbrains/kotlin/types/TypeUtils.kt +++ b/core/descriptors/src/org/jetbrains/kotlin/types/TypeUtils.kt @@ -55,6 +55,13 @@ fun KotlinType.isAnyOrNullableAny(): Boolean = KotlinBuiltIns.isAnyOrNullableAny fun KotlinType.isBoolean(): Boolean = KotlinBuiltIns.isBoolean(this) fun KotlinType.isBooleanOrNullableBoolean(): Boolean = KotlinBuiltIns.isBooleanOrNullableBoolean(this) +fun KotlinType?.isArrayOfNothing(): Boolean { + if (this == null || !KotlinBuiltIns.isArray(this)) return false + + val typeArg = arguments.firstOrNull()?.type + return typeArg != null && KotlinBuiltIns.isNothingOrNullableNothing(typeArg) +} + private fun KotlinType.getContainedTypeParameters(): Collection<TypeParameterDescriptor> { val declarationDescriptor = getConstructor().getDeclarationDescriptor() if (declarationDescriptor is TypeParameterDescriptor) return listOf(declarationDescriptor)
52115e35af7a8361ae9e8b32499c24f9ba4174d0
intellij-community
support for forced compilation of a set of- files/modules--
a
https://github.com/JetBrains/intellij-community
diff --git a/java/compiler/impl/src/com/intellij/compiler/JpsServerManager.java b/java/compiler/impl/src/com/intellij/compiler/JpsServerManager.java index f48f3078eaab9..b87426dda4105 100644 --- a/java/compiler/impl/src/com/intellij/compiler/JpsServerManager.java +++ b/java/compiler/impl/src/com/intellij/compiler/JpsServerManager.java @@ -192,14 +192,16 @@ public void run() { } @Nullable - public RequestFuture submitCompilationTask(final String projectId, final List<String> modules, final boolean rebuild, final JpsServerResponseHandler handler) { + public RequestFuture submitCompilationTask(final String projectId, final boolean isRebuild, final boolean isMake, final Collection<String> modules, final Collection<String> paths, final JpsServerResponseHandler handler) { final Ref<RequestFuture> futureRef = new Ref<RequestFuture>(null); final RunnableFuture future = myTaskExecutor.submit(new Runnable() { public void run() { try { final Client client = ensureServerRunningAndClientConnected(true); if (client != null) { - final RequestFuture requestFuture = client.sendCompileRequest(projectId, modules, rebuild, handler); + final RequestFuture requestFuture = isRebuild ? + client.sendRebuildRequest(projectId, handler) : + client.sendCompileRequest(isMake, projectId, modules, paths, handler); futureRef.set(requestFuture); } else { @@ -412,7 +414,7 @@ private Process launchServer(int port) throws ExecutionException { // debugging cmdLine.addParameter("-XX:+HeapDumpOnOutOfMemoryError"); - //cmdLine.addParameter("-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5008"); + cmdLine.addParameter("-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5008"); // javac's VM should use the same default locale that IDEA uses in order for javac to print messages in 'correct' language final String lang = System.getProperty("user.language"); diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java index 7cf572d4131c8..e227f523ce023 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java @@ -417,9 +417,9 @@ private void attachAnnotationProcessorsOutputDirectories(CompileContextEx contex } @Nullable - private RequestFuture compileOnServer(final CompileContext compileContext, Collection<Module> modules, boolean isMake, @Nullable final CompileStatusNotification callback) + private RequestFuture compileOnServer(final CompileContext compileContext, Collection<Module> modules, final Collection<String> paths, @Nullable final CompileStatusNotification callback) throws Exception { - List<String> moduleNames = Collections.emptyList(); + Collection<String> moduleNames = Collections.emptyList(); if (modules != null && modules.size() > 0) { moduleNames = new ArrayList<String>(modules.size()); for (Module module : modules) { @@ -427,7 +427,7 @@ private RequestFuture compileOnServer(final CompileContext compileContext, Colle } } final JpsServerManager jpsServerManager = JpsServerManager.getInstance(); - return jpsServerManager.submitCompilationTask(myProject.getLocation(), moduleNames, !isMake, new JpsServerResponseHandlerAdapter() { + return jpsServerManager.submitCompilationTask(myProject.getLocation(), compileContext.isRebuild(), compileContext.isMake(), moduleNames, paths, new JpsServerResponseHandlerAdapter() { public void handleCompileMessage(JpsRemoteProto.Message.Response.CompileMessage compilerMessage) { final JpsRemoteProto.Message.Response.CompileMessage.Kind kind = compilerMessage.getKind(); @@ -560,7 +560,9 @@ public void run() { if (message != null) { compileContext.addMessage(message); } - final RequestFuture future = compileOnServer(compileContext, Arrays.asList(compileContext.getCompileScope().getAffectedModules()), compileContext.isMake(), callback); + final Collection<String> paths = fetchFiles(compileContext); + final List<Module> modules = paths.isEmpty()? Arrays.asList(compileContext.getCompileScope().getAffectedModules()) : Collections.<Module>emptyList(); + final RequestFuture future = compileOnServer(compileContext, modules, paths, callback); if (future != null) { // start cancel watcher ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { @@ -675,6 +677,32 @@ public void run() { }); } + private static List<String> fetchFiles(CompileContextImpl context) { + if (context.isRebuild()) { + return Collections.emptyList(); + } + final CompileScope scope = context.getCompileScope(); + if (shouldFetchFiles(scope)) { + final List<String> paths = new ArrayList<String>(); + for (VirtualFile file : scope.getFiles(null, true)) { + paths.add(file.getPath()); + } + return paths; + } + return Collections.emptyList(); + } + + private static boolean shouldFetchFiles(CompileScope scope) { + if (scope instanceof CompositeScope) { + for (CompileScope compileScope : ((CompositeScope)scope).getScopes()) { + if (shouldFetchFiles(compileScope)) { + return true; + } + } + } + return scope instanceof OneProjectItemCompileScope || scope instanceof FileSetCompileScope; + } + private void doCompile(final CompileContextImpl compileContext, final boolean isRebuild, final boolean forceCompile, diff --git a/jps/jps-builders/proto/jps_remote_proto.proto b/jps/jps-builders/proto/jps_remote_proto.proto index 566e4ef09c6eb..f0f9d21bb1d57 100644 --- a/jps/jps-builders/proto/jps_remote_proto.proto +++ b/jps/jps-builders/proto/jps_remote_proto.proto @@ -42,6 +42,7 @@ message Message { required Type command_type = 1; optional string project_id = 2; repeated string module_name = 3; + repeated string file_path = 4; } message ShutdownCommand { diff --git a/jps/jps-builders/src/org/jetbrains/jps/api/JpsRemoteProto.java b/jps/jps-builders/src/org/jetbrains/jps/api/JpsRemoteProto.java index 5d3dd9839192f..4279a42789930 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/api/JpsRemoteProto.java +++ b/jps/jps-builders/src/org/jetbrains/jps/api/JpsRemoteProto.java @@ -845,6 +845,18 @@ public java.lang.String getModuleName(int index) { return moduleName_.get(index); } + // repeated string file_path = 4; + public static final int FILE_PATH_FIELD_NUMBER = 4; + private java.util.List<java.lang.String> filePath_ = + java.util.Collections.emptyList(); + public java.util.List<java.lang.String> getFilePathList() { + return filePath_; + } + public int getFilePathCount() { return filePath_.size(); } + public java.lang.String getFilePath(int index) { + return filePath_.get(index); + } + private void initFields() { commandType_ = org.jetbrains.jps.api.JpsRemoteProto.Message.Request.CompilationRequest.Type.REBUILD; } @@ -865,6 +877,9 @@ public void writeTo(com.google.protobuf.CodedOutputStream output) for (java.lang.String element : getModuleNameList()) { output.writeString(3, element); } + for (java.lang.String element : getFilePathList()) { + output.writeString(4, element); + } } private int memoizedSerializedSize = -1; @@ -890,6 +905,15 @@ public int getSerializedSize() { size += dataSize; size += 1 * getModuleNameList().size(); } + { + int dataSize = 0; + for (java.lang.String element : getFilePathList()) { + dataSize += com.google.protobuf.CodedOutputStream + .computeStringSizeNoTag(element); + } + size += dataSize; + size += 1 * getFilePathList().size(); + } memoizedSerializedSize = size; return size; } @@ -1031,6 +1055,10 @@ public org.jetbrains.jps.api.JpsRemoteProto.Message.Request.CompilationRequest b result.moduleName_ = java.util.Collections.unmodifiableList(result.moduleName_); } + if (result.filePath_ != java.util.Collections.EMPTY_LIST) { + result.filePath_ = + java.util.Collections.unmodifiableList(result.filePath_); + } org.jetbrains.jps.api.JpsRemoteProto.Message.Request.CompilationRequest returnMe = result; result = null; return returnMe; @@ -1050,6 +1078,12 @@ public Builder mergeFrom(org.jetbrains.jps.api.JpsRemoteProto.Message.Request.Co } result.moduleName_.addAll(other.moduleName_); } + if (!other.filePath_.isEmpty()) { + if (result.filePath_.isEmpty()) { + result.filePath_ = new java.util.ArrayList<java.lang.String>(); + } + result.filePath_.addAll(other.filePath_); + } return this; } @@ -1084,6 +1118,10 @@ public Builder mergeFrom( addModuleName(input.readString()); break; } + case 34: { + addFilePath(input.readString()); + break; + } } } } @@ -1171,6 +1209,46 @@ public Builder clearModuleName() { return this; } + // repeated string file_path = 4; + public java.util.List<java.lang.String> getFilePathList() { + return java.util.Collections.unmodifiableList(result.filePath_); + } + public int getFilePathCount() { + return result.getFilePathCount(); + } + public java.lang.String getFilePath(int index) { + return result.getFilePath(index); + } + public Builder setFilePath(int index, java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + result.filePath_.set(index, value); + return this; + } + public Builder addFilePath(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + if (result.filePath_.isEmpty()) { + result.filePath_ = new java.util.ArrayList<java.lang.String>(); + } + result.filePath_.add(value); + return this; + } + public Builder addAllFilePath( + java.lang.Iterable<? extends java.lang.String> values) { + if (result.filePath_.isEmpty()) { + result.filePath_ = new java.util.ArrayList<java.lang.String>(); + } + super.addAll(values, result.filePath_); + return this; + } + public Builder clearFilePath() { + result.filePath_ = java.util.Collections.emptyList(); + return this; + } + // @@protoc_insertion_point(builder_scope:org.jetbrains.jpsservice.Message.Request.CompilationRequest) } diff --git a/jps/jps-builders/src/org/jetbrains/jps/api/ProtoUtil.java b/jps/jps-builders/src/org/jetbrains/jps/api/ProtoUtil.java index b41c448084f72..c9f48b3517675 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/api/ProtoUtil.java +++ b/jps/jps-builders/src/org/jetbrains/jps/api/ProtoUtil.java @@ -6,10 +6,7 @@ import java.io.ByteArrayOutputStream; import java.io.PrintStream; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.UUID; +import java.util.*; /** * @author Eugene Zhuravlev @@ -32,15 +29,19 @@ public static JpsRemoteProto.Message.Failure createFailure(final String descript } public static JpsRemoteProto.Message.Request createMakeRequest(String project, Collection<String> modules) { - return createCompileRequest(JpsRemoteProto.Message.Request.CompilationRequest.Type.MAKE, project, modules); + return createCompileRequest(JpsRemoteProto.Message.Request.CompilationRequest.Type.MAKE, project, modules, Collections.<String>emptyList()); } - public static JpsRemoteProto.Message.Request createRebuildRequest(String project, Collection<String> modules) { - return createCompileRequest(JpsRemoteProto.Message.Request.CompilationRequest.Type.REBUILD, project, modules); + public static JpsRemoteProto.Message.Request createForceCompileRequest(String project, Collection<String> modules, Collection<String> paths) { + return createCompileRequest(JpsRemoteProto.Message.Request.CompilationRequest.Type.FORCED_COMPILATION, project, modules, paths); + } + + public static JpsRemoteProto.Message.Request createRebuildRequest(String project) { + return createCompileRequest(JpsRemoteProto.Message.Request.CompilationRequest.Type.REBUILD, project, Collections.<String>emptyList(), Collections.<String>emptyList()); } public static JpsRemoteProto.Message.Request createCleanRequest(String project, Collection<String> modules) { - return createCompileRequest(JpsRemoteProto.Message.Request.CompilationRequest.Type.CLEAN, project, modules); + return createCompileRequest(JpsRemoteProto.Message.Request.CompilationRequest.Type.CLEAN, project, modules, Collections.<String>emptyList()); } public static JpsRemoteProto.Message.Request createCancelRequest(UUID compileSessionId) { @@ -49,13 +50,16 @@ public static JpsRemoteProto.Message.Request createCancelRequest(UUID compileSes return JpsRemoteProto.Message.Request.newBuilder().setRequestType(JpsRemoteProto.Message.Request.Type.CANCEL_BUILD_COMMAND).setCancelBuildCommand(builder.build()).build(); } - public static JpsRemoteProto.Message.Request createCompileRequest(final JpsRemoteProto.Message.Request.CompilationRequest.Type command, String project, Collection<String> modules) { + public static JpsRemoteProto.Message.Request createCompileRequest(final JpsRemoteProto.Message.Request.CompilationRequest.Type command, String project, Collection<String> modules, Collection<String> paths) { final JpsRemoteProto.Message.Request.CompilationRequest.Builder builder = JpsRemoteProto.Message.Request.CompilationRequest.newBuilder().setCommandType( command); builder.setProjectId(project); if (modules.size() > 0) { builder.addAllModuleName(modules); } + if (paths.size() > 0) { + builder.addAllFilePath(paths); + } return JpsRemoteProto.Message.Request.newBuilder().setRequestType(JpsRemoteProto.Message.Request.Type.COMPILE_REQUEST).setCompileRequest( builder.build()).build(); } diff --git a/jps/jps-builders/src/org/jetbrains/jps/client/Client.java b/jps/jps-builders/src/org/jetbrains/jps/client/Client.java index 563623c944bad..ff3927a00fc9b 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/client/Client.java +++ b/jps/jps-builders/src/org/jetbrains/jps/client/Client.java @@ -87,12 +87,18 @@ public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws } @NotNull - public RequestFuture sendCompileRequest(String projectId, List<String> modules, boolean rebuild, JpsServerResponseHandler handler) throws Exception{ + public RequestFuture sendCompileRequest(boolean isMake, String projectId, Collection<String> modules, Collection<String> paths, JpsServerResponseHandler handler) throws Exception{ checkConnected(); - return sendRequest( - rebuild? ProtoUtil.createRebuildRequest(projectId, modules) : ProtoUtil.createMakeRequest(projectId, modules), - handler - ); + final JpsRemoteProto.Message.Request request = isMake? + ProtoUtil.createMakeRequest(projectId, modules) : + ProtoUtil.createForceCompileRequest(projectId, modules, paths); + return sendRequest(request, handler); + } + + @NotNull + public RequestFuture sendRebuildRequest(String projectId, JpsServerResponseHandler handler) throws Exception{ + checkConnected(); + return sendRequest(ProtoUtil.createRebuildRequest(projectId), handler); } @NotNull diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/AllProjectScope.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/AllProjectScope.java new file mode 100644 index 0000000000000..43d7a6b42903d --- /dev/null +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/AllProjectScope.java @@ -0,0 +1,34 @@ +package org.jetbrains.jps.incremental; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jps.Module; +import org.jetbrains.jps.Project; + +import java.io.File; + +/** + * @author Eugene Zhuravlev + * Date: 9/17/11 + */ +public class AllProjectScope extends CompileScope { + + private final boolean myIsForcedCompilation; + + public AllProjectScope(Project project, boolean forcedCompilation) { + super(project); + myIsForcedCompilation = forcedCompilation; + } + + public boolean isRecompilationForced(@NotNull Module module) { + return myIsForcedCompilation; + } + + public boolean isAffected(@NotNull Module module) { + return true; + } + + public boolean isAffected(Module module, @NotNull File file) { + return true; + } + +} diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/Builder.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/Builder.java index d52217717e6a9..79ded2d232588 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/Builder.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/Builder.java @@ -82,7 +82,7 @@ public final boolean updateMappings(CompileContext context, final Mappings delta } else { additionalPassRequired = context.isMake(); - context.markDirty(chunk); + context.markDirtyRecursively(chunk); } } diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileContext.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileContext.java index 57a9972ed5e21..d7b4fc88b2185 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileContext.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileContext.java @@ -83,7 +83,7 @@ public void markDirty(final File file) throws Exception { } } - public void markDirty(ModuleChunk chunk) throws Exception { + public void markDirtyRecursively(ModuleChunk chunk) throws Exception { final Set<Module> modules = chunk.getModules(); final Set<Module> dirtyModules = new HashSet<Module>(modules); @@ -147,7 +147,7 @@ void onChunkBuildComplete(@NotNull ModuleChunk chunk) throws Exception { final List<RootDescriptor> roots = myRootsIndex.getModuleRoots(module); for (RootDescriptor descriptor : roots) { if (compilingTests? descriptor.isTestRoot : !descriptor.isTestRoot) { - myFsState.markAllUpToDate(descriptor, myTsStorage, myCompilationStartStamp); + myFsState.markAllUpToDate(getScope(), descriptor, myTsStorage, myCompilationStartStamp); } } } @@ -178,7 +178,7 @@ public void processMessage(BuildMessage msg) { public void processFilesToRecompile(ModuleChunk chunk, FileProcessor processor) throws Exception { for (Module module : chunk.getModules()) { - myFsState.processFilesToRecompile(module, isCompilingTests(), processor); + myFsState.processFilesToRecompile(this, module, processor); } } @@ -188,10 +188,16 @@ final void ensureFSStateInitialized(ModuleChunk chunk) throws Exception { markDirtyFiles(module, myTsStorage, true, isCompilingTests() ? DirtyMarkScope.TESTS : DirtyMarkScope.PRODUCTION, null); } else { - // in 'make' mode - // todo: consider situation when only several files are forced to be compiled => this is not project rebuild and not make - if (myFsState.markInitialScanPerformed(module, isCompilingTests())) { - initModuleFSState(module); + if (isMake()) { + if (myFsState.markInitialScanPerformed(module, isCompilingTests())) { + initModuleFSState(module); + } + } + else { + // forced compilation mode + if (getScope().isRecompilationForced(module)) { + markDirtyFiles(module, myTsStorage, true, isCompilingTests() ? DirtyMarkScope.TESTS : DirtyMarkScope.PRODUCTION, null); + } } } } @@ -233,7 +239,7 @@ public void setDone(float done) { processMessage(new ProgressMessage("", done)); } - private static enum DirtyMarkScope{ + public static enum DirtyMarkScope{ PRODUCTION, TESTS, BOTH } diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileScope.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileScope.java index 6b42d3c0552e0..d1f439c6eb438 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileScope.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/CompileScope.java @@ -1,46 +1,42 @@ package org.jetbrains.jps.incremental; +import org.jetbrains.annotations.NotNull; import org.jetbrains.jps.Module; import org.jetbrains.jps.ModuleChunk; import org.jetbrains.jps.Project; -import java.util.Collection; -import java.util.Collections; -import java.util.Set; +import java.io.File; /** * @author Eugene Zhuravlev - * Date: 9/17/11 + * Date: 1/15/12 */ -public class CompileScope { +public abstract class CompileScope { + @NotNull private final Project myProject; - private final Collection<Module> myModules; - public CompileScope(Project project) { - this(project, project.getModules().values()); - } - - public CompileScope(Project project, Collection<Module> modules) { + protected CompileScope(@NotNull Project project) { myProject = project; - myModules = modules; } - public Collection<Module> getAffectedModules() { - return Collections.unmodifiableCollection(myModules); - } + public abstract boolean isAffected(Module module, @NotNull File file); + + public abstract boolean isAffected(@NotNull Module module); + + public abstract boolean isRecompilationForced(@NotNull Module module); - public boolean isAffected(ModuleChunk chunk) { - final Set<Module> modules = chunk.getModules(); - for (Module module : getAffectedModules()) { - if (modules.contains(module)) { + public final boolean isAffected(ModuleChunk chunk) { + for (Module module : chunk.getModules()) { + if (isAffected(module)) { return true; } } return false; } - public Project getProject() { + @NotNull + public final Project getProject() { return myProject; } } diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/FSState.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/FSState.java index 950265a6950cb..cc89a8d71cd13 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/FSState.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/FSState.java @@ -72,21 +72,26 @@ public void markDirty(final File file, final RootDescriptor rd, final @Nullable } } - public void markAllUpToDate(final RootDescriptor rd, final TimestampStorage tsStorage, final long compilationStartStamp) throws Exception { + public void markAllUpToDate(CompileScope scope, final RootDescriptor rd, final TimestampStorage tsStorage, final long compilationStartStamp) throws Exception { final FilesDelta delta = getDelta(rd.module); final Set<File> files = delta.clearRecompile(rd.root, rd.isTestRoot); if (files != null) { final CompilerExcludes excludes = rd.module.getProject().getCompilerConfiguration().getExcludes(); for (File file : files) { if (!excludes.isExcluded(file)) { - final long stamp = file.lastModified(); - if (stamp > compilationStartStamp) { - // if the file was modified after the compilation had started, - // do not save the stamp considering file dirty - delta.markRecompile(rd.root, rd.isTestRoot, file); + if (scope.isAffected(rd.module, file)) { + final long stamp = file.lastModified(); + if (stamp > compilationStartStamp) { + // if the file was modified after the compilation had started, + // do not save the stamp considering file dirty + delta.markRecompile(rd.root, rd.isTestRoot, file); + } + else { + tsStorage.saveStamp(file, stamp); + } } else { - tsStorage.saveStamp(file, stamp); + delta.markRecompile(rd.root, rd.isTestRoot, file); } } else { @@ -96,16 +101,19 @@ public void markAllUpToDate(final RootDescriptor rd, final TimestampStorage tsSt } } - - public boolean processFilesToRecompile(final Module module, final boolean forTests, final FileProcessor processor) throws Exception { + public boolean processFilesToRecompile(CompileContext context, final Module module, final FileProcessor processor) throws Exception { final FilesDelta lastRoundDelta = myLastRoundDelta; final FilesDelta delta = lastRoundDelta != null? lastRoundDelta : getDelta(module); - final Map<File, Set<File>> data = delta.getSourcesToRecompile(forTests); + final Map<File, Set<File>> data = delta.getSourcesToRecompile(context.isCompilingTests()); final CompilerExcludes excludes = module.getProject().getCompilerConfiguration().getExcludes(); + final CompileScope scope = context.getScope(); synchronized (data) { for (Map.Entry<File, Set<File>> entry : data.entrySet()) { final String root = FileUtil.toSystemIndependentName(entry.getKey().getPath()); for (File file : entry.getValue()) { + if (!scope.isAffected(module, file)) { + continue; + } if (excludes.isExcluded(file)) { continue; } diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java index c7ac05d9ebc93..23ec5ee1e5c34 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java @@ -71,7 +71,7 @@ public void build(CompileScope scope, final boolean isMake, final boolean isProj JPS_SERVER_NAME, BuildMessage.Kind.INFO, "Internal caches are corrupted or have outdated format, forcing project rebuild: " + e.getMessage()) ); - context = createContext(new CompileScope(scope.getProject()), false, true); + context = createContext(new AllProjectScope(scope.getProject(), true), false, true); runBuild(context); } else { diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/ModulesAndFilesScope.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/ModulesAndFilesScope.java new file mode 100644 index 0000000000000..380c0daadf1f3 --- /dev/null +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/ModulesAndFilesScope.java @@ -0,0 +1,49 @@ +package org.jetbrains.jps.incremental; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jps.Module; +import org.jetbrains.jps.Project; + +import java.io.File; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * @author Eugene Zhuravlev + * Date: 9/17/11 + */ +public class ModulesAndFilesScope extends CompileScope { + + private final Set<Module> myModules; + private final Map<Module, Set<File>> myFiles; + private final boolean myForcedCompilation; + + public ModulesAndFilesScope(Project project, Collection<Module> modules, Map<Module, Set<File>> files, boolean isForcedCompilation) { + super(project); + myFiles = files; + myForcedCompilation = isForcedCompilation; + myModules = new HashSet<Module>(modules); + } + + public boolean isRecompilationForced(@NotNull Module module) { + return myForcedCompilation && myModules.contains(module); + } + + public boolean isAffected(@NotNull Module module) { + if (myModules.contains(module) || myFiles.containsKey(module)) { + return true; + } + return false; + } + + public boolean isAffected(Module module, @NotNull File file) { + if (myModules.contains(module)) { + return true; + } + final Set<File> files = myFiles.get(module); + return files != null && files.contains(file); + } + +} diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/ModulesScope.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/ModulesScope.java new file mode 100644 index 0000000000000..56ffec4d7f465 --- /dev/null +++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/ModulesScope.java @@ -0,0 +1,37 @@ +package org.jetbrains.jps.incremental; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jps.Module; +import org.jetbrains.jps.Project; + +import java.io.File; +import java.util.Set; + +/** + * @author Eugene Zhuravlev + * Date: 9/17/11 + */ +public class ModulesScope extends CompileScope { + + private final Set<Module> myModules; + private final boolean myForcedCompilation; + + public ModulesScope(Project project, Set<Module> modules, boolean isForcedCompilation) { + super(project); + myModules = modules; + myForcedCompilation = isForcedCompilation; + } + + public boolean isRecompilationForced(@NotNull Module module) { + return myForcedCompilation && isAffected(module); + } + + public boolean isAffected(@NotNull Module module) { + return myModules.contains(module); + } + + public boolean isAffected(Module module, @NotNull File file) { + return true; // for speed reasons + } + +} diff --git a/jps/jps-builders/src/org/jetbrains/jps/server/ServerMessageHandler.java b/jps/jps-builders/src/org/jetbrains/jps/server/ServerMessageHandler.java index e137a682165aa..6a4c6f28683e9 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/server/ServerMessageHandler.java +++ b/jps/jps-builders/src/org/jetbrains/jps/server/ServerMessageHandler.java @@ -137,7 +137,7 @@ private JpsRemoteProto.Message startBuild(UUID sessionId, final ChannelHandlerCo case MAKE: case FORCED_COMPILATION: case REBUILD: { - final CompilationTask task = new CompilationTask(sessionId, channelContext, projectId, compileRequest.getModuleNameList()); + final CompilationTask task = new CompilationTask(sessionId, channelContext, projectId, compileRequest.getModuleNameList(), compileRequest.getFilePathList()); if (myBuildsInProgress.putIfAbsent(projectId, task) == null) { task.getBuildParams().buildType = convertCompileType(compileType); task.getBuildParams().useInProcessJavac = true; @@ -166,14 +166,16 @@ private class CompilationTask implements Runnable, BuildCanceledStatus { private final UUID mySessionId; private final ChannelHandlerContext myChannelContext; private final String myProjectPath; + private final Collection<String> myPaths; private final Set<String> myModules; private final BuildParameters myParams; private volatile boolean myCanceled = false; - public CompilationTask(UUID sessionId, ChannelHandlerContext channelContext, String projectId, List<String> modules) { + public CompilationTask(UUID sessionId, ChannelHandlerContext channelContext, String projectId, Collection<String> modules, Collection<String> paths) { mySessionId = sessionId; myChannelContext = channelContext; myProjectPath = projectId; + myPaths = paths; myModules = new HashSet<String>(modules); myParams = new BuildParameters(); } @@ -194,7 +196,7 @@ public void run() { Channels.write(myChannelContext.getChannel(), ProtoUtil.toMessage(mySessionId, ProtoUtil.createBuildStartedEvent("build started"))); Throwable error = null; try { - ServerState.getInstance().startBuild(myProjectPath, myModules, myParams, new MessageHandler() { + ServerState.getInstance().startBuild(myProjectPath, myModules, myPaths, myParams, new MessageHandler() { public void processMessage(BuildMessage buildMessage) { final JpsRemoteProto.Message.Response response; if (buildMessage instanceof CompilerMessage) { diff --git a/jps/jps-builders/src/org/jetbrains/jps/server/ServerState.java b/jps/jps-builders/src/org/jetbrains/jps/server/ServerState.java index bfce4ceabeba1..b9d4999d5afe2 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/server/ServerState.java +++ b/jps/jps-builders/src/org/jetbrains/jps/server/ServerState.java @@ -14,6 +14,7 @@ import org.jetbrains.jps.idea.IdeaProjectLoader; import org.jetbrains.jps.incremental.*; import org.jetbrains.jps.incremental.storage.ProjectTimestamps; +import org.jetbrains.jps.incremental.storage.TimestampStorage; import java.io.File; import java.lang.reflect.Method; @@ -96,7 +97,7 @@ public void clearProjectCache(Collection<String> projectPaths) { } } - public void startBuild(String projectPath, Set<String> modules, final BuildParameters params, final MessageHandler msgHandler, BuildCanceledStatus cs) throws Throwable{ + public void startBuild(String projectPath, Set<String> modules, Collection<String> paths, final BuildParameters params, final MessageHandler msgHandler, BuildCanceledStatus cs) throws Throwable{ final String projectName = getProjectName(projectPath); BuildType buildType = params.buildType; @@ -115,20 +116,7 @@ public void startBuild(String projectPath, Set<String> modules, final BuildParam final Project project = pd.project; try { - final List<Module> toCompile = new ArrayList<Module>(); - if (modules != null && modules.size() > 0) { - for (Module m : project.getModules().values()) { - if (modules.contains(m.getName())){ - toCompile.add(m); - } - } - } - else { - toCompile.addAll(project.getModules().values()); - } - - final CompileScope compileScope = new CompileScope(project, toCompile); - + final CompileScope compileScope = createCompilationScope(buildType, pd, modules, paths); final IncProjectBuilder builder = new IncProjectBuilder(pd, BuilderRegistry.getInstance(), cs); if (msgHandler != null) { builder.addMessageHandler(msgHandler); @@ -158,6 +146,60 @@ public void startBuild(String projectPath, Set<String> modules, final BuildParam } } + private static CompileScope createCompilationScope(BuildType buildType, ProjectDescriptor pd, Set<String> modules, Collection<String> paths) throws Exception { + final CompileScope compileScope; + if (buildType == BuildType.PROJECT_REBUILD || (modules.isEmpty() && paths.isEmpty())) { + compileScope = new AllProjectScope(pd.project, buildType != BuildType.MAKE); + } + else { + final Set<Module> forcedModules; + if (!modules.isEmpty()) { + forcedModules = new HashSet<Module>(); + for (Module m : pd.project.getModules().values()) { + if (modules.contains(m.getName())){ + forcedModules.add(m); + } + } + } + else { + forcedModules = Collections.emptySet(); + } + + final TimestampStorage tsStorage = pd.timestamps.getStorage(); + + final Map<Module, Set<File>> filesToCompile; + if (!paths.isEmpty()) { + filesToCompile = new HashMap<Module, Set<File>>(); + for (String path : paths) { + final File file = new File(path); + final RootDescriptor rd = pd.rootsIndex.getModuleAndRoot(file); + if (rd != null) { + Set<File> files = filesToCompile.get(rd.module); + if (files == null) { + files = new HashSet<File>(); + filesToCompile.put(rd.module, files); + } + files.add(file); + if (buildType == BuildType.FORCED_COMPILATION) { + pd.fsState.markDirty(file, rd, tsStorage); + } + } + } + } + else { + filesToCompile = Collections.emptyMap(); + } + + if (filesToCompile.isEmpty()) { + compileScope = new ModulesScope(pd.project, forcedModules, buildType != BuildType.MAKE); + } + else { + compileScope = new ModulesAndFilesScope(pd.project, forcedModules, filesToCompile, buildType != BuildType.MAKE); + } + } + return compileScope; + } + private static void clearZipIndexCache() { try { final Class<?> indexClass = Class.forName("com.sun.tools.javac.zip.ZipFileIndex");
10f91cb0d91dab0e19103754bc2c9bf4b40e96a3
camel
CAMEL-2795: Fixed tests--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@952909 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/camel
diff --git a/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/jettyproducer/JettyHttpProducerTimeoutTest.java b/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/jettyproducer/JettyHttpProducerTimeoutTest.java index e1347e87e2e01..6a223d47cea26 100644 --- a/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/jettyproducer/JettyHttpProducerTimeoutTest.java +++ b/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/jettyproducer/JettyHttpProducerTimeoutTest.java @@ -16,6 +16,7 @@ */ package org.apache.camel.component.jetty.jettyproducer; +import org.apache.camel.Exchange; import org.apache.camel.ExchangeTimedOutException; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.test.junit4.CamelTestSupport; @@ -38,13 +39,11 @@ public void testTimeout() throws Exception { // give Jetty time to startup properly Thread.sleep(1000); - try { - template.request(url, null); - fail("Should have thrown a timeout exception"); - } catch (Exception e) { - ExchangeTimedOutException cause = assertIsInstanceOf(ExchangeTimedOutException.class, e.getCause()); - assertEquals(2000, cause.getTimeout()); - } + Exchange reply = template.request(url, null); + Exception e = reply.getException(); + assertNotNull("Should have thrown an exception", e); + ExchangeTimedOutException cause = assertIsInstanceOf(ExchangeTimedOutException.class, e); + assertEquals(2000, cause.getTimeout()); } @Override
91caac25756464a87e7185c305302353b8bb2faa
Valadoc
driver/0.10.x: Add support for attributes
a
https://github.com/GNOME/vala/
diff --git a/src/driver/0.10.x/treebuilder.vala b/src/driver/0.10.x/treebuilder.vala index 7cb92d3bf2..1c972772bd 100644 --- a/src/driver/0.10.x/treebuilder.vala +++ b/src/driver/0.10.x/treebuilder.vala @@ -184,6 +184,53 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { // 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" + }; + + foreach (Vala.Attribute att in lst) { + if (att.name == "CCode" && att.has_argument ("has_target") && att.get_bool ("has_target") == 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 (att.has_argument ("since")) { + new_attribute.add_string ("since", att.get_string ("since"), att); + } + + if (att.has_argument ("replacement")) { + new_attribute.add_string ("replacement", att.get_string ("replacement"), 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 SourceComment? create_comment (Vala.Comment? comment) { if (comment != null) { Vala.SourceReference pos = comment.source_reference; @@ -737,6 +784,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { } } + process_attributes (node, element.attributes); process_children (node, element); // save GLib.Error @@ -767,6 +815,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { } } + process_attributes (node, element.attributes); process_children (node, element); } @@ -790,6 +839,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { node.base_type = create_type_reference (basetype, node, node); } + process_attributes (node, element.attributes); process_children (node, element); } @@ -806,6 +856,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); } @@ -833,6 +884,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { node.setter = new PropertyAccessor (node, file, element.name, get_access_modifier(element), accessor.get_cname(), get_property_accessor_type (accessor), get_property_ownership (accessor), accessor); } + process_attributes (node, element.attributes); process_children (node, element); } @@ -849,6 +901,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); } @@ -865,6 +918,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); } @@ -881,6 +935,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); } @@ -897,6 +952,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); } @@ -912,6 +968,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); } @@ -927,6 +984,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); } @@ -943,6 +1001,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); } @@ -958,6 +1017,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); } @@ -973,6 +1033,7 @@ public class Valadoc.Drivers.TreeBuilder : Vala.CodeVisitor { symbol_map.set (element, node); parent.add_child (node); + process_attributes (node, element.attributes); process_children (node, element); }
fbb645beca490238e4ed849142d96e18def15e86
tapiji
Adds product icons for RCP translator
a
https://github.com/tapiji/tapiji
diff --git a/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_16.bmp b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_16.bmp new file mode 100644 index 00000000..d4c77139 Binary files /dev/null and b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_16.bmp differ diff --git a/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_32.bmp b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_32.bmp new file mode 100644 index 00000000..88a365f7 Binary files /dev/null and b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_32.bmp differ diff --git a/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_32.xpm b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_32.xpm new file mode 100644 index 00000000..8526353c --- /dev/null +++ b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_32.xpm @@ -0,0 +1,636 @@ +/* XPM */ +static char * TapiJI_32_xpm[] = { +"32 32 601 2", +" c None", +". c #F2B7A1", +"+ c #F4BEA4", +"@ c #F1B8A2", +"# c #F1BBA4", +"$ c #F1BCA7", +"% c #F1BDA9", +"& c #F1BEA9", +"* c #F2BEAA", +"= c #F1BEAA", +"- c #F1BEA8", +"; c #F2BDA8", +"> c #F1BCA5", +", c #F1B9A3", +"' c #F1B8A0", +") c #EEB69E", +"! c #EEB399", +"~ c #EDB195", +"{ c #EDAD91", +"] c #ECAA8C", +"^ c #ECA787", +"/ c #ECA483", +"( c #EAA07E", +"_ c #E89B76", +": c #E79770", +"< c #E59268", +"[ c #E48D61", +"} c #E98B5B", +"| c #D17A4D", +"1 c #F4B8A1", +"2 c #FFD2B6", +"3 c #FFCEB5", +"4 c #FFD0B7", +"5 c #FFD2BA", +"6 c #FFD3BC", +"7 c #FFD4BD", +"8 c #FFD2BB", +"9 c #FFD1B9", +"0 c #FFCFB6", +"a c #FFCDB2", +"b c #FFCBAE", +"c c #FFC8AA", +"d c #FFC4A6", +"e c #FFC1A1", +"f c #FFBD9C", +"g c #FFBA96", +"h c #FFB691", +"i c #FFB28A", +"j c #FFAD84", +"k c #FFA87D", +"l c #FFA374", +"m c #FF9D6C", +"n c #FF9B65", +"o c #D57A4D", +"p c #F2B9A2", +"q c #FFC8AF", +"r c #FEC5AE", +"s c #FFC7B1", +"t c #FFC9B4", +"u c #FFCAB6", +"v c #FFCBB7", +"w c #FFCCB7", +"x c #FFCBB6", +"y c #FEC9B4", +"z c #FEC8B2", +"A c #FEC6AF", +"B c #FDC3AB", +"C c #FDC1A7", +"D c #FCBFA3", +"E c #FBBB9F", +"F c #FAB89A", +"G c #FAB595", +"H c #F9B190", +"I c #F9AD8B", +"J c #F7AA85", +"K c #F6A57F", +"L c #F5A178", +"M c #F49B70", +"N c #F39668", +"O c #F79462", +"P c #D07A4C", +"Q c #F2BBA4", +"R c #FFCAB1", +"S c #FFC7B0", +"T c #FFCAB4", +"U c #FFCEBA", +"V c #FFCFBB", +"W c #FFCDB7", +"X c #FFCBB5", +"Y c #FFC8B2", +"Z c #FFC6AE", +"` c #FFC3AA", +" . c #FFC1A6", +".. c #FCBCA1", +"+. c #FAB99C", +"@. c #FAB597", +"#. c #F9B292", +"$. c #F9AE8C", +"%. c #F8AA86", +"&. c #F6A680", +"*. c #F5A179", +"=. c #F49C71", +"-. c #F39769", +";. c #F79563", +">. c #D07A4D", +",. c #F3BCA6", +"'. c #FFCAB2", +"). c #FAC6B1", +"!. c #F2C1AD", +"~. c #F3C3B0", +"{. c #F3C4B1", +"]. c #F3C4B2", +"^. c #F3C1AE", +"/. c #F2BFAA", +"(. c #F1B8A1", +"_. c #F0B59C", +":. c #F7BA9F", +"<. c #FABA9D", +"[. c #FAB698", +"}. c #FAB393", +"|. c #F9AF8D", +"1. c #F8AB87", +"2. c #F6A781", +"3. c #F5A27A", +"4. c #F49D72", +"5. c #F3976A", +"6. c #F89564", +"7. c #D07B4E", +"8. c #FFCBB3", +"9. c #C8ABA0", +"0. c #D3CBC8", +"a. c #DAD0CD", +"b. c #D9D0CD", +"c. c #D9D0CC", +"d. c #D9CFCB", +"e. c #D9CECA", +"f. c #D9CEC9", +"g. c #D7CDC9", +"h. c #F1C1AD", +"i. c #FBBA9D", +"j. c #F8AB88", +"k. c #F5A27B", +"l. c #F49D73", +"m. c #F3986B", +"n. c #F89664", +"o. c #C3AEA6", +"p. c #F8FEFF", +"q. c #FFFFFF", +"r. c #FCD2BF", +"s. c #FAB89B", +"t. c #FAB699", +"u. c #F6A782", +"v. c #D0B4A8", +"w. c #F8F2EF", +"x. c #FFF8F5", +"y. c #FFF8F6", +"z. c #FFFEFD", +"A. c #FFFDFD", +"B. c #FFF7F4", +"C. c #FFF9F6", +"D. c #FCD0BC", +"E. c #FABB9E", +"F. c #FAB596", +"G. c #F8AD8A", +"H. c #F6A984", +"I. c #F5A47D", +"J. c #F49F75", +"K. c #FFC9B1", +"L. c #FBC7B2", +"M. c #FECDB9", +"N. c #FFCFBC", +"O. c #FFD1BF", +"P. c #ECC3B3", +"Q. c #DED9D7", +"R. c #FFF3EE", +"S. c #FECBB5", +"T. c #FDC2AA", +"U. c #FCB99D", +"V. c #FBAF8F", +"W. c #FAA37D", +"X. c #F89B72", +"Y. c #F7966A", +"Z. c #F79163", +"`. c #F69062", +" + c #F59061", +".+ c #F49162", +"++ c #F39363", +"@+ c #F39365", +"#+ c #F39465", +"$+ c #F79666", +"%+ c #D07C4F", +"&+ c #FFC8B1", +"*+ c #FFCCB6", +"=+ c #E6B7A5", +"-+ c #D2CDCB", +";+ c #FEE9E0", +">+ c #FCA07A", +",+ c #FA976C", +"'+ c #F98E61", +")+ c #F98B5C", +"!+ c #F88A59", +"~+ c #F78855", +"{+ c #F68451", +"]+ c #F6824D", +"^+ c #F47F49", +"/+ c #F37D46", +"(+ c #F27A41", +"_+ c #F0773B", +":+ c #EE7538", +"<+ c #EF763A", +"[+ c #F37D40", +"}+ c #CE6E3C", +"|+ c #F2B8A0", +"1+ c #FFC6AC", +"2+ c #FEC3AB", +"3+ c #FEC7B0", +"4+ c #E6B9A7", +"5+ c #D4CECC", +"6+ c #FEE3D8", +"7+ c #FA9063", +"8+ c #F99164", +"9+ c #F99063", +"0+ c #F98E5F", +"a+ c #F88B5C", +"b+ c #F68958", +"c+ c #F68754", +"d+ c #F58450", +"e+ c #F4824C", +"f+ c #F37F48", +"g+ c #F27C43", +"h+ c #F0783D", +"i+ c #EE7436", +"j+ c #ED6F2F", +"k+ c #F16E29", +"l+ c #CC5A1F", +"m+ c #F2B69D", +"n+ c #FFC4A9", +"o+ c #FEC1A8", +"p+ c #FEC2AA", +"q+ c #FEC4AD", +"r+ c #FFC2A8", +"s+ c #E69E80", +"t+ c #D4CAC6", +"u+ c #FEE4D8", +"v+ c #FA9164", +"w+ c #F98F61", +"x+ c #F88D5D", +"y+ c #F88A5A", +"z+ c #F68856", +"A+ c #F68552", +"B+ c #F5834E", +"C+ c #F3814B", +"D+ c #F37E46", +"E+ c #F17B41", +"F+ c #EE7335", +"G+ c #ED7030", +"H+ c #F16F2B", +"I+ c #CB5B20", +"J+ c #F1B59A", +"K+ c #FFC2A6", +"L+ c #FDBEA4", +"M+ c #FEC0A8", +"N+ c #FDB396", +"O+ c #FE9D74", +"P+ c #E48963", +"Q+ c #D4C9C5", +"R+ c #FEE3D7", +"S+ c #F98F62", +"T+ c #F98D5E", +"U+ c #F88B5B", +"V+ c #F68957", +"W+ c #F68450", +"X+ c #F38049", +"Y+ c #F37D44", +"Z+ c #F1793F", +"`+ c #EF7539", +" @ c #EE7233", +".@ c #EC6E2E", +"+@ c #CB5A1F", +"@@ c #EFB297", +"#@ c #FFBFA2", +"$@ c #FBA987", +"%@ c #FA9469", +"&@ c #FD9468", +"*@ c #E38963", +"=@ c #F98C5E", +"-@ c #FA8E5F", +";@ c #FA8A57", +">@ c #F6834F", +",@ c #F5804B", +"'@ c #F57E48", +")@ c #F47D46", +"!@ c #F4804A", +"~@ c #F67C42", +"{@ c #F07337", +"]@ c #EF7031", +"^@ c #ED6C2C", +"/@ c #EC6925", +"(@ c #EA6622", +"_@ c #F06C26", +":@ c #CB591E", +"<@ c #EFAF93", +"[@ c #FFBC9E", +"}@ c #FBBA9E", +"|@ c #FAA47F", +"1@ c #F99062", +"2@ c #F99165", +"3@ c #FC9366", +"4@ c #E28760", +"5@ c #D4C9C4", +"6@ c #FEE2D6", +"7@ c #F98B5B", +"8@ c #F48859", +"9@ c #C3896F", +"0@ c #D0A490", +"a@ c #D1A28D", +"b@ c #D0A28D", +"c@ c #D39D83", +"d@ c #EE804D", +"e@ c #C17F60", +"f@ c #CD9E87", +"g@ c #CE9B82", +"h@ c #CD9A80", +"i@ c #CD9B81", +"j@ c #CE9578", +"k@ c #EB7131", +"l@ c #CB5617", +"m@ c #EEAC8F", +"n@ c #FFBB9B", +"o@ c #FAA47E", +"p@ c #F98F60", +"q@ c #FC9162", +"r@ c #E2845C", +"s@ c #FDE1D5", +"t@ c #FA8957", +"u@ c #DC7D52", +"v@ c #C3C3C3", +"w@ c #FEFFFF", +"x@ c #FBFFFF", +"y@ c #FBE8DF", +"z@ c #E17744", +"A@ c #BFB2AC", +"B@ c #FCFFFF", +"C@ c #F8E8DF", +"D@ c #EF712E", +"E@ c #C85415", +"F@ c #EFAD90", +"G@ c #FFAD88", +"H@ c #F88C5D", +"I@ c #F88D5E", +"J@ c #FB8E5E", +"K@ c #E18259", +"L@ c #D3C8C3", +"M@ c #FDE0D4", +"N@ c #F78653", +"O@ c #ED8454", +"P@ c #EE9A74", +"Q@ c #ECA27F", +"R@ c #E6DEDA", +"S@ c #FCCCB5", +"T@ c #EB743B", +"U@ c #EB8756", +"V@ c #D6AE9A", +"W@ c #FFF6F1", +"X@ c #F29A6D", +"Y@ c #ED7F44", +"Z@ c #EE671F", +"`@ c #C85617", +" # c #EFA685", +".# c #FF9565", +"+# c #F78A59", +"@# c #FA8B59", +"## c #E08055", +"$# c #FDE0D3", +"%# c #F88651", +"&# c #FB7F46", +"*# c #CF7145", +"=# c #D2D2D2", +"-# c #F7AA86", +";# c #F27538", +"># c #EC6C2D", +",# c #B49483", +"'# c #FBDFD0", +")# c #E9641E", +"!# c #E86018", +"~# c #EE671E", +"{# c #C85516", +"]# c #EC9066", +"^# c #FD8954", +"/# c #F68653", +"(# c #F68755", +"_# c #F98855", +":# c #DE7D51", +"<# c #D1CCC9", +"[# c #FEE5DB", +"}# c #F5814B", +"|# c #F5824D", +"1# c #F67F48", +"2# c #C18163", +"3# c #EBF0F3", +"4# c #FFFCFA", +"5# c #F39060", +"6# c #F17335", +"7# c #D76A33", +"8# c #C8BCB6", +"9# c #F6C0A4", +"0# c #E9621C", +"a# c #E86520", +"b# c #ED651C", +"c# c #C75414", +"d# c #E87D4A", +"e# c #FC864F", +"f# c #F5834F", +"g# c #F58451", +"h# c #F68551", +"i# c #F88551", +"j# c #E67E4E", +"k# c #DDB29E", +"l# c #FCDAC9", +"m# c #FBD9C9", +"n# c #F9C1A7", +"o# c #F3804A", +"p# c #F37B42", +"q# c #B7927F", +"r# c #FDEAE1", +"s# c #F07C43", +"t# c #F17232", +"u# c #CA6D3E", +"v# c #D8D9DA", +"w# c #F19C6F", +"x# c #E8621A", +"y# c #E8641D", +"z# c #EC6419", +"A# c #C75312", +"B# c #E67745", +"C# c #FB844C", +"D# c #F4824D", +"E# c #F67E47", +"F# c #F37B43", +"G# c #F37A42", +"H# c #F37E48", +"I# c #F57E46", +"J# c #E3733C", +"K# c #C0AEA5", +"L# c #F9D2BE", +"M# c #EE6F2F", +"N# c #F06E2C", +"O# c #BC7957", +"P# c #EDF3F6", +"Q# c #FFFAF7", +"R# c #ED8047", +"S# c #E76118", +"T# c #E7621A", +"U# c #EC6217", +"V# c #C75210", +"W# c #E67640", +"X# c #FA8147", +"Y# c #F37E47", +"Z# c #F37F49", +"`# c #F37F47", +" $ c #F47E46", +".$ c #F4793D", +"+$ c #F4763A", +"@$ c #F77536", +"#$ c #C26B40", +"$$ c #D5D5D5", +"%$ c #F5AE89", +"&$ c #F06A26", +"*$ c #EA621C", +"=$ c #B28C78", +"-$ c #FBE2D4", +";$ c #E9631C", +">$ c #E76016", +",$ c #E66017", +"'$ c #EB6014", +")$ c #C64F0F", +"!$ c #E5733B", +"~$ c #F87D41", +"{$ c #F27B42", +"]$ c #F27C44", +"^$ c #F37C42", +"/$ c #E6763F", +"($ c #C88564", +"_$ c #DC8A62", +":$ c #C97E58", +"<$ c #BAA99F", +"[$ c #FAFFFF", +"}$ c #FEF3EE", +"|$ c #F07E44", +"1$ c #CB6B3B", +"2$ c #C4805D", +"3$ c #CABFB9", +"4$ c #F7E0D5", +"5$ c #CF8258", +"6$ c #DF6725", +"7$ c #E65E13", +"8$ c #EB5F12", +"9$ c #C64E0C", +"0$ c #E26E35", +"a$ c #F6793B", +"b$ c #EF773B", +"c$ c #F0773C", +"d$ c #F3783A", +"e$ c #CD6F41", +"f$ c #CBD5DA", +"g$ c #EFFCFF", +"h$ c #EAF8FE", +"i$ c #FFF4EF", +"j$ c #F29B6D", +"k$ c #E5621D", +"l$ c #B09B90", +"m$ c #F3FFFF", +"n$ c #F4F4F5", +"o$ c #E67334", +"p$ c #E55A0E", +"q$ c #EA5D10", +"r$ c #C64E0B", +"s$ c #E26C2F", +"t$ c #F57535", +"u$ c #EE7437", +"v$ c #EF7334", +"w$ c #DD723D", +"x$ c #E7AD90", +"y$ c #FAC6AA", +"z$ c #FBC3A7", +"A$ c #F4AA84", +"B$ c #ED7F46", +"C$ c #EA651F", +"D$ c #E46625", +"E$ c #DC8150", +"F$ c #F39C6F", +"G$ c #F0996A", +"H$ c #EF9767", +"I$ c #EE9766", +"J$ c #EE8D58", +"K$ c #E66016", +"L$ c #E45B0F", +"M$ c #EA5C0E", +"N$ c #C64D0A", +"O$ c #E06729", +"P$ c #F3722F", +"Q$ c #ED7031", +"R$ c #ED7131", +"S$ c #EE6F2E", +"T$ c #ED6825", +"U$ c #EA6621", +"V$ c #E96824", +"W$ c #E96722", +"X$ c #EB6118", +"Y$ c #E65A0F", +"Z$ c #E5590C", +"`$ c #E55709", +" % c #E45507", +".% c #E45506", +"+% c #E45A0D", +"@% c #EA5C0C", +"#% c #E26525", +"$% c #FF742B", +"%% c #F9722B", +"&% c #F9722C", +"*% c #F9732D", +"=% c #F9732E", +"-% c #F8712B", +";% c #F87029", +">% c #F87027", +",% c #F76E26", +"'% c #F76D25", +")% c #F66C23", +"!% c #F66B20", +"~% c #F56A1E", +"{% c #F5681C", +"]% c #F46619", +"^% c #F36517", +"/% c #F36314", +"(% c #F26112", +"_% c #F2600F", +":% c #F15F0E", +"<% c #F15F0D", +"[% c #F8610D", +"}% c #CB4F0B", +"|% c #CE5A1E", +"1% c #D25E1F", +"2% c #C8591E", +"3% c #CA5A20", +"4% c #CA5B20", +"5% c #CA5B21", +"6% c #C95A1E", +"7% c #C9591D", +"8% c #C9581C", +"9% c #C9561B", +"0% c #C85619", +"a% c #C85416", +"b% c #C65314", +"c% c #C65212", +"d% c #C55011", +"e% c #C5500E", +"f% c #C54E0C", +"g% c #C44D0B", +"h% c #C44D0A", +"i% c #C94F0A", +"j% c #AE4308", +" ", +" ", +" . + @ # $ % & * = - ; > , ' ) ! ~ { ] ^ / ( _ : < [ } | ", +" 1 2 3 4 5 6 7 7 7 6 8 9 0 a b c d e f g h i j k l m n o ", +" p q r s t u v w v x y z A B C D E F G H I J K L M N O P ", +" Q R S T w U V V V U W X Y Z ` ...+.@.#.$.%.&.*.=.-.;.>. ", +" ,.'.s ).!.~.{.].{.~.^./.; # (._.:.<.[.}.|.1.2.3.4.5.6.7. ", +" ,.8.Y 9.0.a.b.b.b.c.c.d.d.e.f.g.h.i.[.}.|.j.2.k.l.m.n.7. ", +" ,.8.s o.p.q.q.q.q.q.q.q.q.q.q.q.r.s.t.}.|.j.u.k.l.m.n.7. ", +" ,.'.S v.w.x.x.y.z.q.q.A.B.x.C.y.D.E.s.F.H G.H.I.J.m.6.7. ", +" Q K.A L.M.N.O.P.Q.q.q.R.S.T.U.V.W.X.Y.Z.`. +.+++@+#+$+%+ ", +" p q r &+&+t *+=+-+q.q.;+>+,+'+)+!+~+{+]+^+/+(+_+:+<+[+}+ ", +" |+1+2+r 3+z *+4+5+q.q.6+7+8+9+0+a+b+c+d+e+f+g+h+i+j+k+l+ ", +" m+n+o+p+q+z r+s+t+q.q.u+v+8+w+x+y+z+A+B+C+D+E+_+F+G+H+I+ ", +" J+K+L+M+2+N+O+P+Q+q.q.R+w+S+T+U+V+c+W+e+X+Y+Z+`+ @.@k++@ ", +" @@#@..L+$@%@&@*@Q+q.q.R+=@-@;@>@,@'@)@!@~@{@]@^@/@(@_@:@ ", +" <@[@}@|@1@2@3@4@[email protected]@7@8@9@0@a@b@c@d@e@f@g@h@i@j@k@l@ ", +" m@n@o@T+p@S+q@r@[email protected]@t@u@v@w@w@x@y@z@[email protected]@B@B@C@D@E@ ", +" F@G@U+U+H@I@J@K@[email protected]@N@O@P@Q@[email protected]@T@U@V@B@W@X@Y@Z@`@ ", +" #.#c+b++#+#@###[email protected].$#>@%#&#*#=#q.-#;#>#,#w@'#)#!#~#{# ", +" ]#^#/#c+(#(#_#:#<#q.q.[#}#|#1#2#3#4#5#6#7#8#q.9#0#a#b#c# ", +" d#e#f#W+g#h#i#j#k#l#m#n#X+o#p#q#B@r#s#t#u#v#q.w#x#y#z#A# ", +" B#C#C+C+e+D#D#|#E#F#G#F#H#I#J#K#q.L#M#N#O#P#Q#R#S#T#U#V# ", +" W#X#Y#f+f+Z#X+Z#`#D+ $.$+$@$#$$$q.%$&$*$=$B@-$;$>$,$'$)$ ", +" !$~$E+{$g+]$]$g+g+^$/$($_$:$<$[$}$|$1$2$3$q.4$5$6$7$8$9$ ", +" 0$a$b$c$h+h+h+h+h+d$e$f$g$h$q.i$j$k$l$m$q.q.q.n$o$p$q$r$ ", +" s$t$F+i+u$u$u$u$u$v$w$x$y$z$A$B$C$D$E$F$G$H$I$J$K$L$M$N$ ", +" O$P$j+G+G+Q$Q$R$Q$G+S$T$U$C$*$)#V$W$X$Y$Z$`$ %.%L$+%@%N$ ", +" #%$%%%&%*%*%=%*%*%&%-%;%>%,%'%)%!%~%{%]%^%/%(%_%:%<%[%}% ", +" |%1%2%3%4%5%5%4%4%3%6%6%7%8%9%0%a%E@b%c%d%e%f%g%g%h%i%j% ", +" ", +" "}; diff --git a/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_48.bmp b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_48.bmp new file mode 100644 index 00000000..88e384d2 Binary files /dev/null and b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_48.bmp differ diff --git a/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_48.xpm b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_48.xpm new file mode 100644 index 00000000..856a18a9 --- /dev/null +++ b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_48.xpm @@ -0,0 +1,1048 @@ +/* XPM */ +static char * TapiJI_48_xpm[] = { +"48 48 997 2", +" c None", +". c #F2BAA2", +"+ c #F4BDA4", +"@ c #F1B79F", +"# c #F0B7A1", +"$ c #F0BAA3", +"% c #F0BBA5", +"& c #F0BBA6", +"* c #F0BCA7", +"= c #F0BDA8", +"- c #F0BDA9", +"; c #F0BEA9", +"> c #F1BEA9", +", c #F1BDA8", +"' c #F1BDA7", +") c #F1BCA6", +"! c #EEBAA3", +"~ c #EEB8A1", +"{ c #EEB79E", +"] c #EDB69D", +"^ c #EDB39B", +"/ c #ECB298", +"( c #ECB096", +"_ c #EBAE92", +": c #EBAC90", +"< c #EBA98C", +"[ c #EBA889", +"} c #EBA586", +"| c #E9A383", +"1 c #E8A07F", +"2 c #E79E7B", +"3 c #E79C77", +"4 c #E79873", +"5 c #E6956E", +"6 c #E49269", +"7 c #E48F64", +"8 c #E28B5F", +"9 c #E3885B", +"0 c #E88958", +"a c #C57246", +"b c #F4BAA1", +"c c #FFCFB3", +"d c #FFCBB0", +"e c #FFCCB3", +"f c #FFCEB5", +"g c #FFCFB7", +"h c #FFD0B8", +"i c #FFD1BA", +"j c #FFD2BA", +"k c #FFD3BB", +"l c #FFD3BC", +"m c #FFD2BB", +"n c #FFD1B8", +"o c #FFD0B7", +"p c #FFCFB6", +"q c #FFCDB4", +"r c #FFCCB2", +"s c #FFC9AD", +"t c #FFC7AA", +"u c #FFC5A7", +"v c #FFC3A5", +"w c #FFC1A1", +"x c #FFBF9E", +"y c #FFBD9B", +"z c #FFBA97", +"A c #FFB894", +"B c #FFB590", +"C c #FFB38C", +"D c #FFB088", +"E c #FFAD83", +"F c #FFAA7E", +"G c #FFA679", +"H c #FFA274", +"I c #FF9F6E", +"J c #FF9B68", +"K c #FF9763", +"L c #FF9860", +"M c #C57145", +"N c #F0B8A1", +"O c #FFC6AB", +"P c #FEC2A9", +"Q c #FEC3AB", +"R c #FEC5AD", +"S c #FFC6AF", +"T c #FFC7B1", +"U c #FFC8B2", +"V c #FFC9B3", +"W c #FFC9B4", +"X c #FFCAB4", +"Y c #FFCAB5", +"Z c #FEC9B4", +"` c #FEC8B3", +" . c #FEC8B2", +".. c #FEC7B1", +"+. c #FEC6AF", +"@. c #FDC3AB", +"#. c #FDC2A9", +"$. c #FDC0A6", +"%. c #FCBEA3", +"&. c #FBBCA1", +"*. c #FABA9E", +"=. c #FAB89B", +"-. c #FAB698", +";. c #FAB494", +">. c #F9B291", +",. c #F9AF8D", +"'. c #F9AD8A", +"). c #F8AA86", +"!. c #F7A882", +"~. c #F6A57E", +"{. c #F5A27A", +"]. c #F59E74", +"^. c #F39B6F", +"/. c #F3976A", +"(. c #F29465", +"_. c #F1905F", +":. c #F7915D", +"<. c #B96B43", +"[. c #F0B8A2", +"}. c #FFC7AD", +"|. c #FFCAB6", +"1. c #FFCBB6", +"2. c #FFCBB7", +"3. c #FDC4AD", +"4. c #FDC3AA", +"5. c #FDC1A8", +"6. c #FDC0A5", +"7. c #FBBEA2", +"8. c #FBBB9F", +"9. c #FAB99D", +"0. c #FAB799", +"a. c #FAB596", +"b. c #FAB392", +"c. c #F9B08F", +"d. c #F9AE8B", +"e. c #F8AB88", +"f. c #F7A884", +"g. c #F6A57F", +"h. c #F5A37B", +"i. c #F59F76", +"j. c #F49C70", +"k. c #F3986B", +"l. c #F39566", +"m. c #F19161", +"n. c #F8925E", +"o. c #B86B42", +"p. c #FFC8AE", +"q. c #FEC4AC", +"r. c #FFC8B3", +"s. c #FFCCB8", +"t. c #FFCCB9", +"u. c #FFCDB9", +"v. c #FFCCB7", +"w. c #FECBB6", +"x. c #FEC7B0", +"y. c #FEC5AE", +"z. c #FDC4AB", +"A. c #FBBCA0", +"B. c #FABA9D", +"C. c #FAB89A", +"D. c #FAB597", +"E. c #FAB393", +"F. c #F9B190", +"G. c #F9AE8C", +"H. c #F7A985", +"I. c #F6A680", +"J. c #F5A37C", +"K. c #F5A076", +"L. c #F49C71", +"M. c #F3996C", +"N. c #F39567", +"O. c #F19261", +"P. c #F8925F", +"Q. c #B86B43", +"R. c #F0BAA5", +"S. c #FFC9B0", +"T. c #FEC4AD", +"U. c #FFC6B0", +"V. c #FFCDBA", +"W. c #FFCEBB", +"X. c #FFCEBA", +"Y. c #FECAB5", +"Z. c #FDC2AA", +"`. c #FDC0A7", +" + c #FCBFA4", +".+ c #FBBDA1", +"++ c #F9AE8D", +"@+ c #F8AC89", +"#+ c #F7AA85", +"$+ c #F6A781", +"%+ c #F6A47C", +"&+ c #F5A077", +"*+ c #F49D72", +"=+ c #F3996D", +"-+ c #F39668", +";+ c #F19262", +">+ c #F8935F", +",+ c #B86C43", +"'+ c #FFC9B1", +")+ c #FFCAB3", +"!+ c #FFCDB7", +"~+ c #FFCEB9", +"{+ c #FFCFBB", +"]+ c #FFD0BC", +"^+ c #FFD0BD", +"/+ c #FFCFBA", +"(+ c #FFCCB6", +"_+ c #FFCBB4", +":+ c #FFC9B2", +"<+ c #FFC8AF", +"[+ c #FFC5AD", +"}+ c #FFC3AA", +"|+ c #FFC1A7", +"1+ c #FFBFA4", +"2+ c #FCBDA2", +"3+ c #FABB9F", +"4+ c #FAB99C", +"5+ c #FAB495", +"6+ c #F6A782", +"7+ c #F6A47D", +"8+ c #F5A178", +"9+ c #F59D73", +"0+ c #F39A6D", +"a+ c #F29363", +"b+ c #F89360", +"c+ c #FFCAB1", +"d+ c #FFC5AE", +"e+ c #F8C4AF", +"f+ c #C7A699", +"g+ c #CAAEA3", +"h+ c #CBAFA4", +"i+ c #CBAFA5", +"j+ c #CBB0A6", +"k+ c #CBB0A5", +"l+ c #CBAFA3", +"m+ c #CBAEA3", +"n+ c #CBADA1", +"o+ c #CBADA0", +"p+ c #CBAC9E", +"q+ c #CAAB9D", +"r+ c #CAA99C", +"s+ c #CAA89A", +"t+ c #C9A798", +"u+ c #ECB69F", +"v+ c #FDBCA0", +"w+ c #F9B292", +"x+ c #F9AF8E", +"y+ c #F6A47E", +"z+ c #F39A6E", +"A+ c #F39669", +"B+ c #B96C45", +"C+ c #EBBAA6", +"D+ c #A4A09E", +"E+ c #E4E7E8", +"F+ c #E4E7E7", +"G+ c #E5E7E8", +"H+ c #E5E8E8", +"I+ c #E4E9EA", +"J+ c #F4CBB8", +"K+ c #FBBA9E", +"L+ c #FAB595", +"M+ c #FAB292", +"N+ c #F89461", +"O+ c #B7B0AD", +"P+ c #FFFFFF", +"Q+ c #FDD4C0", +"R+ c #EAB9A5", +"S+ c #B1ACAA", +"T+ c #FCD3C1", +"U+ c #FAB291", +"V+ c #F8AD8A", +"W+ c #B96C43", +"X+ c #FFC8B1", +"Y+ c #C6B4AD", +"Z+ c #FEF2ED", +"`+ c #FEF2EE", +" @ c #FDF3EF", +".@ c #FCFCFB", +"+@ c #FFF8F6", +"@@ c #FEF1EB", +"#@ c #FEF1EC", +"$@ c #FCCFBB", +"%@ c #FABCA0", +"&@ c #F9B494", +"*@ c #F9AF8C", +"=@ c #F6A985", +"-@ c #F5A37A", +";@ c #FFCBB8", +">@ c #E3B9A9", +",@ c #CDCBCB", +"'@ c #FFE4D9", +")@ c #FEC6B0", +"!@ c #FCBCA1", +"~@ c #FCB496", +"{@ c #FBAD8C", +"]@ c #FAA682", +"^@ c #F9A07A", +"/@ c #F89B72", +"(@ c #F7976C", +"_@ c #F79365", +":@ c #F79163", +"<@ c #F79264", +"[@ c #F69263", +"}@ c #F59365", +"|@ c #F59567", +"1@ c #F5986B", +"2@ c #F4986C", +"3@ c #F49A6E", +"4@ c #F39A6F", +"5@ c #F3986A", +"6@ c #F19465", +"7@ c #FFC7B0", +"8@ c #D9B1A0", +"9@ c #BCBBBA", +"0@ c #FEE0D5", +"a@ c #FDB89B", +"b@ c #FCAD8B", +"c@ c #FBA07A", +"d@ c #FA986E", +"e@ c #F99163", +"f@ c #F98C5D", +"g@ c #F98A5B", +"h@ c #F88958", +"i@ c #F78755", +"j@ c #F68552", +"k@ c #F6834F", +"l@ c #F5824D", +"m@ c #F4804A", +"n@ c #F37F47", +"o@ c #F37D45", +"p@ c #F37B42", +"q@ c #F1793E", +"r@ c #F1793F", +"s@ c #F07C42", +"t@ c #EF7E46", +"u@ c #F0844E", +"v@ c #F08A56", +"w@ c #F8915D", +"x@ c #B86C46", +"y@ c #FFC7AC", +"z@ c #FEC2AA", +"A@ c #FEC5AF", +"B@ c #FFCEB8", +"C@ c #DBB1A0", +"D@ c #BFBEBD", +"E@ c #FDCDB9", +"F@ c #FB9367", +"G@ c #FA9266", +"H@ c #FA9163", +"I@ c #F99062", +"J@ c #F98F61", +"K@ c #F98E5F", +"L@ c #F88D5D", +"M@ c #F88B5B", +"N@ c #F68958", +"O@ c #F68855", +"P@ c #F68653", +"Q@ c #F58450", +"R@ c #F4824C", +"S@ c #F3814A", +"T@ c #F37F48", +"U@ c #F37D44", +"V@ c #F17A41", +"W@ c #F1773C", +"X@ c #EE7436", +"Y@ c #EE7132", +"Z@ c #ED6E2E", +"`@ c #EC6E2D", +" # c #F37635", +".# c #B65C2D", +"+# c #EFB7A1", +"@# c #FEC1A8", +"## c #FEC3AA", +"$# c #DBB1A1", +"%# c #BFBDBD", +"&# c #FDCAB4", +"*# c #FA9165", +"=# c #FA9468", +"-# c #F99266", +";# c #F88C5C", +"># c #F78A5A", +",# c #F68957", +"'# c #F68754", +")# c #F5844F", +"!# c #F4824B", +"~# c #F3804A", +"{# c #F37E47", +"]# c #F27C43", +"^# c #F17A3F", +"/# c #F0773C", +"(# c #EE7537", +"_# c #EE7233", +":# c #ED7030", +"<# c #EB6D2B", +"[# c #F26C27", +"}# c #B54F1B", +"|# c #EFB69F", +"1# c #FFC4A9", +"2# c #FEC0A6", +"3# c #DBA48E", +"4# c #BFBCBB", +"5# c #FA9064", +"6# c #F99366", +"7# c #F99165", +"8# c #F98E60", +"9# c #F98D5E", +"0# c #F78958", +"a# c #F68856", +"b# c #F68654", +"c# c #F58551", +"d# c #F5834E", +"e# c #F4814B", +"f# c #F37F49", +"g# c #F37E46", +"h# c #F17C43", +"i# c #EF773B", +"j# c #EE7437", +"k# c #EE7232", +"l# c #EC6F2F", +"m# c #F26E29", +"n# c #B5511C", +"o# c #EFB59D", +"p# c #FFC3A7", +"q# c #FDBEA4", +"r# c #FEC0A7", +"s# c #FFA884", +"t# c #D98866", +"u# c #BFBCBA", +"v# c #FCC9B3", +"w# c #FA8F62", +"x# c #F99265", +"y# c #F99063", +"z# c #F68755", +"A# c #F27D45", +"B# c #F1783D", +"C# c #EF7639", +"D# c #EE7335", +"E# c #EE7131", +"F# c #EC6E2E", +"G# c #EB6C2A", +"H# c #F16D28", +"I# c #EEB49A", +"J# c #FFC1A5", +"K# c #FDBDA2", +"L# c #FDB192", +"M# c #FB9A72", +"N# c #FF966B", +"O# c #D88764", +"P# c #FCC8B3", +"Q# c #F88C5D", +"R# c #F68756", +"S# c #F38049", +"T# c #F27C44", +"U# c #EF7538", +"V# c #EE7234", +"W# c #EB6B29", +"X# c #F16C26", +"Y# c #B34F1B", +"Z# c #EEB299", +"`# c #FFC0A2", +" $ c #FCBBA0", +".$ c #FDBFA5", +"+$ c #FCA783", +"@$ c #FB9469", +"#$ c #FB9569", +"$$ c #FE976C", +"%$ c #D88663", +"&$ c #FCC8B1", +"*$ c #F88A59", +"=$ c #F5824C", +"-$ c #F3814B", +";$ c #F17B42", +">$ c #F0763A", +",$ c #EE7133", +"'$ c #EA6B28", +")$ c #B34F1A", +"!$ c #ECB196", +"~$ c #FFBEA0", +"{$ c #FBBA9D", +"]$ c #FCBB9F", +"^$ c #FCBDA3", +"/$ c #FDBA9F", +"($ c #FB9F79", +"_$ c #FA9469", +":$ c #FE9569", +"<$ c #D78561", +"[$ c #FCC7B0", +"}$ c #F98C5C", +"|$ c #FA8D5D", +"1$ c #FD8B59", +"2$ c #F98652", +"3$ c #F88450", +"4$ c #F8834E", +"5$ c #F8814B", +"6$ c #F78049", +"7$ c #F77E45", +"8$ c #F48049", +"9$ c #F87E44", +"0$ c #F4773C", +"a$ c #F27538", +"b$ c #F17234", +"c$ c #F0702F", +"d$ c #EF6D2C", +"e$ c #EF6B28", +"f$ c #ED6825", +"g$ c #EC6722", +"h$ c #EA6A26", +"i$ c #F16B24", +"j$ c #B34F19", +"k$ c #ECAE93", +"l$ c #FFBC9D", +"m$ c #FBB79A", +"n$ c #FBB79B", +"o$ c #F99C73", +"p$ c #F98F62", +"q$ c #FD9366", +"r$ c #D7835F", +"s$ c #FCC6AF", +"t$ c #F5895A", +"u$ c #BB7A5D", +"v$ c #C08B74", +"w$ c #C28C73", +"x$ c #C28B72", +"y$ c #C28B71", +"z$ c #C28A70", +"A$ c #C08A71", +"B$ c #DD8459", +"C$ c #F77F46", +"D$ c #BD714D", +"E$ c #BB8368", +"F$ c #C18568", +"G$ c #BF8466", +"H$ c #BE8364", +"I$ c #BE8163", +"J$ c #BE8061", +"K$ c #BD8060", +"L$ c #C27C58", +"M$ c #E46B2C", +"N$ c #F16A22", +"O$ c #B34E19", +"P$ c #EDAE91", +"Q$ c #FFBA9A", +"R$ c #FAB598", +"S$ c #FA9B72", +"T$ c #F98E5E", +"U$ c #FD9264", +"V$ c #D7815D", +"W$ c #FCC5AE", +"X$ c #F88857", +"Y$ c #FB8C5B", +"Z$ c #DE7E52", +"`$ c #9E9896", +" % c #EAF2F6", +".% c #ECF2F5", +"+% c #ECF3F7", +"@% c #F09E78", +"#% c #E7733C", +"$% c #988A82", +"%% c #E6F1F7", +"&% c #EDF4F8", +"*% c #ECF3F6", +"=% c #EDF5FA", +"-% c #EDF7FC", +";% c #EBD9D0", +">% c #E86B29", +",% c #F06821", +"'% c #B34D17", +")% c #EDAB8F", +"!% c #FFB897", +"~% c #FAB496", +"{% c #F99E75", +"]% c #F98F60", +"^% c #FD9061", +"/% c #D7805B", +"(% c #BFBBBA", +"_% c #FBC5AD", +":% c #FB8B58", +"<% c #C57653", +"[% c #BAC1C5", +"}% c #FFF8F3", +"|% c #F9905E", +"1% c #D16D3E", +"2% c #B2AAA7", +"3% c #FFFFFE", +"4% c #F9C5AA", +"5% c #E8631B", +"6% c #F06820", +"7% c #B24D16", +"8% c #ECA98A", +"9% c #FFB796", +"0% c #F9A47E", +"a% c #F88A5A", +"b% c #F98D5D", +"c% c #F88D5E", +"d% c #FD8E5E", +"e% c #D77F58", +"f% c #FBC4AB", +"g% c #F78855", +"h% c #E58255", +"i% c #EB9974", +"j% c #FAA57D", +"k% c #EBA484", +"l% c #E0DDDB", +"m% c #FCE1D5", +"n% c #E87841", +"o% c #E78556", +"p% c #E98E61", +"q% c #D3C5BE", +"r% c #FEFFFF", +"s% c #FDEFE8", +"t% c #F0905E", +"u% c #EE854E", +"v% c #EB7536", +"w% c #E8651F", +"x% c #EF671F", +"y% c #B34C14", +"z% c #ECA88A", +"A% c #FFAF8B", +"B% c #F78D5D", +"C% c #F78957", +"D% c #F78A59", +"E% c #F78B5A", +"F% c #FC8C5C", +"G% c #D67D56", +"H% c #FAC3AA", +"I% c #F6844F", +"J% c #FA8652", +"K% c #F88049", +"L% c #F97C43", +"M% c #C06B43", +"N% c #BFC2C3", +"O% c #F9C6AE", +"P% c #F1763B", +"Q% c #F37A3E", +"R% c #F77535", +"S% c #CA622E", +"T% c #AEAAA8", +"U% c #FAD6C3", +"V% c #E9621B", +"W% c #E9611A", +"X% c #E8641D", +"Y% c #E86520", +"Z% c #EE661D", +"`% c #B24B14", +" & c #EBA587", +".& c #FF9B6E", +"+& c #F78A58", +"@& c #D47B54", +"#& c #FAC2A9", +"$& c #F6824D", +"%& c #F5834D", +"&& c #F88149", +"*& c #A8745B", +"=& c #DDE2E3", +"-& c #F17539", +";& c #F0783C", +">& c #F27537", +",& c #B56943", +"'& c #CBCED1", +")& c #F5B593", +"!& c #E9641F", +"~& c #E96824", +"{& c #E86620", +"]& c #E8641E", +"^& c #EE661B", +"/& c #B24B13", +"(& c #EB9A76", +"_& c #FD8B58", +":& c #FA8955", +"<& c #D47A51", +"[& c #FAC1A8", +"}& c #F5804A", +"|& c #F07C46", +"1& c #9E8274", +"2& c #F3F6F8", +"3& c #FEF9F6", +"4& c #F38E5D", +"5& c #F07438", +"6& c #EE7539", +"7& c #F07232", +"8& c #A17159", +"9& c #E6EAEC", +"0& c #F09363", +"a& c #E9641E", +"b& c #E96721", +"c& c #E7631C", +"d& c #EE651A", +"e& c #B14B11", +"f& c #FD8650", +"g& c #F68450", +"h& c #F68551", +"i& c #FA8753", +"j& c #D2784F", +"k& c #BCBEBF", +"l& c #FAC4AB", +"m& c #F47E47", +"n& c #F6814A", +"o& c #DC7443", +"p& c #A89C96", +"q& c #FCE7DD", +"r& c #EF7537", +"s& c #EF7436", +"t& c #E66C2F", +"u& c #9F877A", +"v& c #F8FBFC", +"w& c #FDF3ED", +"x& c #ED7B40", +"y& c #E7621A", +"z& c #ED6418", +"A& c #B14910", +"B& c #E27844", +"C& c #FB864E", +"D& c #F4834D", +"E& c #F78450", +"F& c #E87F4F", +"G& c #DE9A7B", +"H& c #F9B698", +"I& c #F8B697", +"J& c #F8B696", +"K& c #F59B70", +"L& c #C76F45", +"M& c #B9BABB", +"N& c #FACEB8", +"O& c #F17333", +"P& c #D06630", +"Q& c #ACA4A0", +"R& c #FADECE", +"S& c #E7621B", +"T& c #E76118", +"U& c #ED6317", +"V& c #B2490F", +"W& c #E27644", +"X& c #FB844C", +"Y& c #F4824D", +"Z& c #F6834C", +"`& c #F37A41", +" * c #F27941", +".* c #F27940", +"+* c #F37C44", +"@* c #F37E45", +"#* c #F67C42", +"$* c #AE6E50", +"%* c #D5D9DB", +"&* c #F5AC88", +"** c #ED6F2F", +"=* c #F1702F", +"-* c #BC6538", +";* c #C1C4C6", +">* c #F6BFA2", +",* c #E86119", +"'* c #E7631B", +")* c #E76219", +"!* c #E66016", +"~* c #ED6215", +"{* c #B1480E", +"]* c #E27541", +"^* c #FB8248", +"/* c #F27B42", +"(* c #F0773B", +"_* c #9A7A69", +":* c #EFF2F4", +"<* c #FFFDFC", +"[* c #EE6E2D", +"}* c #EF6D2B", +"|* c #A56B4D", +"1* c #DEE2E4", +"2* c #F09B6D", +"3* c #E76018", +"4* c #E8631C", +"5* c #E66017", +"6* c #E65F15", +"7* c #EC6114", +"8* c #B1470E", +"9* c #E1733C", +"0* c #FA8045", +"a* c #F27D44", +"b* c #F27E45", +"c* c #F67E42", +"d* c #F5793C", +"e* c #F57A3E", +"f* c #F67A3E", +"g* c #FB793A", +"h* c #C46435", +"i* c #A6A3A1", +"j* c #FCE8DF", +"k* c #EE773B", +"l* c #F26F2C", +"m* c #F36C28", +"n* c #EC6620", +"o* c #9A7B6A", +"p* c #F3F6F9", +"q* c #FDF6F2", +"r* c #EE793B", +"s* c #EC5E10", +"t* c #E86219", +"u* c #E66118", +"v* c #E65F16", +"w* c #E55E14", +"x* c #EC6012", +"y* c #B1460D", +"z* c #E17039", +"A* c #F97D41", +"B* c #F17A40", +"C* c #F17B41", +"D* c #F17B43", +"E* c #F17C44", +"F* c #F47B41", +"G* c #C77045", +"H* c #CC7E57", +"I* c #DB7543", +"J* c #D56E3B", +"K* c #BE6A3F", +"L* c #968278", +"M* c #E7EAEB", +"N* c #F6B492", +"O* c #ED6927", +"P* c #D66930", +"Q* c #C76A3B", +"R* c #BA663A", +"S* c #AAA09A", +"T* c #FCEDE5", +"U* c #D77D4C", +"V* c #C56530", +"W* c #DF621F", +"X* c #E75F15", +"Y* c #E65E14", +"Z* c #E55D12", +"`* c #EC5F11", +" = c #B0460B", +".= c #DF6D36", +"+= c #F77A3D", +"@= c #997868", +"#= c #D7DEE3", +"$= c #D8D1CE", +"%= c #C8C1BD", +"&= c #C7CACC", +"*= c #EEF3F5", +"== c #FBDED0", +"-= c #ED7437", +";= c #EE6A25", +">= c #976D57", +",= c #C3CDD2", +"'= c #D6DCDF", +")= c #EFF0F1", +"!= c #E5ECEF", +"~= c #D3D1D0", +"{= c #E17133", +"]= c #E65C10", +"^= c #E55C11", +"/= c #EB5E0F", +"(= c #B0460A", +"_= c #DE6C32", +":= c #F57839", +"<= c #EF763A", +"[= c #F1773A", +"}= c #DA6C35", +"|= c #A29995", +"1= c #F9D1BD", +"2= c #ED7C41", +"3= c #EC6824", +"4= c #DE6425", +"5= c #9D8E86", +"6= c #FFEBDF", +"7= c #E8631A", +"8= c #E55D11", +"9= c #E45B0F", +"0= c #EB5E0E", +"a= c #B04509", +"b= c #DE692F", +"c= c #F57535", +"d= c #EE7334", +"e= c #EE7538", +"f= c #EE7438", +"g= c #F07435", +"h= c #DC6D34", +"i= c #CD967A", +"j= c #F9D7C5", +"k= c #F9D8C6", +"l= c #F8D0BC", +"m= c #F6B99A", +"n= c #EA6622", +"o= c #EB6A27", +"p= c #DF6525", +"q= c #D17D50", +"r= c #F1A075", +"s= c #F09F73", +"t= c #F09E72", +"u= c #F09D70", +"v= c #EF9C70", +"w= c #EF9C6E", +"x= c #EF9B6E", +"y= c #EC8750", +"z= c #E55B0E", +"A= c #E45C0F", +"B= c #E45A0E", +"C= c #EB5D0D", +"D= c #B04609", +"E= c #DC672A", +"F= c #F47331", +"G= c #EF7131", +"H= c #F16E2B", +"I= c #EC6825", +"J= c #EB6825", +"K= c #EB6723", +"L= c #EA641F", +"M= c #EA631E", +"N= c #EA6825", +"O= c #EA6925", +"P= c #EA6723", +"Q= c #ED631A", +"R= c #E75C12", +"S= c #E65B10", +"T= c #E65A0E", +"U= c #E5580C", +"V= c #E5570A", +"W= c #E55608", +"X= c #E45506", +"Y= c #E45608", +"Z= c #E55B10", +"`= c #E45A0D", +" - c #DB6628", +".- c #F3702D", +"+- c #EC6F2E", +"@- c #ED702F", +"#- c #EB6C2B", +"$- c #EB6B28", +"%- c #EA6A27", +"&- c #EA6926", +"*- c #EA6924", +"=- c #E96723", +"-- c #DB6325", +";- c #EC6D2B", +">- c #EC6D2C", +",- c #EC6C2B", +"'- c #EC6C2A", +")- c #EB6C29", +"!- c #EA6824", +"~- c #E96620", +"{- c #E8621B", +"]- c #E65E13", +"^- c #E55C10", +"/- c #E45A0C", +"(- c #AF4509", +"_- c #DB6120", +":- c #FE7228", +"<- c #F76F27", +"[- c #F76F28", +"}- c #F77029", +"|- c #F7712A", +"1- c #F8712A", +"2- c #F87029", +"3- c #F66E26", +"4- c #F66E25", +"5- c #F66D24", +"6- c #F66B22", +"7- c #F56A21", +"8- c #F56A20", +"9- c #F5691E", +"0- c #F4681D", +"a- c #F4671B", +"b- c #F36619", +"c- c #F36518", +"d- c #F26416", +"e- c #F26315", +"f- c #F26214", +"g- c #F26212", +"h- c #F16111", +"i- c #F1600F", +"j- c #F1600E", +"k- c #F15F0D", +"l- c #F15F0E", +"m- c #F8620E", +"n- c #B54809", +"o- c #BB531A", +"p- c #A94A18", +"q- c #A64919", +"r- c #A54A19", +"s- c #A54A1A", +"t- c #A54919", +"u- c #A54918", +"v- c #A54816", +"w- c #A44815", +"x- c #A44615", +"y- c #A44614", +"z- c #A44512", +"A- c #A44511", +"B- c #A44411", +"C- c #A24410", +"D- c #A2420E", +"E- c #A2420D", +"F- c #A2410C", +"G- c #A2410A", +"H- c #A1400A", +"I- c #A24009", +"J- c #A24008", +"K- c #A64109", +"L- c #833308", +" ", +" ", +" ", +" . + @ # $ % & * = - ; - > , , ' ) % ! ~ { ] ^ / ( _ : < [ } | 1 2 3 4 5 6 7 8 9 0 a ", +" b c d e f g h i j k l k k m j n o p q r d s t u v w x y z A B C D E F G H I J K L M ", +" N O P Q R S T U V W X Y W Z ` ...+.R @.#.$.%.&.*.=.-.;.>.,.'.).!.~.{.].^./.(._.:.<. ", +" [.}.Q R +.T V X |.1.2.2.2.1.Y Z ` ..+.3.4.5.6.7.8.9.0.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o. ", +" $ p.q.+.T r.Y 2.s.t.u.u.u.s.v.w.Z .x.y.z.#.$.%.A.B.C.D.E.F.G.e.H.I.J.K.L.M.N.O.P.Q. ", +" R.S.T.U.U X 1.s.u.V.W.W.X.V.t.s.Y.Z .+.3.Z.`. +.+*.=.-.;.F.++@+#+$+%+&+*+=+-+;+>+,+ ", +" % '+y.T )+!+s.~+{+]+^+]+]+{+/+u.(+_+:+<+[+}+|+1+2+3+4+-.5+>.,.'.).6+7+8+9+0+-+a+b+,+ ", +" & c+d+U e+f+g+h+i+j+j+j+j+k+i+l+m+n+o+p+q+r+s+t+u+v+4+0.5+w+x+'.).6+y+8+9+z+A+a+b+B+ ", +" & c+S V C+D+E+E+E+F+F+F+F+F+E+E+G+G+G+G+H+H+H+I+J+K+4+0.L+M+x+'.).6+~.8+9+z+A+a+N+B+ ", +" & c+S V C+O+P+P+P+P+P+P+P+P+P+P+P+P+P+P+P+P+P+P+Q+9.4+0.L+M+x+'.).6+~.8+9+z+A+a+N+B+ ", +" & '+y.:+R+S+P+P+P+P+P+P+P+P+P+P+P+P+P+P+P+P+P+P+T+9.4+0.5+U+x+V+).6+y+8+9+z+-+a+b+W+ ", +" % '+y.X+- Y+Z+Z+`+`+`+ @.@P+P+P+P++@@@@@@@#@Z+Z+$@%@3+=.-.&@F.*@@[email protected]@].z+-+;+b+,+ ", +" R.<+T.S U X r.Y 2.;@~+>@,@P+P+P+P+'@)@x.@.!@~@{@]@^@/@(@_@:@<@[@}@|@1@2@3@4@5@6@b+,+ ", +" $ p.Q y.7@U W Y 1.;@/+8@9@P+P+P+P+0@a@b@c@d@e@f@g@h@i@j@k@l@m@n@o@p@q@r@s@t@u@v@w@x@ ", +" [.y@[email protected]@T U W Y 1.B@C@D@P+P+P+P+E@F@G@H@I@J@K@L@M@N@O@P@Q@R@S@T@U@V@W@X@Y@Z@`@ #.# ", +" +#O @###T.y.x.T r.V !+$#%#P+P+P+P+&#*#=#-#e@J@K@;#>#,#'#j@)#!#~#{#]#^#/#(#_#:#<#[#}# ", +" |#1#2#P Q q.y.+.x.Z )+3#4#P+P+P+P+&#5#6#7#I@8#9#M@0#a#b#c#d#e#f#g#h#q@i#j#k#l#<#m#n# ", +" o#p#q#r#@#z@Q y. .q#s#t#u#P+P+P+P+v#w#x#y#J@9#;#>#,#z#j@Q@R@~#T@A#V@B#C#D#E#F#G#H#n# ", +" I#J#K#q#$.r###q.L#M#N#O#4#P+P+P+P+P#8#y#J@K@Q#M@N@R#P@c#d#e#S#{#T#^#/#U#V#:#`@W#X#Y# ", +" Z#`# $K#q#`..$+$@$#$$$%$u#P+P+P+P+&$9#J@K@L@M@*$a#'#j@)#=$-$T@o@;$q@>$X@,$l#<#'$X#)$ ", +" !$~${$]$^$/$($*#=#_$:$<$u#P+P+P+P+[$}$K@|$1$2$3$4$5$6$7$8$~#9$0$a$b$c$d$e$f$g$h$i$j$ ", +" k$l$m${$n$o$p$-#G@-#q$r$u#P+P+P+P+s$*$f@t$u$v$w$x$y$z$A$B$C$D$E$F$G$H$I$J$K$L$M$N$O$ ", +" P$Q$-.R$S$T$y#y#e@e@U$V$u#P+P+P+P+W$X$Y$Z$`$ %.%.%.%.%+%@%#%$%%%&%*%*%+%=%-%;%>%,%'% ", +" )%!%~%{%}$K@]%J@J@J@^%/%(%P+P+P+P+_%i@:%<%[%P+P+P+P+P+}%|%1%2%P+P+P+P+P+P+3%4%5%6%7% ", +" 8%9%0%a%;#Q#b%c%9#9#d%e%u#P+P+P+P+f%j@g%h%i%j%k%l%P+P+m%U@n%o%p%q%r%P+s%t%u%v%w%x%y% ", +" z%A%B%C%D%E%M@M@M@M@F%G%u#P+P+P+P+H%I%P@J%K%L%M%N%P+P+O%P%Q%R%S%T%P+P+U%V%W%X%Y%Z%`% ", +" &.&j@a#a#,#,#0#N@+&:%@&(%P+P+P+P+#&$&c#Q@%&&&*&=&P+P+I.-&;&>&,&'&P+P+)&!&~&{&]&^&/& ", +" (&_&j@P@b#'#z#z#O@a#:&<&(%P+P+P+P+[&}&d#R@e#|&1&2&P+3&4&5&6&7&8&9&P+P+0&a&b&w%c&d&e& ", +" o%f&Q@g&h&j@P@P@P@P@i&j&k&P+P+P+P+l&m&e#-$n&o&p&r%P+q&s@r&s&t&u&v&P+w&x&a&Y%X%y&z&A& ", +" B&C&R@D&d#)#)#Q@Q@Q@E&F&G&H&I&J&J&K&T@~#T@C$L&M&P+P+N&Y@X@O&P&Q&P+P+R&~&w%]&S&T&U&V& ", +" W&X&~#-$-$R@R@Y&R@R@R@Z&C$p@`& *.*+*f#{#@*#*$*%*P+P+&***_#=*-*;*P+P+>*,*w%'*)*!*~*{* ", +" ]*^*T@f#f#S#~#~#~#~#~#~#~#~#f#T@n@g#A#T#/*(*_*:*P+<*_.[*:#}*|*1*P+P+2*3*4*)*5*6*7*8* ", +" 9*0*a*b*g#g#{#n@T@T@T@T@{#g#g#A#c*d*e*f*g*h*i*P+P+j*k*l*m*n*o*p*P+q*r*s*t*u*v*w*x*y* ", +" z*A*B*C*;$D*]#E*a*T#T#T#h#]#;$F*G*H*I*J*K*L*M*P+P+N*O*P*Q*R*S*r%P+T*U*V*W*X*Y*Z*`* = ", +" .=+=/#B#q@r@r@B*B*B*B*^#^#r@q@-&@=#=$=%=&=*=P+P+==-=;=>=,='=)=P+P+P+!=~={=]=Z*^=/=(= ", +" _=:=U#C#<=(*(*/#/#/#/#(*(*i#[=}=|=P+P+P+P+P+P+1=2=3=4=5=P+P+P+P+P+P+P+6=7=8=^=9=0=a= ", +" b=c=d=D#X@j#j#j#e=e=f=j#j#X@g=h=i=1=j=k=l=m=;+W#n=o=p=q=r=s=t=u=v=w=x=y=z=^=A=B=C=D= ", +" E=F=:#E#Y@k#_#_#V#V#V#_#_#k#Y@G=H=I=J=K=n=L=M=N=O=~&P=Q=R=S=T=U=V=W=X=Y=^=Z=B=`=C=D= ", +" -.-`@`@+-l#l#@-:#:#:#@-****+-`@`@#-G#$-%-%-&-*-=-b&{&]&c&y&T&5*6*Y*Z*^=9=`=`=`=C=D= ", +" --m#W#G#G#;-;-;->->->->-;-,-'-)-W#$-o=h$O=!-P=b&~-w%X%{-)*T&!*6*]-Z*^-9=`=/-/-`=C=(- ", +" _-:-<-[-}-}-}-|-|-1-1-|-2-}-}-[-<-3-4-5-5-6-7-8-9-0-a-b-c-d-e-f-g-h-i-j-k-k-l-l-m-n- ", +" o-p-q-q-r-r-r-s-s-s-s-r-t-t-q-u-u-v-v-w-x-y-y-z-A-B-C-D-E-E-F-G-H-I-J-I-I-I-I-K-L- ", +" ", +" ", +" "}; diff --git a/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_64.bmp b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_64.bmp new file mode 100644 index 00000000..3c3f7216 Binary files /dev/null and b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_64.bmp differ diff --git a/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_64.xpm b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_64.xpm new file mode 100644 index 00000000..8cd53c78 --- /dev/null +++ b/org.eclipselabs.tapiji.translator.rcp/icons/TapiJI_64.xpm @@ -0,0 +1,1393 @@ +/* XPM */ +static char * TapiJI_64_xpm[] = { +"64 64 1326 2", +" c None", +". c #F0BBA5", +"+ c #F7C0A6", +"@ c #F1B8A0", +"# c #F0B8A1", +"$ c #EFB8A1", +"% c #EFB9A3", +"& c #EFB9A5", +"* c #F0BAA6", +"= c #F0BCA6", +"- c #F0BDA7", +"; c #F0BDA8", +"> c #F0BEA9", +", c #EFBDA9", +"' c #EFBDAA", +") c #EFBDA7", +"! c #EFBCA7", +"~ c #EFBBA5", +"{ c #EEBAA4", +"] c #EFBAA5", +"^ c #EFB9A2", +"/ c #EDB7A0", +"( c #ECB69F", +"_ c #ECB49C", +": c #ECB39B", +"< c #EBB197", +"[ c #EBB196", +"} c #ECAF94", +"| c #ECAE92", +"1 c #ECAC8F", +"2 c #EBAA8D", +"3 c #EAA98C", +"4 c #EAA788", +"5 c #EAA586", +"6 c #EAA484", +"7 c #E8A381", +"8 c #E8A07E", +"9 c #E79E7B", +"0 c #E69C78", +"a c #E79B75", +"b c #E79871", +"c c #E5966E", +"d c #E5936B", +"e c #E59067", +"f c #E28D62", +"g c #E38B5F", +"h c #E2895B", +"i c #E18657", +"j c #E78856", +"k c #F2BAA2", +"l c #FFCDB1", +"m c #FFC9AD", +"n c #FFCAAF", +"o c #FFCBB1", +"p c #FFCCB2", +"q c #FFCEB4", +"r c #FFCEB6", +"s c #FFCFB6", +"t c #FFD0B8", +"u c #FFD0B9", +"v c #FFD1B9", +"w c #FFD1BA", +"x c #FFD2BA", +"y c #FFD1B8", +"z c #FFCFB7", +"A c #FFCDB3", +"B c #FFCCB1", +"C c #FFCBB0", +"D c #FFCAAE", +"E c #FFC8AC", +"F c #FFC7AA", +"G c #FFC6A8", +"H c #FFC4A6", +"I c #FFC3A4", +"J c #FFC1A2", +"K c #FFBF9F", +"L c #FFBE9C", +"M c #FFBC9A", +"N c #FFBB97", +"O c #FFB894", +"P c #FFB792", +"Q c #FFB590", +"R c #FFB38C", +"S c #FFB18A", +"T c #FFAE86", +"U c #FFAD82", +"V c #FFAA7F", +"W c #FFA77B", +"X c #FFA577", +"Y c #FFA273", +"Z c #FF9F6F", +"` c #FF9D6B", +" . c #FF9A67", +".. c #FF9763", +"+. c #FE945E", +"@. c #FF965D", +"#. c #A76039", +"$. c #EFB8A2", +"%. c #FFC4AA", +"&. c #FEC0A7", +"*. c #FEC1A9", +"=. c #FEC2AA", +"-. c #FEC4AC", +";. c #FEC5AE", +">. c #FEC5AF", +",. c #FEC6B0", +"'. c #FEC7B1", +"). c #FFC8B2", +"!. c #FFC8B3", +"~. c #FFC9B3", +"{. c #FEC9B3", +"]. c #FFC9B4", +"^. c #FEC8B3", +"/. c #FEC8B2", +"(. c #FEC8B1", +"_. c #FDC4AC", +":. c #FDC3AB", +"<. c #FDC2A9", +"[. c #FDC1A7", +"}. c #FDC0A5", +"|. c #FCBEA4", +"1. c #FBBDA1", +"2. c #FBBB9F", +"3. c #FABA9D", +"4. c #FAB89B", +"5. c #FAB799", +"6. c #FAB596", +"7. c #FAB494", +"8. c #F9B292", +"9. c #F9B08F", +"0. c #F9AE8C", +"a. c #F9AC89", +"b. c #F8AB87", +"c. c #F7A984", +"d. c #F6A781", +"e. c #F6A57E", +"f. c #F5A27A", +"g. c #F5A076", +"h. c #F49D73", +"i. c #F39A6F", +"j. c #F3986B", +"k. c #F39567", +"l. c #F19363", +"m. c #F1905F", +"n. c #F18D5B", +"o. c #F68F5A", +"p. c #955635", +"q. c #FFC5AB", +"r. c #FEC1A8", +"s. c #FEC3AC", +"t. c #FEC5AD", +"u. c #FEC6AF", +"v. c #FFC7B0", +"w. c #FFC7B1", +"x. c #FFCAB5", +"y. c #FEC9B4", +"z. c #FEC7B2", +"A. c #FEC7B0", +"B. c #FDC3AA", +"C. c #FDC1A9", +"D. c #FDBFA5", +"E. c #FBBEA3", +"F. c #FBBCA1", +"G. c #FAB99C", +"H. c #FAB79A", +"I. c #FAB698", +"J. c #FAB495", +"K. c #FAB393", +"L. c #F9B190", +"M. c #F9AF8D", +"N. c #F9AD8A", +"O. c #F8AB88", +"P. c #F7A985", +"Q. c #F7A782", +"R. c #F6A57F", +"S. c #F5A37B", +"T. c #F5A077", +"U. c #F59E74", +"V. c #F39B70", +"W. c #F3996C", +"X. c #F39668", +"Y. c #F29364", +"Z. c #F19160", +"`. c #F18E5C", +" + c #F7905B", +".+ c #915333", +"++ c #FFC6AC", +"@+ c #FEC2A9", +"#+ c #FEC4AD", +"$+ c #FEC6AE", +"%+ c #FFC7B2", +"&+ c #FFCAB6", +"*+ c #FFCBB6", +"=+ c #FFCBB7", +"-+ c #FECAB5", +";+ c #FDC4AD", +">+ c #FDC4AB", +",+ c #FDC2AA", +"'+ c #FDC1A8", +")+ c #FDC0A6", +"!+ c #FCBFA4", +"~+ c #F9B08E", +"{+ c #F9AE8B", +"]+ c #F8AC88", +"^+ c #F8AA85", +"/+ c #F7A883", +"(+ c #F6A680", +"_+ c #F5A47C", +":+ c #F5A178", +"<+ c #F59E75", +"[+ c #F39C71", +"}+ c #F3996D", +"|+ c #F39669", +"1+ c #F29465", +"2+ c #F19161", +"3+ c #F18E5D", +"4+ c #F7905C", +"5+ c #915334", +"6+ c #EFB9A4", +"7+ c #FFC7AE", +"8+ c #FEC3AA", +"9+ c #FFCCB8", +"0+ c #FECBB5", +"a+ c #FECAB4", +"b+ c #FBBCA0", +"c+ c #FABB9E", +"d+ c #FAB597", +"e+ c #F9B291", +"f+ c #F8AC89", +"g+ c #F8AB86", +"h+ c #F6A47D", +"i+ c #F5A179", +"j+ c #F59F75", +"k+ c #F49C71", +"l+ c #F39A6D", +"m+ c #F3976A", +"n+ c #F19261", +"o+ c #F18F5D", +"p+ c #F7915C", +"q+ c #FFC8AE", +"r+ c #FEC3AB", +"s+ c #FFCCB9", +"t+ c #FFCDBA", +"u+ c #FFCEBA", +"v+ c #FFCDB9", +"w+ c #FDC5AE", +"x+ c #FDC3AC", +"y+ c #FCBEA3", +"z+ c #FABB9F", +"A+ c #F9B18F", +"B+ c #F59F76", +"C+ c #F49D72", +"D+ c #F39A6E", +"E+ c #F29566", +"F+ c #F19262", +"G+ c #F18F5E", +"H+ c #F7915D", +"I+ c #915434", +"J+ c #FFC8AF", +"K+ c #FFC5AE", +"L+ c #FFCEBB", +"M+ c #FBBDA2", +"N+ c #F59D73", +"O+ c #F39B6F", +"P+ c #F8915D", +"Q+ c #EFBBA7", +"R+ c #FFC9B0", +"S+ c #FFC6AF", +"T+ c #FFCBB5", +"U+ c #FFCEB9", +"V+ c #FFCFBB", +"W+ c #FFD1BD", +"X+ c #FFD2BE", +"Y+ c #FFD2BF", +"Z+ c #FFD3BF", +"`+ c #FFD0BC", +" @ c #FFCDB8", +".@ c #FFCDB6", +"+@ c #FFCCB5", +"@@ c #FFCAB3", +"#@ c #FFC9B1", +"$@ c #FFC6AD", +"%@ c #FFC3A9", +"&@ c #FFC2A6", +"*@ c #F9AF8E", +"=@ c #F8925E", +"-@ c #915435", +";@ c #F8C5B0", +">@ c #E8B9A7", +",@ c #E7B9A7", +"'@ c #E7BAA9", +")@ c #E7BBAA", +"!@ c #E7BCAB", +"~@ c #E7BCAC", +"{@ c #E7BDAC", +"]@ c #E7BCAA", +"^@ c #E7BBA9", +"/@ c #E7BAA8", +"(@ c #E6B8A6", +"_@ c #E6B7A4", +":@ c #E6B7A3", +"<@ c #E6B5A1", +"[@ c #E6B49F", +"}@ c #E5B39D", +"|@ c #E5B29C", +"1@ c #E5B09A", +"2@ c #E5AE98", +"3@ c #E4AD96", +"4@ c #F3B89E", +"5@ c #FCBCA1", +"6@ c #FABA9E", +"7@ c #FAB99B", +"8@ c #FAB394", +"9@ c #F7AA85", +"0@ c #F6A882", +"a@ c #F29363", +"b@ c #FFCCB6", +"c@ c #C7A294", +"d@ c #908C8A", +"e@ c #B7B2AF", +"f@ c #B5B0AD", +"g@ c #B5B0AE", +"h@ c #B5AFAD", +"i@ c #B5AFAC", +"j@ c #B5AEAC", +"k@ c #B5AEAB", +"l@ c #B3AEAB", +"m@ c #E3B8A5", +"n@ c #FDBDA1", +"o@ c #F6A67F", +"p@ c #F3986C", +"q@ c #C09F91", +"r@ c #B4B8BA", +"s@ c #FEFFFF", +"t@ c #FDFFFF", +"u@ c #FBD3C1", +"v@ c #FBBB9E", +"w@ c #F5A37C", +"x@ c #F5A078", +"y@ c #F1915F", +"z@ c #C2A092", +"A@ c #B9BBBC", +"B@ c #FFFFFF", +"C@ c #FCD3C1", +"D@ c #FBBA9E", +"E@ c #F19364", +"F@ c #B8BABB", +"G@ c #FBBA9D", +"H@ c #F59E73", +"I@ c #F39667", +"J@ c #F7925E", +"K@ c #FFC8B0", +"L@ c #FFCBB4", +"M@ c #BE9C8F", +"N@ c #B4B9BB", +"O@ c #FCD4C2", +"P@ c #F9AD8B", +"Q@ c #F8A985", +"R@ c #F6A782", +"S@ c #DAB09E", +"T@ c #D3C0B8", +"U@ c #FFEBE3", +"V@ c #FEEAE2", +"W@ c #FEEAE3", +"X@ c #FEEBE3", +"Y@ c #FEEBE4", +"Z@ c #FAEBE7", +"`@ c #F8F8F8", +" # c #FFEFE9", +".# c #FEE8DF", +"+# c #FDE8DE", +"@# c #FDE7DE", +"## c #FDE7DD", +"$# c #FEE7DD", +"%# c #FEE7DE", +"&# c #FDE8DF", +"*# c #FBCDB8", +"=# c #FABCA1", +"-# c #F9B393", +";# c #F8AD8B", +"># c #F7AB88", +",# c #F6A985", +"'# c #F5A47D", +")# c #F8925D", +"!# c #FFC9B5", +"~# c #D7B1A3", +"{# c #BFC0C1", +"]# c #FED5C4", +"^# c #FDC5AD", +"/# c #FCB598", +"(# c #FBB08F", +"_# c #FAAB89", +":# c #FAA682", +"<# c #F9A079", +"[# c #F89C73", +"}# c #F7996E", +"|# c #F79467", +"1# c #F79264", +"2# c #F69365", +"3# c #F69465", +"4# c #F69366", +"5# c #F5976A", +"6# c #F5996D", +"7# c #F59C71", +"8# c #F29668", +"9# c #F19362", +"0# c #FFCCB7", +"a# c #CBA798", +"b# c #ACADAD", +"c# c #FED9C9", +"d# c #FCB79A", +"e# c #FCAC8B", +"f# c #FBA17B", +"g# c #F99970", +"h# c #F99367", +"i# c #F98E5E", +"j# c #F98B5B", +"k# c #F98A5A", +"l# c #F78857", +"m# c #F78755", +"n# c #F68652", +"o# c #F68450", +"p# c #F6834E", +"q# c #F5824C", +"r# c #F5804A", +"s# c #F47F48", +"t# c #F37E47", +"u# c #F37D45", +"v# c #F37C42", +"w# c #F17B42", +"x# c #F17D44", +"y# c #F17F47", +"z# c #F1824C", +"A# c #F18954", +"B# c #F28D5C", +"C# c #F29261", +"D# c #CDA899", +"E# c #AFB0B0", +"F# c #FDC6AF", +"G# c #FCA37F", +"H# c #FB9A72", +"I# c #FA9368", +"J# c #FA9064", +"K# c #F98F62", +"L# c #F98F61", +"M# c #F98F60", +"N# c #F98E5F", +"O# c #F98D5E", +"P# c #F88C5C", +"Q# c #F78A5A", +"R# c #F68958", +"S# c #F68856", +"T# c #F68754", +"U# c #F68552", +"V# c #F58450", +"W# c #F5834D", +"X# c #F4824B", +"Y# c #F3804A", +"Z# c #F37F48", +"`# c #F1783E", +" $ c #F07639", +".$ c #EF7336", +"+$ c #EE7233", +"@$ c #EE7132", +"#$ c #EE7536", +"$$ c #EE7A3F", +"%$ c #EE824A", +"&$ c #F68D55", +"*$ c #EDB8A2", +"=$ c #FFC6AB", +"-$ c #FEC4AE", +";$ c #FFCEB8", +">$ c #CDA698", +",$ c #FCB091", +"'$ c #FA9366", +")$ c #F99165", +"!$ c #F99063", +"~$ c #F88D5D", +"{$ c #F88B5B", +"]$ c #F68857", +"^$ c #F68855", +"/$ c #F68653", +"($ c #F58551", +"_$ c #F5834F", +":$ c #F3814B", +"<$ c #F38049", +"[$ c #F37F47", +"}$ c #F1793F", +"|$ c #F0773C", +"1$ c #EF7539", +"2$ c #EE7435", +"3$ c #ED6F2E", +"4$ c #EC6C2A", +"5$ c #EB6B28", +"6$ c #F2712C", +"7$ c #8D441D", +"8$ c #EDB6A1", +"9$ c #FFC5AA", +"0$ c #FEC1A7", +"a$ c #CCA798", +"b$ c #FCB293", +"c$ c #FA9266", +"d$ c #FA9469", +"e$ c #FA9367", +"f$ c #F99265", +"g$ c #F99164", +"h$ c #F99062", +"i$ c #F98E60", +"j$ c #F78959", +"k$ c #F5834E", +"l$ c #F4824C", +"m$ c #F37F49", +"n$ c #F37E46", +"o$ c #F27C44", +"p$ c #F17B41", +"q$ c #F1793E", +"r$ c #EF773B", +"s$ c #EE7538", +"t$ c #EE7335", +"u$ c #ED6F2F", +"v$ c #EB6E2C", +"w$ c #EB6C29", +"x$ c #F16C27", +"y$ c #8D3E15", +"z$ c #EDB69F", +"A$ c #FFC4A9", +"B$ c #FEC0A6", +"C$ c #CCA493", +"D$ c #FCB191", +"E$ c #FA9265", +"F$ c #FA9468", +"G$ c #F98D5D", +"H$ c #F68957", +"I$ c #F37E45", +"J$ c #F27C43", +"K$ c #F17A40", +"L$ c #F0783D", +"M$ c #EF763A", +"N$ c #EE7537", +"O$ c #EE7334", +"P$ c #ED7131", +"Q$ c #EC6F2E", +"R$ c #EB6D2C", +"S$ c #EB6B29", +"T$ c #F16D27", +"U$ c #8D3F15", +"V$ c #FFC3A7", +"W$ c #FDBEA4", +"X$ c #FFB696", +"Y$ c #CB896E", +"Z$ c #AFB1B1", +"`$ c #FBB091", +" % c #FA9164", +".% c #F99061", +"+% c #F78A59", +"@% c #F68755", +"#% c #F68551", +"$% c #F5844F", +"%% c #F4824D", +"&% c #F37E48", +"*% c #F27D45", +"=% c #EF7639", +"-% c #EE7436", +";% c #ED7030", +">% c #EC6E2E", +",% c #EB6D2B", +"'% c #EDB59D", +")% c #FDBDA3", +"!% c #FEBCA1", +"~% c #FCA47F", +"{% c #FF996E", +"]% c #CB8163", +"^% c #AFB1B2", +"/% c #FBAF90", +"(% c #F98D5F", +"_% c #F88C5D", +":% c #F58451", +"<% c #F3804B", +"[% c #F0773B", +"}% c #EE7232", +"|% c #EC6E2D", +"1% c #EB6C2A", +"2% c #EA6B27", +"3% c #F16C26", +"4% c #ECB39C", +"5% c #FFC1A4", +"6% c #FDBCA1", +"7% c #FDBFA4", +"8% c #FDBFA6", +"9% c #FDAF90", +"0% c #FB9970", +"a% c #FB956B", +"b% c #CA8163", +"c% c #FBAF8E", +"d% c #F88B5C", +"e% c #F78B5A", +"f% c #F78958", +"g% c #F4814B", +"h% c #F1783D", +"i% c #EE7437", +"j% c #EE7131", +"k% c #EC6F2F", +"l% c #EA6A27", +"m% c #F16B26", +"n% c #FFBFA2", +"o% c #FCBB9F", +"p% c #FDBDA2", +"q% c #FEBEA3", +"r% c #FBA47F", +"s% c #FB9469", +"t% c #FB956A", +"u% c #FB966C", +"v% c #FF986C", +"w% c #CA8162", +"x% c #FBAE8D", +"y% c #F68654", +"z% c #F27D44", +"A% c #EE7234", +"B% c #EA6A26", +"C% c #F16B25", +"D% c #8D3E14", +"E% c #EAB298", +"F% c #FFBEA1", +"G% c #FCBCA0", +"H% c #FCBDA1", +"I% c #FDBEA3", +"J% c #FCB89B", +"K% c #FA9D75", +"L% c #FA956A", +"M% c #FF976A", +"N% c #C98060", +"O% c #FBAD8C", +"P% c #F98C5D", +"Q% c #F68451", +"R% c #F17C43", +"S% c #EA6925", +"T% c #F06A23", +"U% c #8C3E14", +"V% c #EAB096", +"W% c #FFBD9E", +"X% c #FBB89B", +"Y% c #FBB99D", +"Z% c #FCBA9E", +"`% c #FBB496", +" & c #FA986E", +".& c #FA9165", +"+& c #FF9668", +"@& c #C97F5F", +"#& c #FBAD8B", +"$& c #F98C5C", +"%& c #FF8D5B", +"&& c #FD8955", +"*& c #FB8753", +"=& c #FB8652", +"-& c #FB8550", +";& c #FB844F", +">& c #FB834D", +",& c #FA824B", +"'& c #FA8148", +")& c #F78048", +"!& c #F98046", +"~& c #F87B40", +"{& c #F5783C", +"]& c #F57739", +"^& c #F47536", +"/& c #F37333", +"(& c #F27131", +"_& c #F2702D", +":& c #F26D2A", +"<& c #F06C28", +"[& c #EF6A24", +"}& c #EE6923", +"|& c #E96824", +"1& c #F06A22", +"2& c #8D3C12", +"3& c #EAAD95", +"4& c #FFBB9C", +"5& c #FBB99C", +"6& c #FBBBA0", +"7& c #FBB192", +"8& c #F9956A", +"9& c #F99266", +"0& c #FA9267", +"a& c #FE9466", +"b& c #C97E5E", +"c& c #FBAC89", +"d& c #F68A5A", +"e& c #BD7656", +"f& c #BA7C60", +"g& c #BD7E62", +"h& c #BD7E61", +"i& c #BD7D60", +"j& c #BD7C60", +"k& c #BD7C5F", +"l& c #BC7B5D", +"m& c #BB7B5C", +"n& c #C67C5A", +"o& c #F27F4A", +"p& c #F67F47", +"q& c #C26E46", +"r& c #B47353", +"s& c #BA7655", +"t& c #BA7653", +"u& c #B97452", +"v& c #B87350", +"w& c #B9724F", +"x& c #B9714E", +"y& c #B8704C", +"z& c #B76F4B", +"A& c #B66F49", +"B& c #BE6E45", +"C& c #E66A29", +"D& c #EA6823", +"E& c #F06922", +"F& c #8C3C12", +"G& c #ECAE93", +"H& c #FFBA9A", +"I& c #FBB191", +"J& c #F99468", +"K& c #FE9364", +"L& c #C87D5C", +"M& c #FBAB88", +"N& c #F88959", +"O& c #FB8C5B", +"P& c #E07F54", +"Q& c #807975", +"R& c #CBD3D6", +"S& c #D5DBDD", +"T& c #D4DADC", +"U& c #D4DADD", +"V& c #D4DCE0", +"W& c #DBBBAD", +"X& c #F37C45", +"Y& c #EE7A42", +"Z& c #816C62", +"`& c #BFC8CD", +" * c #D6DCDF", +".* c #D5DBDE", +"+* c #D4DEE2", +"@* c #D7C0B5", +"#* c #E76825", +"$* c #E96722", +"%* c #F06820", +"&* c #EAAB90", +"** c #FFB898", +"=* c #F99469", +"-* c #FE9162", +";* c #C87C5B", +">* c #FAAA87", +",* c #F88857", +"'* c #FC8B59", +")* c #C77550", +"!* c #9D9F9F", +"~* c #FDBFA1", +"{* c #F67B40", +"]* c #D47040", +"^* c #8F8A87", +"/* c #FBC5A9", +"(* c #E9631D", +"_* c #E96621", +":* c #EAAA8E", +"<* c #FFB795", +"[* c #F9996E", +"}* c #F98E61", +"|* c #FE9060", +"1* c #C87B59", +"2* c #FAA985", +"3* c #F78754", +"4* c #F78A58", +"5* c #FA8A56", +"6* c #A36C54", +"7* c #B8C1C5", +"8* c #FFFEFE", +"9* c #F69E74", +"0* c #F77B3F", +"a* c #BF6B43", +"b* c #A5A2A1", +"c* c #FEF9F6", +"d* c #FFFCF8", +"e* c #FEF9F7", +"f* c #FEF7F4", +"g* c #FDF7F4", +"h* c #F0996B", +"i* c #E8631C", +"j* c #E86620", +"k* c #EF671F", +"l* c #8C3C10", +"m* c #E9A98B", +"n* c #FFB593", +"o* c #FAB293", +"p* c #F99F77", +"q* c #F88A59", +"r* c #FD8E5E", +"s* c #C87A58", +"t* c #F9A984", +"u* c #F68956", +"v* c #F78855", +"w* c #DC7F55", +"x* c #EB9974", +"y* c #F8A67F", +"z* c #F8A37C", +"A* c #EBA98B", +"B* c #E1E1E1", +"C* c #FEF2EC", +"D* c #F48B58", +"E* c #F27A41", +"F* c #E57742", +"G* c #E78353", +"H* c #F48C59", +"I* c #DA9572", +"J* c #DBDEDF", +"K* c #FCE9DF", +"L* c #EF8852", +"M* c #ED8249", +"N* c #EC8149", +"O* c #E96C2A", +"P* c #E96620", +"Q* c #E8651F", +"R* c #EF671E", +"S* c #EAA889", +"T* c #FFB492", +"U* c #F9A783", +"V* c #FD8D5C", +"W* c #C87957", +"X* c #F8A783", +"Y* c #FC8753", +"Z* c #F9814A", +"`* c #F57D45", +" = c #F97C43", +".= c #B26845", +"+= c #B3B6B8", +"@= c #FCDED0", +"#= c #F27B42", +"$= c #F47A3F", +"%= c #F37538", +"&= c #F3702F", +"*= c #9E6041", +"== c #BFC3C5", +"-= c #F8CBB4", +";= c #E9621A", +">= c #E9641E", +",= c #E9621B", +"'= c #E9651F", +")= c #E8641E", +"!= c #EE661C", +"~= c #8C3B0E", +"{= c #E9A788", +"]= c #FFB28E", +"^= c #F88A5A", +"/= c #F88B5A", +"(= c #FC8B5A", +"_= c #C77855", +":= c #F8A781", +"<= c #F6834F", +"[= c #F8824A", +"}= c #936A55", +"|= c #CDD1D3", +"1= c #F9C2A8", +"2= c #F1773B", +"3= c #ED7234", +"4= c #8B6B5B", +"5= c #DDE0E2", +"6= c #F4AA83", +"7= c #EA6620", +"8= c #E96724", +"9= c #E8641D", +"0= c #EE651B", +"a= c #FFA379", +"b= c #F68553", +"c= c #FB8A58", +"d= c #C77853", +"e= c #AFB2B3", +"f= c #F8A680", +"g= c #F6824D", +"h= c #F5824D", +"i= c #EB7B47", +"j= c #8B756B", +"k= c #E8EBEC", +"l= c #F6A27B", +"m= c #F17539", +"n= c #F17638", +"o= c #DA6B33", +"p= c #8D7F77", +"q= c #F2F4F6", +"r= c #FFFDFB", +"s= c #EF8B57", +"t= c #EA6824", +"u= c #E86520", +"v= c #E7631B", +"w= c #EE651A", +"x= c #8A3A0D", +"y= c #E7A180", +"z= c #FD915F", +"A= c #FB8955", +"B= c #C67752", +"C= c #F8A57E", +"D= c #F5814B", +"E= c #F7824B", +"F= c #D37245", +"G= c #928B89", +"H= c #F9FAFB", +"I= c #FEF6F3", +"J= c #F38C5B", +"K= c #F17639", +"L= c #F27536", +"M= c #C36535", +"N= c #9A9A9A", +"O= c #FEFEFF", +"P= c #FCECE4", +"Q= c #EC7638", +"R= c #E96723", +"S= c #E7641C", +"T= c #E7621A", +"U= c #ED6419", +"V= c #E79169", +"W= c #FD8852", +"X= c #C57551", +"Y= c #AEB3B5", +"Z= c #F7A57E", +"`= c #F47F49", +" - c #F88149", +".- c #BA6B47", +"+- c #A6A8AA", +"@- c #FCE4D8", +"#- c #F17B40", +"$- c #F0763A", +"%- c #A7623F", +"&- c #B6BBBD", +"*- c #F9D4C1", +"=- c #E96721", +"-- c #E7621B", +";- c #E76219", +">- c #ED6317", +",- c #8A3A0C", +"'- c #E37B4A", +")- c #FC864E", +"!- c #FB8651", +"~- c #C7754F", +"{- c #B0B0B0", +"]- c #FFFCFB", +"^- c #FEFCFA", +"/- c #FEFBFA", +"(- c #FEFCFB", +"_- c #F6A27A", +":- c #F77F46", +"<- c #9C684F", +"[- c #C5C9CB", +"}- c #F9CAB2", +"|- c #EF7234", +"1- c #F0702F", +"2- c #8E6651", +"3- c #D4D8DA", +"4- c #F4B491", +"5- c #E66118", +"6- c #ED6216", +"7- c #8C3A0C", +"8- c #DF7543", +"9- c #FB854D", +"0- c #F4834C", +"a- c #F6844F", +"b- c #EC814E", +"c- c #E88C61", +"d- c #F79B70", +"e- c #F69A6E", +"f- c #F6996E", +"g- c #F6996D", +"h- c #F38753", +"i- c #F47E47", +"j- c #EF7A41", +"k- c #8C6F61", +"l- c #E0E3E5", +"m- c #F5AA84", +"n- c #EE7235", +"o- c #EF7232", +"p- c #E06A2D", +"q- c #8A776C", +"r- c #ECEEF0", +"s- c #EF9261", +"t- c #E7631C", +"u- c #E76118", +"v- c #E66016", +"w- c #ED6215", +"x- c #DE7442", +"y- c #FB844C", +"z- c #F3814C", +"A- c #F7834C", +"B- c #F88048", +"C- c #F37C43", +"D- c #F47C43", +"E- c #F37B43", +"F- c #F37B42", +"G- c #F57E44", +"H- c #DA713E", +"I- c #8D827D", +"J- c #F5F6F7", +"K- c #FFFAF9", +"L- c #F28F5E", +"M- c #EE7031", +"N- c #F1712F", +"O- c #CA6430", +"P- c #94908E", +"Q- c #FBFCFC", +"R- c #FDF3ED", +"S- c #EC7A3D", +"T- c #E7631A", +"U- c #E76119", +"V- c #E66017", +"W- c #E65F15", +"X- c #ED6114", +"Y- c #8A380C", +"Z- c #DE7441", +"`- c #FB824A", +" ; c #F67C41", +".; c #BD693F", +"+; c #9EA0A0", +"@; c #FCEAE0", +"#; c #EF7B41", +"$; c #F06F2D", +"%; c #B06036", +"&; c #ABB0B2", +"*; c #FADDCD", +"=; c #E66117", +"-; c #E65F16", +";; c #E65E14", +">; c #EC6013", +",; c #8A380A", +"'; c #DE713E", +"); c #FA8147", +"!; c #F6793C", +"~; c #91624B", +"{; c #C4C8CA", +"]; c #F9D0BC", +"^; c #EE6E2E", +"/; c #ED6F30", +"(; c #F06D28", +"_; c #946147", +":; c #CBCFD2", +"<; c #F6BEA1", +"[; c #E85F17", +"}; c #E76017", +"|; c #E55E13", +"1; c #EC6012", +"2; c #8A370A", +"3; c #DC6F3B", +"4; c #F97F44", +"5; c #F37D44", +"6; c #F97D40", +"7; c #F57A3E", +"8; c #F37A3F", +"9; c #F47A3E", +"0; c #FB7A3B", +"a; c #CB6635", +"b; c #807A76", +"c; c #EFF1F2", +"d; c #F4A57C", +"e; c #ED6B2A", +"f; c #EF702F", +"g; c #F26F2B", +"h; c #F26C28", +"i; c #876D60", +"j; c #E5E8EA", +"k; c #F19665", +"l; c #EC5E12", +"m; c #ED6217", +"n; c #E86219", +"o; c #E55D12", +"p; c #EC5F11", +"q; c #8A3709", +"r; c #DC6E37", +"s; c #F97D41", +"t; c #F17A41", +"u; c #F17B43", +"v; c #E47640", +"w; c #B86C48", +"x; c #DA7644", +"y; c #E77137", +"z; c #E97035", +"A; c #E16D34", +"B; c #BE6438", +"C; c #7D675D", +"D; c #C7CACC", +"E; c #FCEBE2", +"F; c #EE793C", +"G; c #ED6D2C", +"H; c #E16A2E", +"I; c #CB632D", +"J; c #CF642B", +"K; c #B65A2A", +"L; c #908782", +"M; c #F8F9FA", +"N; c #FEFBF9", +"O; c #E58A5B", +"P; c #CB5A1E", +"Q; c #C95C21", +"R; c #E0601B", +"S; c #E76016", +"T; c #E55E14", +"U; c #E55C11", +"V; c #EB5F10", +"W; c #893709", +"X; c #DC6C36", +"Y; c #F77B3E", +"Z; c #F17A3F", +"`; c #F67A3E", +" > c #BF693F", +".> c #8A9094", +"+> c #D2CCC8", +"@> c #C0A99D", +"#> c #AF9588", +"$> c #A69389", +"%> c #A2A2A2", +"&> c #D3D8DA", +"*> c #F3A47B", +"=> c #EB6926", +"-> c #F06E2B", +";> c #9D5E3D", +">> c #969595", +",> c #BBB6B3", +"'> c #B6B2B1", +")> c #D6D6D6", +"!> c #E8E2E0", +"~> c #BCB8B6", +"{> c #B8ADA7", +"]> c #DC6D2F", +"^> c #E75E12", +"/> c #E55D13", +"(> c #E55D11", +"_> c #E55C10", +":> c #EB5E0F", +"<> c #8A3708", +"[> c #D96B33", +"}> c #F6793B", +"|> c #F0783E", +"1> c #F0783C", +"2> c #F4773A", +"3> c #A06447", +"4> c #C1C4C7", +"5> c #FBFFFF", +"6> c #F5FBFF", +"7> c #F7FCFF", +"8> c #F6BC9D", +"9> c #EB6C2B", +"0> c #EB6A26", +"a> c #886857", +"b> c #DEE4E8", +"c> c #FEEBDF", +"d> c #E86721", +"e> c #E45B0F", +"f> c #EB5D0E", +"g> c #8A3508", +"h> c #DB6930", +"i> c #F57737", +"j> c #EF7538", +"k> c #EF763B", +"l> c #EC7235", +"m> c #866C5F", +"n> c #DDE7ED", +"o> c #FDEEE6", +"p> c #F3A982", +"q> c #EB6A27", +"r> c #ED6C28", +"s> c #D46226", +"t> c #88817C", +"u> c #F3FCFF", +"v> c #F7CAB2", +"w> c #E5590C", +"x> c #E45B0E", +"y> c #EB5D0D", +"z> c #DB682D", +"A> c #F57635", +"B> c #EF7436", +"C> c #E56F33", +"D> c #B1795C", +"E> c #EDCEBF", +"F> c #FBE2D5", +"G> c #FBE6DB", +"H> c #FBE5DA", +"I> c #FADECF", +"J> c #F8CAB2", +"K> c #F3A47C", +"L> c #ED7A3E", +"M> c #EA651F", +"N> c #EC6A26", +"O> c #DA6426", +"P> c #C67950", +"Q> c #F0A57C", +"R> c #F1A57C", +"S> c #F0A47B", +"T> c #F0A379", +"U> c #F0A378", +"V> c #F0A278", +"W> c #EFA277", +"X> c #EFA176", +"Y> c #EA7E42", +"Z> c #E55B0F", +"`> c #E45A0E", +" , c #E45A0D", +"., c #D9662B", +"+, c #F57432", +"@, c #ED7031", +"#, c #F3712F", +"$, c #EE6D2B", +"%, c #EC7133", +"&, c #ED7538", +"*, c #EC7437", +"=, c #EC7335", +"-, c #EA6621", +";, c #EA641E", +">, c #EA6722", +",, c #E96825", +"', c #EB6823", +"), c #EE651C", +"!, c #E85E14", +"~, c #E75C13", +"{, c #E75B11", +"], c #E65A0F", +"^, c #E6590D", +"/, c #E6590C", +"(, c #E5580B", +"_, c #E45709", +":, c #E55608", +"<, c #E45507", +"[, c #E4590B", +"}, c #D86529", +"|, c #EE7030", +"1, c #EC6C2B", +"2, c #EB6A28", +"3, c #EA6B28", +"4, c #E96925", +"5, c #E96823", +"6, c #E8641F", +"7, c #E7631D", +"8, c #D86326", +"9, c #F2702C", +"0, c #EC6D2B", +"a, c #E65E13", +"b, c #E45C10", +"c, c #E45A0C", +"d, c #D66123", +"e, c #F26E29", +"f, c #EC6D2C", +"g, c #EC6E2C", +"h, c #EB6D2A", +"i, c #EA6926", +"j, c #E66015", +"k, c #E65F14", +"l, c #E45B0C", +"m, c #D66022", +"n, c #F26D27", +"o, c #EB6B27", +"p, c #EC6B29", +"q, c #EC6C29", +"r, c #EC6B28", +"s, c #EB6A25", +"t, c #EB6925", +"u, c #EA6924", +"v, c #EA6721", +"w, c #E9651E", +"x, c #E8631B", +"y, c #E8631A", +"z, c #E8621A", +"A, c #E76218", +"B, c #E76117", +"C, c #E76015", +"D, c #E65D12", +"E, c #E65D11", +"F, c #E55C0F", +"G, c #E55B0E", +"H, c #E55A0C", +"I, c #E55A0D", +"J, c #E55B0D", +"K, c #EC5D0D", +"L, c #D9601F", +"M, c #FC7026", +"N, c #F56D26", +"O, c #F56E26", +"P, c #F56E27", +"Q, c #F66E27", +"R, c #F66F27", +"S, c #F66F28", +"T, c #F56D27", +"U, c #F56D25", +"V, c #F46C24", +"W, c #F56C23", +"X, c #F56B22", +"Y, c #F46A21", +"Z, c #F36A20", +"`, c #F3691F", +" ' c #F3681D", +".' c #F3681C", +"+' c #F2671B", +"@' c #F2661A", +"#' c #F26619", +"$' c #F26518", +"%' c #F16517", +"&' c #F16416", +"*' c #F16315", +"=' c #F16314", +"-' c #F06213", +";' c #F06112", +">' c #F06111", +",' c #F06010", +"'' c #EF5F0F", +")' c #EF5F0E", +"!' c #EF5E0D", +"~' c #EF5F0D", +"{' c #EF5E0E", +"]' c #F7620D", +"^' c #953B08", +"/' c #7D3713", +"(' c #733312", +"_' c #723211", +":' c #743211", +"<' c #723210", +"[' c #72320E", +"}' c #72310E", +"|' c #70310E", +"1' c #70310D", +"2' c #702F0D", +"3' c #702F0B", +"4' c #702F09", +"5' c #702D09", +"6' c #702D08", +"7' c #702C08", +"8' c #702C06", +"9' c #772E06", +" ", +" ", +" ", +" ", +" . + @ # $ % & * = - ; > , , ' ' , , , , ) ! ~ { ] ^ $ / ( _ : < [ } | 1 2 3 4 5 6 7 8 9 0 a b c d e f g h i j ", +" k l m n o p q r s t u v w w x x x w v y t z r q A B C D E F G H I J K L M N O P Q R S T U V W X Y Z ` ...+.@.#. ", +" $.%.&.*.=.-.;.>.,.'.).!.~.{.].~.].^./.(.'.,.>.;._.:.<.[.}.|.1.2.3.4.5.6.7.8.9.0.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p. ", +" $.q.r.=.s.t.u.v.w.!.~.].x.x.x.x.x.y.y.{.^.z.A.u.;._.B.C.[.D.E.F.2.G.H.I.J.K.L.M.N.O.P.Q.R.S.T.U.V.W.X.Y.Z.`. +.+ ", +" $.++@+s.#+$+,.%+!.].x.&+*+=+=+=+*+*+x.-+y.{./.A.u.;+>+,+'+)+!+1.2.3.4.I.6.K.L.~+{+]+^+/+(+_+:+<+[+}+|+1+2+3+4+5+ ", +" 6+7+8+#+;.A.).!.].x.=+=+9+9+9+9+9+9+=+*+0+a+{.'.,.;.;+B.<.[.D.E.b+c+G.5.d+7.e+9.0.f+g+/+(+h+i+j+k+l+m+1+n+o+p+5+ ", +" 6+q+r+#+u.w.!.].&+=+9+s+t+t+t+u+t+v+s+9+=+-+y./.'.,.w+x+,+'+}.y+1.z+G.H.I.J.8.A+0.N.b.c.d.e.f.B+C+D+m+E+F+G+H+I+ ", +" ~ J+-.K+v.%+~.x.=+9+v+t+L+L+L+L+L+L+t+v+9+*+-+{./.A.w+_.B.C.)+|.M+z+3.4.I.6.K.L.M.N.b.c.d.e.f.T.N+O+j.k.l.m.P+I+ ", +" Q+R+#+S+w.).T+U+u+V+W+X+Y+Z+Y+Y+X+X+W+`+V+u+ @.@+@@@#@J+$@q.%@&@y+b+3.4.5.6.K.L.*@{+O.P.d.R.S.T.N+O+j.k.l.m.=@-@ ", +" Q+R+#+S+w.!.;@>@,@'@)@!@~@{@{@{@{@!@]@^@/@,@(@_@:@<@[@}@|@1@2@3@4@5@6@[email protected]@e+~+{+O.9@[email protected]+O+j.k.a@m.=@-@ ", +" Q+R+t.S+%+b@c@d@e@f@g@g@g@g@g@g@g@g@g@g@f@f@h@h@h@h@i@i@i@j@k@l@m@n@[email protected]+~+{+]+^+0@[email protected]@X.Y.m.=@-@ ", +" Q+R+t.S+%+b@q@r@s@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@t@u@v@[email protected]+~+{+]+^+/+o@w@[email protected]@X.Y.y@=@-@ ", +" Q+R+t.S+w.+@z@A@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@C@D@6@[email protected]+~+{[email protected]@[email protected]@X.E@y@=@-@ ", +" Q+R+#+u.w.T+z@F@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@C@G@[email protected]@e+~+{+O.^+0@[email protected]@V.j.I@[email protected]@-@ ", +" Q+K@#+u.v.L@M@N@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@B@O@G@[email protected]@[email protected]@[email protected]+O+j.k.l.m.=@-@ ", +" ~ K@-.;.v.~.S@T@U@V@V@W@X@Y@X@Z@`@B@B@B@B@B@B@ #.#.#+#@###$#%#&#*#M+=#[email protected]#L.M.;#>#,#d.'#x@N+O+j.k.l.m.)#I+ ", +" ~ q+s.t.S+w.x.L@).].!#x.&+=+v+~#{#B@B@B@B@B@B@]#s.;.^#>+<.5@/#(#_#:#<#[#}#|#1#1#2#3#4#5#6#7#C+U.j+[+l+8#9#m.H+I+ ", +" 6+7+r+-.;.,.).~.].x.=+0#9+ @`+a#b#B@B@B@B@B@B@c#A.r.d#e#f#g#h#i#j#k#l#m#n#o#p#q#r#s#t#u#v#w#x#y#z#A#B#C#E@2+J@I+ ", +" 6+$@=.r+t.u.v.).~.].&+*+=+=+u+D#E#B@B@B@B@B@B@F#G#H#I#J#K#L#M#N#O#P#Q#R#S#T#U#V#W#X#Y#Z#u#w#`# $.$+$@$#$$$%$&$5+ ", +" *$=$r.8+-.-$u.'.).!.].].x.x.;$>$E#B@B@B@B@B@B@,$J#I#I#'$)$!$L#N#~${$Q#]$^$/$($_$q#:$<$[$u#w#}$|$1$2$@$3$4$5$6$7$ ", +" 8$9$0$@+8+-.;.u.A.%+).~.].].0#a$E#B@B@B@B@B@B@b$c$d$e$f$g$h$i$O#P#{$j$S#T#/$($k$l$:$m$n$o$p$q$r$s$t$@$u$v$w$x$y$ ", +" z$A$B$0$@+8+-.t.>.,.'.'./.{. @C$E#B@B@B@B@B@B@D$E$F$c$)$!$L#N#G${$Q#H$S#T#n#V#W#X#Y#Z#I$J$K$L$M$N$O$P$Q$R$S$T$U$ ", +" z$V$W$B$r.*.=.s.#+;.u.u.^.u.X$Y$Z$B@B@B@B@B@B@`$ %'$)$!$.%i$O#P#{$+%]$@%/$#%$%%%:$Y#&%*%w#}$|$=%-%+$;%>%,%5$x$U$ ", +" '%&@)%W$B$0$*.=.r+-.;.'.!%~%{%]%^%B@B@B@B@B@B@/%h$f$g$h$M#(%_%{$+%H$S#T#U#:%k$l$<%m$t#o$p$q$[%s$t$}%;%|%1%2%3%y$ ", +" 4%5%6%)%7%8%&.r.@+-.r+9%0%a%{%b%^%B@B@B@B@B@B@c%L#g$h$L#N#O#d%e%f%]$@%/$#%_$l$g%Y#Z#u#J$K$h%M$i%O$j%k%R$w$l%m%y$ ", +" : n%o%5@p%W$D.)+B.q%r%s%t%u%v%w%^%B@B@B@B@B@B@x%N#h$L#i$O#P#{$+%H$^$y%U#:%k$l$<%m$t#z%w#q$|$=%-%A%;%>%,%5$B%C%D% ", +" E%F%G@o%G%H%I%[.J%K%c$L%L%L%M%N%^%B@B@B@B@B@B@O%P%L#N#O#_%{$+%H$S#T#/$Q%$%l$:$Y#&%*%R%K$L$r$s$t$@$k%|%1%l%S%T%U% ", +" V%W%X%Y%Z%o%|.`% &.&F$F$d$F$+&@&^%B@B@B@B@B@B@#&$&N#O#P%%&&&*&=&-&;&>&,&'&)&Y#m$!&~&{&]&^&/&(&_&:&<&[&}&B%|&1&2& ", +" 3&4&5.X%5&6&7&8&!$9&c$0&'$'$a&b&^%B@B@B@B@B@B@c&k#G$$&d&e&f&g&h&i&j&k&l&m&n&o&p&q&r&s&t&u&v&w&x&y&z&A&B&C&D&E&F& ", +" G&H&d+5.5&I&J&M#g$g$g$)$)$)$K&L&^%B@B@B@B@B@B@M&N&P#O&P&Q&R&S&T&T&T&U&U&V&W&X&Y&Z&`& *S&.*.*.*.*.*.*+*@*#*$*%*F& ", +" &***J.I.K.=*O#L#L#h$h$h$!$h$-*;*^%B@B@B@B@B@B@>*,*e%'*)*!*B@B@B@B@B@B@B@B@~*{*]*^*t@B@B@B@B@B@B@B@B@B@/*(*_*%*F& ", +" :*<*K.8@[*j#(%N#N#i$M#M#}*M#|*1*^%B@B@B@B@B@B@2*3*4*5*6*7*B@B@B@B@B@B@B@8*9*0*a*b*c*d*B@B@B@B@B@e*f*g*h*i*j*k*l* ", +" m*n*o*p*q*P#_%P%~$O#i#O#O#O#r*s*^%B@B@B@B@B@B@t*U#u*v*w*x*y*z*A*B*B@B@B@C*D*E*F*G*H*I*J*B@B@B@K*L*M*N*O*P*Q*R*l* ", +" S*T*U*e%f%e%{$d%{$P#P#P#P#P#V*W*^%B@B@B@B@B@B@X*o#T#y%Y*Z*`* =.=+=B@B@B@@=#=p$$=%=&=*===B@B@B@-=;=>=,='=j*)=!=~= ", +" {=]=1#T#H$R#f%+%+%+%^=/=e%e%(=_=^%B@B@B@B@B@B@:=<=/$U#:%V#k$[=}=|=B@B@B@1=2=}$L$M$3=4=5=B@B@B@6=7=S%8=_*Q*9=0=~= ", +" {=a=b=T#^$S#S#]$H$H$H$R#f%f%c=d=e=B@B@B@B@B@B@f=g=($V#_$h=q#i=j=k=B@B@B@l=m=L$r$n=o=p=q=B@B@r=s=P*t=$*u=)=v=w=x= ", +" y=z=o#/$/$y%T#@%@%@%S#S#S#S#A=B=e=B@B@B@B@B@B@C=D=$%W#%%l$E=F=G=H=B@B@I=J=K=r$1$L=M=N=O=B@B@P=Q=$*R=P*Q*S=T=U=x= ", +" V=W=V#Q%U#U#/$/$/$y%y%y%T#y%*&X=Y=B@B@B@B@B@B@Z=`=h=l$:$:$ -.-+-B@B@B@@-#-$-1$i%/&%-&-B@B@B@*-$*R==-Q*9=--;->-,- ", +" '-)-W#k$_$V#o##%#%#%#%U#U##%!-~-{-]-^-/-/-/-(-_-t#:$:$<$m$:-<-[-B@B@B@}-|-1$i%O$1-2-3-B@B@B@4-i*$*Q*)=v=T=5-6-7- ", +" 8-9-:$l$l$0-k$k$_$_$$%V#V#$%a-b-c-d-e-f-g-g-6#h-m$Y#Z#Z#i-j-k-l-B@B@B@m-@$-%n-o-p-q-r-B@B@B@s-i*j*Q*t-T=u-v-w-,- ", +" x-y-Y#<%:$z-X#l$l$h=W#0-%%W#%%A-B-C-D-E-E-F-E*t#m$Z#n$u#G-H-I-J-B@B@K-L-M-A%@$N-O-P-Q-B@B@R-S-9=Q*9=T-U-V-W-X-Y- ", +" Z-`-Z#m$<$Y#Y#<%:$:$:$g%g%:$g%g%:$<%Y#Y#Y#m$Z#t#t#I$z%J$ ;.;+;B@B@B@@;#;@$@$;%$;%;&;B@B@B@*;$*)=9=v=U-=;-;;;>;,; ", +" ';);I$n$t#Z#Z#Z#m$m$<$<$m$<$<$m$m$Z#Z#Z#t#n$u#*%o$R%p$K$!;~;{;B@B@B@];^;P$/;>%(;_;:;B@B@B@<;[;9=v=;-};v-W-|;1;2; ", +" 3;4;J$o$z%u#u#n$n$t#t#t#t#t#t#n$n$I$u#I$o$5;6;7;8;8;9;0;a;b;c;B@B@B@d;e;f;g;h;R=i;j;B@B@B@k;l;m;n;5-v-W-|;o;p;q; ", +" r;s;K$t;w#u;R%J$o$z%z%z%z%z%z%z%o$o$R%u;#=v;w;x;y;z;A;B;C;D;B@B@B@E;F;G;H;I;J;K;L;M;B@B@N;O;P;Q;R;S;W-T;o;U;V;W; ", +" X;Y;L$`#q$}$Z;K$t;p$p$p$p$p$p$p$t;K$K$}$`; >.>+>@>#>$>%>&>B@B@B@B@*>=>->;>>>,>'>)>B@B@B@8*!>~>{>]>^>T;/>(>_>:><> ", +" [>}>M$r$|$|$L$L$|>`#q$q$q$`#`#`#L$L$L$1>2>3>4>B@5>6>7>B@B@B@B@B@8>S$9>0>a>b>B@B@B@B@B@B@B@B@B@c>d>o;/>U;_>e>f>g> ", +" h>i>i%i%j>1$M$M$M$r$r$[%[%r$k>r$M$M$M$1$l>m>n>B@B@B@B@B@B@B@o>p>5$q>r>s>t>u>B@B@B@B@B@B@B@B@B@v>w>|;(>_>e>x>y><> ", +" z>A>A%t$t$-%i%i%i%j>j>s$s$j>s$s$i%i%i%B>C>D>E>F>G>G>H>I>J>K>L>M>l%5$N>O>P>Q>R>S>S>T>U>V>W>X>W>Y>Z>(>_>e>`> ,y><> ", +" .,+,@,@$@$+$A%A%O$t$t$t$t$t$t$t$O$A%A%+$}%#,$,%,&,*,=,9>-,;,>,5$l%S%,,',),!,~,{,],^,/,(,_,:,<,[,o;_>e>`> , ,y><> ", +" },#,k%k%/;;%|,@,P$j%@$@$@$@$j%j%P$M-;%;%/;u$|%1,S$2,q>l%5$3,B%S%4,5,$*_*Q*6,7,v=;-U-=;-;W-|;o;(>_>e>x> , , ,y><> ", +" 8,9,,%R$|%>%>%Q$k%k%k%k%k%u$u$k%k%Q$>%|%|%R$0,,%w$S$3,l%B%S%|&5,$*_*j*Q*)=i*--;-u-V--;;;a,o;U;b,e>x>c, , , ,y><> ", +" d,e,S$w$1%1%,%,%0,f,f,R$v$g,R$R$f,,%h,9>1%w$5$3,l%l%i,S%|&5,$*=-u=Q*)=9=v=T=;-u-V-j,k,|;o;U;b,e>x> ,c, , ,l,y><> ", +" m,n,0>q>o,5$5$p,q,q,q,q,q,q,q,q,q,r,r,5$o,q>0>s,t,u,t=>,>,v,P*'=w,9=x,y,z,A,B,S;C,k,a,D,E,F,Z>G,H,H,I,I,I,J,K,<> ", +" L,M,N,N,O,P,Q,P,R,S,S,S,S,S,S,S,S,Q,Q,P,T,N,U,U,V,W,X,Y,Y,Z,`, '.'+'@'#'$'%'&'*'='-';'>',''')'!'!'!'!'~'{'!']'^' ", +" /'('_'_':'_':':':':':':':':':'_':'_'_'_'<'<'<'<'['}'}'|'1'1'2'1'3'3'3'4'4'5'6'6'7'7'8'8'8'8'8'8'8'8'8'8'9' ", +" ", +" ", +" ", +" "}; diff --git a/org.eclipselabs.tapiji.translator.rcp/org.eclipselabs.tapiji.translator.rcp.product b/org.eclipselabs.tapiji.translator.rcp/org.eclipselabs.tapiji.translator.rcp.product index ba82c116..593ec185 100644 --- a/org.eclipselabs.tapiji.translator.rcp/org.eclipselabs.tapiji.translator.rcp.product +++ b/org.eclipselabs.tapiji.translator.rcp/org.eclipselabs.tapiji.translator.rcp.product @@ -19,15 +19,22 @@ by Stefan Strobl &amp; Martin Reiterer <vmArgsMac>-XstartOnFirstThread -Dorg.eclipse.swt.internal.carbon.smallFonts</vmArgsMac> </launcherArgs> - <windowImages i16="/org.eclipselabs.tapiji.translator/icons/TapiJI_16.png" i32="/org.eclipselabs.tapiji.translator/icons/TapiJI_32.png" i48="/org.eclipselabs.tapiji.translator/icons/TapiJI_48.png" i64="/org.eclipselabs.tapiji.translator/icons/TapiJI_64.png" i128="/org.eclipselabs.tapiji.translator/icons/TapiJI_128.png"/> + <windowImages i16="/org.eclipselabs.tapiji.translator.rcp.product/icons/TapiJI_16.png" i32="/org.eclipselabs.tapiji.translator.rcp.product/icons/TapiJI_32.png" i48="/org.eclipselabs.tapiji.translator.rcp.product/icons/TapiJI_48.png" i64="/org.eclipselabs.tapiji.translator.rcp.product/icons/TapiJI_64.png" i128="/org.eclipselabs.tapiji.translator.rcp.product/icons/TapiJI_128.png"/> + <splash + location="org.eclipselabs.tapiji.translator" /> <launcher name="translator"> + <linux icon="/org.eclipselabs.tapiji.translator.rcp.product/icons/TapiJI_48.xpm"/> <solaris/> <win useIco="false"> - <bmp/> + <bmp + winSmallHigh="/org.eclipselabs.tapiji.translator.rcp.product/icons/TapiJI_16.bmp" + winMediumHigh="/org.eclipselabs.tapiji.translator.rcp.product/icons/TapiJI_32.bmp" + winLargeHigh="/org.eclipselabs.tapiji.translator.rcp.product/icons/TapiJI_48.bmp"/> </win> </launcher> + <vm> </vm> @@ -293,13 +300,13 @@ litigation. <plugin id="org.eclipse.osgi"/> <plugin id="org.eclipse.osgi.services"/> <plugin id="org.eclipse.swt"/> - <plugin id="org.eclipse.swt.carbon.macosx" fragment="true"/> - <plugin id="org.eclipse.swt.cocoa.macosx" fragment="true"/> - <plugin id="org.eclipse.swt.cocoa.macosx.x86_64" fragment="true"/> - <plugin id="org.eclipse.swt.gtk.linux.x86" fragment="true"/> - <plugin id="org.eclipse.swt.gtk.linux.x86_64" fragment="true"/> - <plugin id="org.eclipse.swt.win32.win32.x86" fragment="true"/> - <plugin id="org.eclipse.swt.win32.win32.x86_64" fragment="true"/> + <plugin id="org.eclipse.swt.carbon.macosx" fragment="true" os="macosx" ws="carbon" arch="x86"/> + <plugin id="org.eclipse.swt.cocoa.macosx" fragment="true" os="macosx" ws="cocoa" arch="x86"/> + <plugin id="org.eclipse.swt.cocoa.macosx.x86_64" fragment="true" os="macosx" ws="cocoa" arch="x86_64"/> + <plugin id="org.eclipse.swt.gtk.linux.x86" fragment="true" os="linux" ws="gtk" arch="x86"/> + <plugin id="org.eclipse.swt.gtk.linux.x86_64" fragment="true" os="linux" ws="gtk" arch="x86_64"/> + <plugin id="org.eclipse.swt.win32.win32.x86" fragment="true" os="win32" ws="win32" arch="x86"/> + <plugin id="org.eclipse.swt.win32.win32.x86_64" fragment="true" os="win32" ws="win32" arch="x86_64"/> <plugin id="org.eclipse.team.core"/> <plugin id="org.eclipse.team.ui"/> <plugin id="org.eclipse.text"/>
fa8fcb53c58b5759ad500fdaf50a66ccb8c08a12
kotlin
Introduce Variable: Forbid extraction from class- initializer (aside of its body) -KT-8329 Fixed--
c
https://github.com/JetBrains/kotlin
diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.java b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.java index b458f0b15be14..44767692efad2 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.java +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceVariable/KotlinIntroduceVariableHandler.java @@ -330,8 +330,7 @@ private void run( JetProperty property = psiFactory.createProperty(variableText); PsiElement anchor = calculateAnchor(commonParent, commonContainer, allReplaces); if (anchor == null) return; - boolean needBraces = !(commonContainer instanceof JetBlockExpression || - commonContainer instanceof JetClassInitializer); + boolean needBraces = !(commonContainer instanceof JetBlockExpression); if (!needBraces) { property = (JetProperty)commonContainer.addBefore(property, anchor); commonContainer.addBefore(psiFactory.createNewLine(), anchor); @@ -548,7 +547,7 @@ private static boolean shouldReplaceOccurrence( @Nullable private static PsiElement getContainer(PsiElement place) { - if (place instanceof JetBlockExpression || place instanceof JetClassInitializer) { + if (place instanceof JetBlockExpression) { return place; } while (place != null) { @@ -559,8 +558,7 @@ private static PsiElement getContainer(PsiElement place) { } } if (parent instanceof JetBlockExpression - || (parent instanceof JetWhenEntry && place == ((JetWhenEntry) parent).getExpression()) - || parent instanceof JetClassInitializer) { + || (parent instanceof JetWhenEntry && place == ((JetWhenEntry) parent).getExpression())) { return parent; } if (parent instanceof JetDeclarationWithBody && ((JetDeclarationWithBody) parent).getBodyExpression() == place) { @@ -596,7 +594,7 @@ private static PsiElement getOccurrenceContainer(PsiElement place) { result = parent; } } - else if (parent instanceof JetClassBody || parent instanceof JetFile || parent instanceof JetClassInitializer) { + else if (parent instanceof JetClassBody || parent instanceof JetFile) { return result; } else if (parent instanceof JetBlockExpression) { diff --git a/idea/testData/refactoring/introduceVariable/InsideOfInitializerAnnotation.kt b/idea/testData/refactoring/introduceVariable/InsideOfInitializerAnnotation.kt new file mode 100644 index 0000000000000..ace8099d55bee --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/InsideOfInitializerAnnotation.kt @@ -0,0 +1,4 @@ +class C { + deprecated(<selection>""</selection>) + init {} +} \ No newline at end of file diff --git a/idea/testData/refactoring/introduceVariable/InsideOfInitializerAnnotation.kt.conflicts b/idea/testData/refactoring/introduceVariable/InsideOfInitializerAnnotation.kt.conflicts new file mode 100644 index 0000000000000..1568c6aea626f --- /dev/null +++ b/idea/testData/refactoring/introduceVariable/InsideOfInitializerAnnotation.kt.conflicts @@ -0,0 +1 @@ +Cannot refactor in this place diff --git a/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/JetExtractionTestGenerated.java b/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/JetExtractionTestGenerated.java index 2d1b47fe1da96..507243e27052b 100644 --- a/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/JetExtractionTestGenerated.java +++ b/idea/tests/org/jetbrains/kotlin/idea/refactoring/introduce/JetExtractionTestGenerated.java @@ -145,6 +145,12 @@ public void testIfThenValuedAddBlock() throws Exception { doIntroduceVariableTest(fileName); } + @TestMetadata("InsideOfInitializerAnnotation.kt") + public void testInsideOfInitializerAnnotation() throws Exception { + String fileName = JetTestUtils.navigationMetadata("idea/testData/refactoring/introduceVariable/InsideOfInitializerAnnotation.kt"); + doIntroduceVariableTest(fileName); + } + @TestMetadata("IntroduceAndCreateBlock.kt") public void testIntroduceAndCreateBlock() throws Exception { String fileName = JetTestUtils.navigationMetadata("idea/testData/refactoring/introduceVariable/IntroduceAndCreateBlock.kt");
e5ef89a6baff7b90f4707efa2c24cbde6563ec94
Vala
mysql: Fix mysql_init binding. Fixes bug 603085.
c
https://github.com/GNOME/vala/
diff --git a/vapi/mysql.vapi b/vapi/mysql.vapi index 8843068f41..8e21ac01b5 100644 --- a/vapi/mysql.vapi +++ b/vapi/mysql.vapi @@ -26,8 +26,8 @@ namespace Mysql { [Compact] [CCode (free_function = "mysql_close", cname = "MYSQL", cprefix = "mysql_")] public class Database { - [CCode (argument0 = "NULL", cname = "mysql_init")] - public void init (); + [CCode (cname = "mysql_init")] + public Database (Database? mysql = null); public ulong affected_rows (); public bool autocommit (bool mode);
6ac389cf8a8d445d7689e672f1b9e8dd23f37419
kotlin
Extracted error messages from- DefaultDiagnosticRenderer to special DefaultErrorMessages class.--
p
https://github.com/JetBrains/kotlin
diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java index 2c74e53d6a3e8..628d07a338f15 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/Errors.java @@ -38,6 +38,8 @@ import static org.jetbrains.jet.lang.diagnostics.Severity.WARNING; /** + * For error messages, see DefaultErrorMessages and IdeErrorMessages. + * * @author abreslav */ public interface Errors { @@ -326,7 +328,8 @@ public List<TextRange> mark(@NotNull JetWhenConditionInRange condition) { @NotNull @Override public List<TextRange> mark(@NotNull JetNullableType element) { - return markNode(element.getQuestionMarkNode()); + return markNode( + element.getQuestionMarkNode()); } }); DiagnosticFactory1<PsiElement, JetType> UNSAFE_CALL = DiagnosticFactory1.create(ERROR); diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java index 746ce87d6182a..6453e0465e7ac 100644 --- a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultDiagnosticRenderer.java @@ -16,25 +16,8 @@ package org.jetbrains.jet.lang.diagnostics.rendering; -import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; -import org.jetbrains.jet.lang.descriptors.CallableDescriptor; -import org.jetbrains.jet.lang.diagnostics.*; -import org.jetbrains.jet.lang.psi.JetExpression; -import org.jetbrains.jet.lang.psi.JetSimpleNameExpression; -import org.jetbrains.jet.lang.psi.JetTypeConstraint; -import org.jetbrains.jet.lang.resolve.calls.ResolvedCall; -import org.jetbrains.jet.lang.types.JetType; -import org.jetbrains.jet.lexer.JetKeywordToken; -import org.jetbrains.jet.resolve.DescriptorRenderer; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import static org.jetbrains.jet.lang.diagnostics.Errors.*; -import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.*; +import org.jetbrains.jet.lang.diagnostics.Diagnostic; /** * @author Evgeny Gerashchenko @@ -42,393 +25,8 @@ */ public class DefaultDiagnosticRenderer implements DiagnosticRenderer<Diagnostic> { public static final DefaultDiagnosticRenderer INSTANCE = new DefaultDiagnosticRenderer(); - private static final Renderer<Collection<? extends ResolvedCall<? extends CallableDescriptor>>> AMBIGUOUS_CALLS = - new Renderer<Collection<? extends ResolvedCall<? extends CallableDescriptor>>>() { - @NotNull - @Override - public String render(@NotNull Collection<? extends ResolvedCall<? extends CallableDescriptor>> argument) { - StringBuilder stringBuilder = new StringBuilder("\n"); - for (ResolvedCall<? extends CallableDescriptor> call : argument) { - stringBuilder.append(DescriptorRenderer.TEXT.render(call.getResultingDescriptor())).append("\n"); - } - return stringBuilder.toString(); - } - }; - - private final Map<AbstractDiagnosticFactory, DiagnosticRenderer<?>> map = - new HashMap<AbstractDiagnosticFactory, DiagnosticRenderer<?>>(); - - protected final <E extends PsiElement> void put(SimpleDiagnosticFactory<E> factory, String message) { - map.put(factory, new SimpleDiagnosticRenderer(message)); - } - - protected final <E extends PsiElement, A> void put(DiagnosticFactory1<E, A> factory, String message, Renderer<? super A> rendererA) { - map.put(factory, new DiagnosticWithParameters1Renderer<A>(message, rendererA)); - } - - protected final <E extends PsiElement, A, B> void put(DiagnosticFactory2<E, A, B> factory, - String message, - Renderer<? super A> rendererA, - Renderer<? super B> rendererB) { - map.put(factory, new DiagnosticWithParameters2Renderer<A, B>(message, rendererA, rendererB)); - } - - protected final <E extends PsiElement, A, B, C> void put(DiagnosticFactory3<E, A, B, C> factory, - String message, - Renderer<? super A> rendererA, - Renderer<? super B> rendererB, - Renderer<? super C> rendererC) { - map.put(factory, new DiagnosticWithParameters3Renderer<A, B, C>(message, rendererA, rendererB, rendererC)); - } - - protected DefaultDiagnosticRenderer() { - put(EXCEPTION_WHILE_ANALYZING, "{0}", new Renderer<Throwable>() { - @NotNull - @Override - public String render(@NotNull Throwable e) { - return e.getClass().getSimpleName() + ": " + e.getMessage(); - } - }); - - put(UNRESOLVED_REFERENCE, "Unresolved reference: {0}", TO_STRING); - - put(INVISIBLE_REFERENCE, "Cannot access ''{0}'' in ''{1}''", NAME, NAME); - put(INVISIBLE_MEMBER, "Cannot access ''{0}'' in ''{1}''", NAME, NAME); - - put(REDECLARATION, "Redeclaration: {0}", NAME); - put(NAME_SHADOWING, "Name shadowed: {0}", NAME); - - put(TYPE_MISMATCH, "Type mismatch: inferred type is {1} but {0} was expected", RENDER_TYPE, RENDER_TYPE); - put(INCOMPATIBLE_MODIFIERS, "Incompatible modifiers: ''{0}''", new Renderer<Collection<JetKeywordToken>>() { - @NotNull - @Override - public String render(@NotNull Collection<JetKeywordToken> tokens) { - StringBuilder sb = new StringBuilder(); - for (Iterator<JetKeywordToken> iterator = tokens.iterator(); iterator.hasNext(); ) { - JetKeywordToken modifier = iterator.next(); - sb.append(modifier.getValue()); - if (iterator.hasNext()) { - sb.append(" "); - } - } - return sb.toString(); - } - }); - put(ILLEGAL_MODIFIER, "Illegal modifier ''{0}''", TO_STRING); - - put(REDUNDANT_MODIFIER, "Modifier {0} is redundant because {1} is present", TO_STRING, TO_STRING); - put(ABSTRACT_MODIFIER_IN_TRAIT, "Modifier ''abstract'' is redundant in trait"); - put(OPEN_MODIFIER_IN_TRAIT, "Modifier ''open'' is redundant in trait"); - put(REDUNDANT_MODIFIER_IN_GETTER, "Visibility modifiers are redundant in getter"); - put(TRAIT_CAN_NOT_BE_FINAL, "Trait can not be final"); - put(TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM, - "Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly"); // TODO: message - put(RETURN_NOT_ALLOWED, "'return' is not allowed here"); - put(PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE, "Projections are not allowed for immediate arguments of a supertype"); - put(LABEL_NAME_CLASH, "There is more than one label with such a name in this scope"); - put(EXPRESSION_EXPECTED_NAMESPACE_FOUND, "Expression expected, but a namespace name found"); - - put(CANNOT_IMPORT_FROM_ELEMENT, "Cannot import from ''{0}''", NAME); - put(CANNOT_BE_IMPORTED, "Cannot import ''{0}'', functions and properties can be imported only from packages", NAME); - put(USELESS_HIDDEN_IMPORT, "Useless import, it is hidden further"); - put(USELESS_SIMPLE_IMPORT, "Useless import, does nothing"); - - put(CANNOT_INFER_PARAMETER_TYPE, - "Cannot infer a type for this parameter. To specify it explicitly use the {(p : Type) => ...} notation"); - - put(NO_BACKING_FIELD_ABSTRACT_PROPERTY, "This property doesn't have a backing field, because it's abstract"); - put(NO_BACKING_FIELD_CUSTOM_ACCESSORS, - "This property doesn't have a backing field, because it has custom accessors without reference to the backing field"); - put(INACCESSIBLE_BACKING_FIELD, "The backing field is not accessible here"); - put(NOT_PROPERTY_BACKING_FIELD, "The referenced variable is not a property and doesn't have backing field"); - - put(MIXING_NAMED_AND_POSITIONED_ARGUMENTS, "Mixing named and positioned arguments in not allowed"); - put(ARGUMENT_PASSED_TWICE, "An argument is already passed for this parameter"); - put(NAMED_PARAMETER_NOT_FOUND, "Cannot find a parameter with this name: {0}", TO_STRING); - put(VARARG_OUTSIDE_PARENTHESES, "Passing value as a vararg is only allowed inside a parenthesized argument list"); - put(NON_VARARG_SPREAD, "The spread operator (*foo) may only be applied in a vararg position"); - - put(MANY_FUNCTION_LITERAL_ARGUMENTS, "Only one function literal is allowed outside a parenthesized argument list"); - put(PROPERTY_WITH_NO_TYPE_NO_INITIALIZER, "This property must either have a type annotation or be initialized"); - - put(ABSTRACT_PROPERTY_IN_PRIMARY_CONSTRUCTOR_PARAMETERS, "This property cannot be declared abstract"); - put(ABSTRACT_PROPERTY_NOT_IN_CLASS, "A property may be abstract only when defined in a class or trait"); - put(ABSTRACT_PROPERTY_WITH_INITIALIZER, "Property with initializer cannot be abstract"); - put(ABSTRACT_PROPERTY_WITH_GETTER, "Property with getter implementation cannot be abstract"); - put(ABSTRACT_PROPERTY_WITH_SETTER, "Property with setter implementation cannot be abstract"); - - put(PACKAGE_MEMBER_CANNOT_BE_PROTECTED, "Package member cannot be protected"); - - put(GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY, "Getter visibility must be the same as property visibility"); - put(BACKING_FIELD_IN_TRAIT, "Property in a trait cannot have a backing field"); - put(MUST_BE_INITIALIZED, "Property must be initialized"); - put(MUST_BE_INITIALIZED_OR_BE_ABSTRACT, "Property must be initialized or be abstract"); - put(PROPERTY_INITIALIZER_IN_TRAIT, "Property initializers are not allowed in traits"); - put(PROPERTY_INITIALIZER_NO_BACKING_FIELD, "Initializer is not allowed here because this property has no backing field"); - put(ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS, "Abstract property {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING); - put(ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS, "Abstract function {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING); - put(ABSTRACT_FUNCTION_WITH_BODY, "A function {0} with body cannot be abstract", TO_STRING); - put(NON_ABSTRACT_FUNCTION_WITH_NO_BODY, "Method {0} without a body must be abstract", TO_STRING); - put(NON_MEMBER_ABSTRACT_FUNCTION, "Function {0} is not a class or trait member and cannot be abstract", TO_STRING); - - put(NON_MEMBER_FUNCTION_NO_BODY, "Function {0} must have a body", TO_STRING); - put(NON_FINAL_MEMBER_IN_FINAL_CLASS, "Non final member in a final class"); - - put(PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE, "Public or protected member should specify a type"); - - put(PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT, - "Projections are not allowed on type arguments of functions and properties"); // TODO : better positioning - put(SUPERTYPE_NOT_INITIALIZED, "This type has a constructor, and thus must be initialized here"); - put(SUPERTYPE_NOT_INITIALIZED_DEFAULT, "Constructor invocation should be explicitly specified"); - put(SECONDARY_CONSTRUCTOR_BUT_NO_PRIMARY, "A secondary constructor may appear only in a class that has a primary constructor"); - put(SECONDARY_CONSTRUCTOR_NO_INITIALIZER_LIST, "Secondary constructors must have an initializer list"); - put(BY_IN_SECONDARY_CONSTRUCTOR, "'by'-clause is only supported for primary constructors"); - put(INITIALIZER_WITH_NO_ARGUMENTS, "Constructor arguments required"); - put(MANY_CALLS_TO_THIS, "Only one call to 'this(...)' is allowed"); - put(NOTHING_TO_OVERRIDE, "{0} overrides nothing", DescriptorRenderer.TEXT); - put(VIRTUAL_MEMBER_HIDDEN, "''{0}'' hides ''{1}'' in class {2} and needs 'override' modifier", DescriptorRenderer.TEXT, - DescriptorRenderer.TEXT, DescriptorRenderer.TEXT); - - put(ENUM_ENTRY_SHOULD_BE_INITIALIZED, "Missing delegation specifier ''{0}''", NAME); - put(ENUM_ENTRY_ILLEGAL_TYPE, "The type constructor of enum entry should be ''{0}''", NAME); - - put(UNINITIALIZED_VARIABLE, "Variable ''{0}'' must be initialized", NAME); - put(UNINITIALIZED_PARAMETER, "Parameter ''{0}'' is uninitialized here", NAME); - put(UNUSED_VARIABLE, "Variable ''{0}'' is never used", NAME); - put(UNUSED_PARAMETER, "Parameter ''{0}'' is never used", NAME); - put(ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE, "Variable ''{0}'' is assigned but never accessed", NAME); - put(VARIABLE_WITH_REDUNDANT_INITIALIZER, "Variable ''{0}'' initializer is redundant", NAME); - put(UNUSED_VALUE, "The value ''{0}'' assigned to ''{1}'' is never used", ELEMENT_TEXT, TO_STRING); - put(UNUSED_CHANGED_VALUE, "The value changed at ''{0}'' is never used", ELEMENT_TEXT); - put(UNUSED_EXPRESSION, "The expression is unused"); - put(UNUSED_FUNCTION_LITERAL, "The function literal is unused. If you mean block, you can use 'run { ... }'"); - - put(VAL_REASSIGNMENT, "Val can not be reassigned", NAME); - put(INITIALIZATION_BEFORE_DECLARATION, "Variable cannot be initialized before declaration", NAME); - put(VARIABLE_EXPECTED, "Variable expected"); - - put(INITIALIZATION_USING_BACKING_FIELD_CUSTOM_SETTER, - "This property has a custom setter, so initialization using backing field required", NAME); - put(INITIALIZATION_USING_BACKING_FIELD_OPEN_SETTER, - "Setter of this property can be overridden, so initialization using backing field required", NAME); - - put(FUNCTION_PARAMETERS_OF_INLINE_FUNCTION, "Function parameters of inline function can only be invoked", NAME); - - put(UNREACHABLE_CODE, "Unreachable code"); - put(MANY_CLASS_OBJECTS, "Only one class object is allowed per class"); - put(CLASS_OBJECT_NOT_ALLOWED, "A class object is not allowed here"); - put(DELEGATION_IN_TRAIT, "Traits cannot use delegation"); - put(DELEGATION_NOT_TO_TRAIT, "Only traits can be delegated to"); - put(NO_CONSTRUCTOR, "This class does not have a constructor"); - put(NOT_A_CLASS, "Not a class"); - put(ILLEGAL_ESCAPE_SEQUENCE, "Illegal escape sequence"); - - put(LOCAL_EXTENSION_PROPERTY, "Local extension properties are not allowed"); - put(LOCAL_VARIABLE_WITH_GETTER, "Local variables are not allowed to have getters"); - put(LOCAL_VARIABLE_WITH_SETTER, "Local variables are not allowed to have setters"); - put(VAL_WITH_SETTER, "A 'val'-property cannot have a setter"); - - put(NO_GET_METHOD, "No get method providing array access"); - put(NO_SET_METHOD, "No set method providing array access"); - - put(INC_DEC_SHOULD_NOT_RETURN_UNIT, "Functions inc(), dec() shouldn't return Unit to be used by operators ++, --"); - put(ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT, "Function ''{0}'' should return Unit to be used by corresponding operator ''{1}''", - NAME, ELEMENT_TEXT); - put(ASSIGN_OPERATOR_AMBIGUITY, "Assignment operators ambiguity: {0}", AMBIGUOUS_CALLS); - - put(EQUALS_MISSING, "No method 'equals(Any?) : Boolean' available"); - put(ASSIGNMENT_IN_EXPRESSION_CONTEXT, "Assignments are not expressions, and only expressions are allowed in this context"); - put(NAMESPACE_IS_NOT_AN_EXPRESSION, "'namespace' is not an expression, it can only be used on the left-hand side of a dot ('.')"); - put(SUPER_IS_NOT_AN_EXPRESSION, "{0} is not an expression, it can only be used on the left-hand side of a dot ('.')", TO_STRING); - put(DECLARATION_IN_ILLEGAL_CONTEXT, "Declarations are not allowed in this position"); - put(SETTER_PARAMETER_WITH_DEFAULT_VALUE, "Setter parameters can not have default values"); - put(NO_THIS, "'this' is not defined in this context"); - put(SUPER_NOT_AVAILABLE, "No supertypes are accessible in this context"); - put(AMBIGUOUS_SUPER, "Many supertypes available, please specify the one you mean in angle brackets, e.g. 'super<Foo>'"); - put(ABSTRACT_SUPER_CALL, "Abstract member cannot be accessed directly"); - put(NOT_A_SUPERTYPE, "Not a supertype"); - put(TYPE_ARGUMENTS_REDUNDANT_IN_SUPER_QUALIFIER, "Type arguments do not need to be specified in a 'super' qualifier"); - put(USELESS_CAST_STATIC_ASSERT_IS_FINE, "No cast needed, use ':' instead"); - put(USELESS_CAST, "No cast needed"); - put(CAST_NEVER_SUCCEEDS, "This cast can never succeed"); - put(WRONG_SETTER_PARAMETER_TYPE, "Setter parameter type must be equal to the type of the property, i.e. {0}", RENDER_TYPE); - put(WRONG_GETTER_RETURN_TYPE, "Getter return type must be equal to the type of the property, i.e. {0}", RENDER_TYPE); - put(NO_CLASS_OBJECT, "Please specify constructor invocation; classifier {0} does not have a class object", NAME); - put(NO_GENERICS_IN_SUPERTYPE_SPECIFIER, "Generic arguments of the base type must be specified"); - - put(HAS_NEXT_PROPERTY_AND_FUNCTION_AMBIGUITY, - "An ambiguity between 'iterator().hasNext()' function and 'iterator().hasNext' property"); - put(HAS_NEXT_MISSING, "Loop range must have an 'iterator().hasNext()' function or an 'iterator().hasNext' property"); - put(HAS_NEXT_FUNCTION_AMBIGUITY, "Function 'iterator().hasNext()' is ambiguous for this expression"); - put(HAS_NEXT_MUST_BE_READABLE, "The 'iterator().hasNext' property of the loop range must be readable"); - put(HAS_NEXT_PROPERTY_TYPE_MISMATCH, "The 'iterator().hasNext' property of the loop range must return Boolean, but returns {0}", - RENDER_TYPE); - put(HAS_NEXT_FUNCTION_TYPE_MISMATCH, "The 'iterator().hasNext()' function of the loop range must return Boolean, but returns {0}", - RENDER_TYPE); - put(NEXT_AMBIGUITY, "Function 'iterator().next()' is ambiguous for this expression"); - put(NEXT_MISSING, "Loop range must have an 'iterator().next()' function"); - put(ITERATOR_MISSING, "For-loop range must have an iterator() method"); - put(ITERATOR_AMBIGUITY, "Method 'iterator()' is ambiguous for this expression: {0}", AMBIGUOUS_CALLS); - - put(COMPARE_TO_TYPE_MISMATCH, "compareTo() must return Int, but returns {0}", RENDER_TYPE); - put(CALLEE_NOT_A_FUNCTION, "Expecting a function type, but found {0}", RENDER_TYPE); - - put(RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY, - "Returns are not allowed for functions with expression body. Use block body in '{...}'"); - put(NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY, "A 'return' expression required in a function with a block body ('{...}')"); - put(RETURN_TYPE_MISMATCH, "This function must return a value of type {0}", RENDER_TYPE); - put(EXPECTED_TYPE_MISMATCH, "Expected a value of type {0}", RENDER_TYPE); - put(ASSIGNMENT_TYPE_MISMATCH, - "Expected a value of type {0}. Assignment operation is not an expression, so it does not return any value", RENDER_TYPE); - put(IMPLICIT_CAST_TO_UNIT_OR_ANY, "Type was casted to ''{0}''. Please specify ''{0}'' as expected type, if you mean such cast", - RENDER_TYPE); - put(EXPRESSION_EXPECTED, "{0} is not an expression, and only expression are allowed here", new Renderer<JetExpression>() { - @NotNull - @Override - public String render(@NotNull JetExpression expression) { - String expressionType = expression.toString(); - return expressionType.substring(0, 1) + - expressionType.substring(1).toLowerCase(); - } - }); - - put(UPPER_BOUND_VIOLATED, "An upper bound {0} is violated", RENDER_TYPE); // TODO : Message - put(FINAL_CLASS_OBJECT_UPPER_BOUND, "{0} is a final type, and thus a class object cannot extend it", RENDER_TYPE); - put(FINAL_UPPER_BOUND, "{0} is a final type, and thus a value of the type parameter is predetermined", RENDER_TYPE); - put(USELESS_ELVIS, "Elvis operator (?:) always returns the left operand of non-nullable type {0}", RENDER_TYPE); - put(CONFLICTING_UPPER_BOUNDS, "Upper bounds of {0} have empty intersection", NAME); - put(CONFLICTING_CLASS_OBJECT_UPPER_BOUNDS, "Class object upper bounds of {0} have empty intersection", NAME); - - put(TOO_MANY_ARGUMENTS, "Too many arguments for {0}", TO_STRING); - put(ERROR_COMPILE_TIME_VALUE, "{0}", TO_STRING); - - put(ELSE_MISPLACED_IN_WHEN, "'else' entry must be the last one in a when-expression"); - - put(NO_ELSE_IN_WHEN, "'when' expression must contain 'else' branch"); - put(TYPE_MISMATCH_IN_RANGE, "Type mismatch: incompatible types of range and element checked in it"); - put(CYCLIC_INHERITANCE_HIERARCHY, "There's a cycle in the inheritance hierarchy for this type"); - - put(MANY_CLASSES_IN_SUPERTYPE_LIST, "Only one class may appear in a supertype list"); - put(SUPERTYPE_NOT_A_CLASS_OR_TRAIT, "Only classes and traits may serve as supertypes"); - put(SUPERTYPE_INITIALIZED_IN_TRAIT, "Traits cannot initialize supertypes"); - put(CONSTRUCTOR_IN_TRAIT, "A trait may not have a constructor"); - put(SECONDARY_CONSTRUCTORS_ARE_NOT_SUPPORTED, "Secondary constructors are not supported"); - put(SUPERTYPE_APPEARS_TWICE, "A supertype appears twice"); - put(FINAL_SUPERTYPE, "This type is final, so it cannot be inherited from"); - - put(ILLEGAL_SELECTOR, "Expression ''{0}'' cannot be a selector (occur after a dot)", TO_STRING); - - put(VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION, "A type annotation is required on a value parameter"); - put(BREAK_OR_CONTINUE_OUTSIDE_A_LOOP, "'break' and 'continue' are only allowed inside a loop"); - put(NOT_A_LOOP_LABEL, "The label ''{0}'' does not denote a loop", TO_STRING); - put(NOT_A_RETURN_LABEL, "The label ''{0}'' does not reference to a context from which we can return", TO_STRING); - - put(ANONYMOUS_INITIALIZER_WITHOUT_CONSTRUCTOR, "Anonymous initializers are only allowed in the presence of a primary constructor"); - put(NULLABLE_SUPERTYPE, "A supertype cannot be nullable"); - put(UNSAFE_CALL, "Only safe calls (?.) are allowed on a nullable receiver of type {0}", RENDER_TYPE); - put(AMBIGUOUS_LABEL, "Ambiguous label"); - put(UNSUPPORTED, "Unsupported [{0}]", TO_STRING); - put(UNNECESSARY_SAFE_CALL, "Unnecessary safe call on a non-null receiver of type {0}", RENDER_TYPE); - put(UNNECESSARY_NOT_NULL_ASSERTION, "Unnecessary non-null assertion (!!) on a non-null receiver of type {0}", RENDER_TYPE); - put(NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER, "{0} does not refer to a type parameter of {1}", new Renderer<JetTypeConstraint>() { - @NotNull - @Override - public String render(@NotNull JetTypeConstraint typeConstraint) { - //noinspection ConstantConditions - return typeConstraint.getSubjectTypeParameterName().getReferencedName(); - } - }, NAME); - put(AUTOCAST_IMPOSSIBLE, "Automatic cast to {0} is impossible, because {1} could have changed since the is-check", RENDER_TYPE, - NAME); - - put(TYPE_MISMATCH_IN_FOR_LOOP, "The loop iterates over values of type {0} but the parameter is declared to be {1}", RENDER_TYPE, - RENDER_TYPE); - put(TYPE_MISMATCH_IN_CONDITION, "Condition must be of type Boolean, but was of type {0}", RENDER_TYPE); - put(TYPE_MISMATCH_IN_TUPLE_PATTERN, "Type mismatch: subject is of type {0} but the pattern is of type Tuple{1}", RENDER_TYPE, - TO_STRING); // TODO: message - put(TYPE_MISMATCH_IN_BINDING_PATTERN, "{0} must be a supertype of {1}. Use 'is' to match against {0}", RENDER_TYPE, RENDER_TYPE); - put(INCOMPATIBLE_TYPES, "Incompatible types: {0} and {1}", RENDER_TYPE, RENDER_TYPE); - put(EXPECTED_CONDITION, "Expected condition of Boolean type"); - - put(CANNOT_CHECK_FOR_ERASED, "Cannot check for instance of erased type: {0}", RENDER_TYPE); - put(UNCHECKED_CAST, "Unchecked cast: {0} to {1}", RENDER_TYPE, RENDER_TYPE); - - put(INCONSISTENT_TYPE_PARAMETER_VALUES, "Type parameter {0} of {1} has inconsistent values: {2}", NAME, DescriptorRenderer.TEXT, - new Renderer<Collection<JetType>>() { - @NotNull - @Override - public String render(@NotNull Collection<JetType> types) { - StringBuilder builder = new StringBuilder(); - for (Iterator<JetType> iterator = types.iterator(); iterator.hasNext(); ) { - JetType jetType = iterator.next(); - builder.append(jetType); - if (iterator.hasNext()) { - builder.append(", "); - } - } - return builder.toString(); - } - }); - - put(EQUALITY_NOT_APPLICABLE, "Operator {0} cannot be applied to {1} and {2}", new Renderer<JetSimpleNameExpression>() { - @NotNull - @Override - public String render(@NotNull JetSimpleNameExpression nameExpression) { - //noinspection ConstantConditions - return nameExpression.getReferencedName(); - } - }, TO_STRING, TO_STRING); - - put(OVERRIDING_FINAL_MEMBER, "''{0}'' in ''{1}'' is final and cannot be overridden", NAME, NAME); - put(CANNOT_WEAKEN_ACCESS_PRIVILEGE, "Cannot weaken access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME); - put(CANNOT_CHANGE_ACCESS_PRIVILEGE, "Cannot change access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME); - - put(RETURN_TYPE_MISMATCH_ON_OVERRIDE, "Return type of {0} is not a subtype of the return type overridden member {1}", - DescriptorRenderer.TEXT, DescriptorRenderer.TEXT); - - put(VAR_OVERRIDDEN_BY_VAL, "Var-property {0} cannot be overridden by val-property {1}", DescriptorRenderer.TEXT, - DescriptorRenderer.TEXT); - - put(ABSTRACT_MEMBER_NOT_IMPLEMENTED, "{0} must be declared abstract or implement abstract member {1}", RENDER_CLASS_OR_OBJECT, - DescriptorRenderer.TEXT); - - put(MANY_IMPL_MEMBER_NOT_IMPLEMENTED, "{0} must override {1} because it inherits many implementations of it", - RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT); - - put(CONFLICTING_OVERLOADS, "{1} is already defined in ''{0}''", DescriptorRenderer.TEXT, TO_STRING); - - - put(RESULT_TYPE_MISMATCH, "{0} must return {1} but returns {2}", TO_STRING, RENDER_TYPE, RENDER_TYPE); - put(UNSAFE_INFIX_CALL, - "Infix call corresponds to a dot-qualified call ''{0}.{1}({2})'' which is not allowed on a nullable receiver ''{0}''. " + - "Use '?.'-qualified call instead", - TO_STRING, TO_STRING, TO_STRING); - - put(OVERLOAD_RESOLUTION_AMBIGUITY, "Overload resolution ambiguity: {0}", AMBIGUOUS_CALLS); - put(NONE_APPLICABLE, "None of the following functions can be called with the arguments supplied: {0}", AMBIGUOUS_CALLS); - put(NO_VALUE_FOR_PARAMETER, "No value passed for parameter {0}", DescriptorRenderer.TEXT); - put(MISSING_RECEIVER, "A receiver of type {0} is required", RENDER_TYPE); - put(NO_RECEIVER_ADMITTED, "No receiver can be passed to this function or property"); - - put(CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS, "Can not create an instance of an abstract class"); - put(TYPE_INFERENCE_FAILED, "Type inference failed: {0}", TO_STRING); - put(WRONG_NUMBER_OF_TYPE_ARGUMENTS, "{0} type arguments expected", new Renderer<Integer>() { - @NotNull - @Override - public String render(@NotNull Integer argument) { - return argument == 0 ? "No" : argument.toString(); - } - }); - - put(UNRESOLVED_IDE_TEMPLATE, "Unresolved IDE template: {0}", TO_STRING); - - put(DANGLING_FUNCTION_LITERAL_ARGUMENT_SUSPECTED, - "This expression is treated as an argument to the function call on the previous line. " + - "Separate it with a semicolon (;) if it is not intended to be an argument."); - - put(NOT_AN_ANNOTATION_CLASS, "{0} is not an annotation class", TO_STRING); - } + private final DiagnosticFactoryToRendererMap map = DefaultErrorMessages.MAP; @NotNull @Override diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java new file mode 100644 index 0000000000000..f9954ace34c5c --- /dev/null +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DefaultErrorMessages.java @@ -0,0 +1,408 @@ +/* + * Copyright 2010-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. + * 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.jet.lang.diagnostics.rendering; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.descriptors.CallableDescriptor; +import org.jetbrains.jet.lang.psi.JetExpression; +import org.jetbrains.jet.lang.psi.JetSimpleNameExpression; +import org.jetbrains.jet.lang.psi.JetTypeConstraint; +import org.jetbrains.jet.lang.resolve.calls.ResolvedCall; +import org.jetbrains.jet.lang.types.JetType; +import org.jetbrains.jet.lexer.JetKeywordToken; +import org.jetbrains.jet.resolve.DescriptorRenderer; + +import java.util.Collection; +import java.util.Iterator; + +import static org.jetbrains.jet.lang.diagnostics.Errors.*; +import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.*; +import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.RENDER_TYPE; +import static org.jetbrains.jet.lang.diagnostics.rendering.Renderers.TO_STRING; + +/** + * @author Evgeny Gerashchenko + * @since 4/13/12 + */ +public class DefaultErrorMessages { + public static final DiagnosticFactoryToRendererMap MAP = new DiagnosticFactoryToRendererMap(); + + private static final Renderer<Collection<? extends ResolvedCall<? extends CallableDescriptor>>> AMBIGUOUS_CALLS = + new Renderer<Collection<? extends ResolvedCall<? extends CallableDescriptor>>>() { + @NotNull + @Override + public String render(@NotNull Collection<? extends ResolvedCall<? extends CallableDescriptor>> argument) { + StringBuilder stringBuilder = new StringBuilder("\n"); + for (ResolvedCall<? extends CallableDescriptor> call : argument) { + stringBuilder.append(DescriptorRenderer.TEXT.render(call.getResultingDescriptor())).append("\n"); + } + return stringBuilder.toString(); + } + }; + + static { + MAP.put(EXCEPTION_WHILE_ANALYZING, "{0}", new Renderer<Throwable>() { + @NotNull + @Override + public String render(@NotNull Throwable e) { + return e.getClass().getSimpleName() + ": " + e.getMessage(); + } + }); + + MAP.put(UNRESOLVED_REFERENCE, "Unresolved reference: {0}", TO_STRING); + + MAP.put(INVISIBLE_REFERENCE, "Cannot access ''{0}'' in ''{1}''", NAME, NAME); + MAP.put(INVISIBLE_MEMBER, "Cannot access ''{0}'' in ''{1}''", NAME, NAME); + + MAP.put(REDECLARATION, "Redeclaration: {0}", NAME); + MAP.put(NAME_SHADOWING, "Name shadowed: {0}", NAME); + + MAP.put(TYPE_MISMATCH, "Type mismatch: inferred type is {1} but {0} was expected", RENDER_TYPE, RENDER_TYPE); + MAP.put(INCOMPATIBLE_MODIFIERS, "Incompatible modifiers: ''{0}''", new Renderer<Collection<JetKeywordToken>>() { + @NotNull + @Override + public String render(@NotNull Collection<JetKeywordToken> tokens) { + StringBuilder sb = new StringBuilder(); + for (Iterator<JetKeywordToken> iterator = tokens.iterator(); iterator.hasNext(); ) { + JetKeywordToken modifier = iterator.next(); + sb.append(modifier.getValue()); + if (iterator.hasNext()) { + sb.append(" "); + } + } + return sb.toString(); + } + }); + MAP.put(ILLEGAL_MODIFIER, "Illegal modifier ''{0}''", TO_STRING); + + MAP.put(REDUNDANT_MODIFIER, "Modifier {0} is redundant because {1} is present", TO_STRING, TO_STRING); + MAP.put(ABSTRACT_MODIFIER_IN_TRAIT, "Modifier ''abstract'' is redundant in trait"); + MAP.put(OPEN_MODIFIER_IN_TRAIT, "Modifier ''open'' is redundant in trait"); + MAP.put(REDUNDANT_MODIFIER_IN_GETTER, "Visibility modifiers are redundant in getter"); + MAP.put(TRAIT_CAN_NOT_BE_FINAL, "Trait can not be final"); + MAP.put(TYPECHECKER_HAS_RUN_INTO_RECURSIVE_PROBLEM, + "Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly"); // TODO: message + MAP.put(RETURN_NOT_ALLOWED, "'return' is not allowed here"); + MAP.put(PROJECTION_IN_IMMEDIATE_ARGUMENT_TO_SUPERTYPE, "Projections are not allowed for immediate arguments of a supertype"); + MAP.put(LABEL_NAME_CLASH, "There is more than one label with such a name in this scope"); + MAP.put(EXPRESSION_EXPECTED_NAMESPACE_FOUND, "Expression expected, but a namespace name found"); + + MAP.put(CANNOT_IMPORT_FROM_ELEMENT, "Cannot import from ''{0}''", NAME); + MAP.put(CANNOT_BE_IMPORTED, "Cannot import ''{0}'', functions and properties can be imported only from packages", NAME); + MAP.put(USELESS_HIDDEN_IMPORT, "Useless import, it is hidden further"); + MAP.put(USELESS_SIMPLE_IMPORT, "Useless import, does nothing"); + + MAP.put(CANNOT_INFER_PARAMETER_TYPE, + "Cannot infer a type for this parameter. To specify it explicitly use the {(p : Type) => ...} notation"); + + MAP.put(NO_BACKING_FIELD_ABSTRACT_PROPERTY, "This property doesn't have a backing field, because it's abstract"); + MAP.put(NO_BACKING_FIELD_CUSTOM_ACCESSORS, + "This property doesn't have a backing field, because it has custom accessors without reference to the backing field"); + MAP.put(INACCESSIBLE_BACKING_FIELD, "The backing field is not accessible here"); + MAP.put(NOT_PROPERTY_BACKING_FIELD, "The referenced variable is not a property and doesn't have backing field"); + + MAP.put(MIXING_NAMED_AND_POSITIONED_ARGUMENTS, "Mixing named and positioned arguments in not allowed"); + MAP.put(ARGUMENT_PASSED_TWICE, "An argument is already passed for this parameter"); + MAP.put(NAMED_PARAMETER_NOT_FOUND, "Cannot find a parameter with this name: {0}", TO_STRING); + MAP.put(VARARG_OUTSIDE_PARENTHESES, "Passing value as a vararg is only allowed inside a parenthesized argument list"); + MAP.put(NON_VARARG_SPREAD, "The spread operator (*foo) may only be applied in a vararg position"); + + MAP.put(MANY_FUNCTION_LITERAL_ARGUMENTS, "Only one function literal is allowed outside a parenthesized argument list"); + MAP.put(PROPERTY_WITH_NO_TYPE_NO_INITIALIZER, "This property must either have a type annotation or be initialized"); + + MAP.put(ABSTRACT_PROPERTY_IN_PRIMARY_CONSTRUCTOR_PARAMETERS, "This property cannot be declared abstract"); + MAP.put(ABSTRACT_PROPERTY_NOT_IN_CLASS, "A property may be abstract only when defined in a class or trait"); + MAP.put(ABSTRACT_PROPERTY_WITH_INITIALIZER, "Property with initializer cannot be abstract"); + MAP.put(ABSTRACT_PROPERTY_WITH_GETTER, "Property with getter implementation cannot be abstract"); + MAP.put(ABSTRACT_PROPERTY_WITH_SETTER, "Property with setter implementation cannot be abstract"); + + MAP.put(PACKAGE_MEMBER_CANNOT_BE_PROTECTED, "Package member cannot be protected"); + + MAP.put(GETTER_VISIBILITY_DIFFERS_FROM_PROPERTY_VISIBILITY, "Getter visibility must be the same as property visibility"); + MAP.put(BACKING_FIELD_IN_TRAIT, "Property in a trait cannot have a backing field"); + MAP.put(MUST_BE_INITIALIZED, "Property must be initialized"); + MAP.put(MUST_BE_INITIALIZED_OR_BE_ABSTRACT, "Property must be initialized or be abstract"); + MAP.put(PROPERTY_INITIALIZER_IN_TRAIT, "Property initializers are not allowed in traits"); + MAP.put(PROPERTY_INITIALIZER_NO_BACKING_FIELD, "Initializer is not allowed here because this property has no backing field"); + MAP.put(ABSTRACT_PROPERTY_IN_NON_ABSTRACT_CLASS, "Abstract property {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING); + MAP.put(ABSTRACT_FUNCTION_IN_NON_ABSTRACT_CLASS, "Abstract function {0} in non-abstract class {1}", TO_STRING, TO_STRING, TO_STRING); + MAP.put(ABSTRACT_FUNCTION_WITH_BODY, "A function {0} with body cannot be abstract", TO_STRING); + MAP.put(NON_ABSTRACT_FUNCTION_WITH_NO_BODY, "Method {0} without a body must be abstract", TO_STRING); + MAP.put(NON_MEMBER_ABSTRACT_FUNCTION, "Function {0} is not a class or trait member and cannot be abstract", TO_STRING); + + MAP.put(NON_MEMBER_FUNCTION_NO_BODY, "Function {0} must have a body", TO_STRING); + MAP.put(NON_FINAL_MEMBER_IN_FINAL_CLASS, "Non final member in a final class"); + + MAP.put(PUBLIC_MEMBER_SHOULD_SPECIFY_TYPE, "Public or protected member should specify a type"); + + MAP.put(PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT, + "Projections are not allowed on type arguments of functions and properties"); // TODO : better positioning + MAP.put(SUPERTYPE_NOT_INITIALIZED, "This type has a constructor, and thus must be initialized here"); + MAP.put(SUPERTYPE_NOT_INITIALIZED_DEFAULT, "Constructor invocation should be explicitly specified"); + MAP.put(SECONDARY_CONSTRUCTOR_BUT_NO_PRIMARY, "A secondary constructor may appear only in a class that has a primary constructor"); + MAP.put(SECONDARY_CONSTRUCTOR_NO_INITIALIZER_LIST, "Secondary constructors must have an initializer list"); + MAP.put(BY_IN_SECONDARY_CONSTRUCTOR, "'by'-clause is only supported for primary constructors"); + MAP.put(INITIALIZER_WITH_NO_ARGUMENTS, "Constructor arguments required"); + MAP.put(MANY_CALLS_TO_THIS, "Only one call to 'this(...)' is allowed"); + MAP.put(NOTHING_TO_OVERRIDE, "{0} overrides nothing", DescriptorRenderer.TEXT); + MAP.put(VIRTUAL_MEMBER_HIDDEN, "''{0}'' hides ''{1}'' in class {2} and needs 'override' modifier", DescriptorRenderer.TEXT, + DescriptorRenderer.TEXT, DescriptorRenderer.TEXT); + + MAP.put(ENUM_ENTRY_SHOULD_BE_INITIALIZED, "Missing delegation specifier ''{0}''", NAME); + MAP.put(ENUM_ENTRY_ILLEGAL_TYPE, "The type constructor of enum entry should be ''{0}''", NAME); + + MAP.put(UNINITIALIZED_VARIABLE, "Variable ''{0}'' must be initialized", NAME); + MAP.put(UNINITIALIZED_PARAMETER, "Parameter ''{0}'' is uninitialized here", NAME); + MAP.put(UNUSED_VARIABLE, "Variable ''{0}'' is never used", NAME); + MAP.put(UNUSED_PARAMETER, "Parameter ''{0}'' is never used", NAME); + MAP.put(ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE, "Variable ''{0}'' is assigned but never accessed", NAME); + MAP.put(VARIABLE_WITH_REDUNDANT_INITIALIZER, "Variable ''{0}'' initializer is redundant", NAME); + MAP.put(UNUSED_VALUE, "The value ''{0}'' assigned to ''{1}'' is never used", ELEMENT_TEXT, TO_STRING); + MAP.put(UNUSED_CHANGED_VALUE, "The value changed at ''{0}'' is never used", ELEMENT_TEXT); + MAP.put(UNUSED_EXPRESSION, "The expression is unused"); + MAP.put(UNUSED_FUNCTION_LITERAL, "The function literal is unused. If you mean block, you can use 'run { ... }'"); + + MAP.put(VAL_REASSIGNMENT, "Val can not be reassigned", NAME); + MAP.put(INITIALIZATION_BEFORE_DECLARATION, "Variable cannot be initialized before declaration", NAME); + MAP.put(VARIABLE_EXPECTED, "Variable expected"); + + MAP.put(INITIALIZATION_USING_BACKING_FIELD_CUSTOM_SETTER, + "This property has a custom setter, so initialization using backing field required", NAME); + MAP.put(INITIALIZATION_USING_BACKING_FIELD_OPEN_SETTER, + "Setter of this property can be overridden, so initialization using backing field required", NAME); + + MAP.put(FUNCTION_PARAMETERS_OF_INLINE_FUNCTION, "Function parameters of inline function can only be invoked", NAME); + + MAP.put(UNREACHABLE_CODE, "Unreachable code"); + + MAP.put(MANY_CLASS_OBJECTS, "Only one class object is allowed per class"); + MAP.put(CLASS_OBJECT_NOT_ALLOWED, "A class object is not allowed here"); + MAP.put(DELEGATION_IN_TRAIT, "Traits cannot use delegation"); + MAP.put(DELEGATION_NOT_TO_TRAIT, "Only traits can be delegated to"); + MAP.put(NO_CONSTRUCTOR, "This class does not have a constructor"); + MAP.put(NOT_A_CLASS, "Not a class"); + MAP.put(ILLEGAL_ESCAPE_SEQUENCE, "Illegal escape sequence"); + + MAP.put(LOCAL_EXTENSION_PROPERTY, "Local extension properties are not allowed"); + MAP.put(LOCAL_VARIABLE_WITH_GETTER, "Local variables are not allowed to have getters"); + MAP.put(LOCAL_VARIABLE_WITH_SETTER, "Local variables are not allowed to have setters"); + MAP.put(VAL_WITH_SETTER, "A 'val'-property cannot have a setter"); + + MAP.put(NO_GET_METHOD, "No get method providing array access"); + MAP.put(NO_SET_METHOD, "No set method providing array access"); + + MAP.put(INC_DEC_SHOULD_NOT_RETURN_UNIT, "Functions inc(), dec() shouldn't return Unit to be used by operators ++, --"); + MAP.put(ASSIGNMENT_OPERATOR_SHOULD_RETURN_UNIT, "Function ''{0}'' should return Unit to be used by corresponding operator ''{1}''", + NAME, ELEMENT_TEXT); + MAP.put(ASSIGN_OPERATOR_AMBIGUITY, "Assignment operators ambiguity: {0}", AMBIGUOUS_CALLS); + + MAP.put(EQUALS_MISSING, "No method 'equals(Any?) : Boolean' available"); + MAP.put(ASSIGNMENT_IN_EXPRESSION_CONTEXT, "Assignments are not expressions, and only expressions are allowed in this context"); + MAP.put(NAMESPACE_IS_NOT_AN_EXPRESSION, "'namespace' is not an expression, it can only be used on the left-hand side of a dot ('.')"); + MAP.put(SUPER_IS_NOT_AN_EXPRESSION, "{0} is not an expression, it can only be used on the left-hand side of a dot ('.')", TO_STRING); + MAP.put(DECLARATION_IN_ILLEGAL_CONTEXT, "Declarations are not allowed in this position"); + MAP.put(SETTER_PARAMETER_WITH_DEFAULT_VALUE, "Setter parameters can not have default values"); + MAP.put(NO_THIS, "'this' is not defined in this context"); + MAP.put(SUPER_NOT_AVAILABLE, "No supertypes are accessible in this context"); + MAP.put(AMBIGUOUS_SUPER, "Many supertypes available, please specify the one you mean in angle brackets, e.g. 'super<Foo>'"); + MAP.put(ABSTRACT_SUPER_CALL, "Abstract member cannot be accessed directly"); + MAP.put(NOT_A_SUPERTYPE, "Not a supertype"); + MAP.put(TYPE_ARGUMENTS_REDUNDANT_IN_SUPER_QUALIFIER, "Type arguments do not need to be specified in a 'super' qualifier"); + MAP.put(USELESS_CAST_STATIC_ASSERT_IS_FINE, "No cast needed, use ':' instead"); + MAP.put(USELESS_CAST, "No cast needed"); + MAP.put(CAST_NEVER_SUCCEEDS, "This cast can never succeed"); + MAP.put(WRONG_SETTER_PARAMETER_TYPE, "Setter parameter type must be equal to the type of the property, i.e. {0}", RENDER_TYPE); + MAP.put(WRONG_GETTER_RETURN_TYPE, "Getter return type must be equal to the type of the property, i.e. {0}", RENDER_TYPE); + MAP.put(NO_CLASS_OBJECT, "Please specify constructor invocation; classifier {0} does not have a class object", NAME); + MAP.put(NO_GENERICS_IN_SUPERTYPE_SPECIFIER, "Generic arguments of the base type must be specified"); + + MAP.put(HAS_NEXT_PROPERTY_AND_FUNCTION_AMBIGUITY, + "An ambiguity between 'iterator().hasNext()' function and 'iterator().hasNext' property"); + MAP.put(HAS_NEXT_MISSING, "Loop range must have an 'iterator().hasNext()' function or an 'iterator().hasNext' property"); + MAP.put(HAS_NEXT_FUNCTION_AMBIGUITY, "Function 'iterator().hasNext()' is ambiguous for this expression"); + MAP.put(HAS_NEXT_MUST_BE_READABLE, "The 'iterator().hasNext' property of the loop range must be readable"); + MAP.put(HAS_NEXT_PROPERTY_TYPE_MISMATCH, "The 'iterator().hasNext' property of the loop range must return Boolean, but returns {0}", + RENDER_TYPE); + MAP.put(HAS_NEXT_FUNCTION_TYPE_MISMATCH, "The 'iterator().hasNext()' function of the loop range must return Boolean, but returns {0}", + RENDER_TYPE); + MAP.put(NEXT_AMBIGUITY, "Function 'iterator().next()' is ambiguous for this expression"); + MAP.put(NEXT_MISSING, "Loop range must have an 'iterator().next()' function"); + MAP.put(ITERATOR_MISSING, "For-loop range must have an iterator() method"); + MAP.put(ITERATOR_AMBIGUITY, "Method 'iterator()' is ambiguous for this expression: {0}", AMBIGUOUS_CALLS); + + MAP.put(COMPARE_TO_TYPE_MISMATCH, "compareTo() must return Int, but returns {0}", RENDER_TYPE); + MAP.put(CALLEE_NOT_A_FUNCTION, "Expecting a function type, but found {0}", RENDER_TYPE); + + MAP.put(RETURN_IN_FUNCTION_WITH_EXPRESSION_BODY, + "Returns are not allowed for functions with expression body. Use block body in '{...}'"); + MAP.put(NO_RETURN_IN_FUNCTION_WITH_BLOCK_BODY, "A 'return' expression required in a function with a block body ('{...}')"); + MAP.put(RETURN_TYPE_MISMATCH, "This function must return a value of type {0}", RENDER_TYPE); + MAP.put(EXPECTED_TYPE_MISMATCH, "Expected a value of type {0}", RENDER_TYPE); + MAP.put(ASSIGNMENT_TYPE_MISMATCH, + "Expected a value of type {0}. Assignment operation is not an expression, so it does not return any value", RENDER_TYPE); + MAP.put(IMPLICIT_CAST_TO_UNIT_OR_ANY, "Type was casted to ''{0}''. Please specify ''{0}'' as expected type, if you mean such cast", + RENDER_TYPE); + MAP.put(EXPRESSION_EXPECTED, "{0} is not an expression, and only expression are allowed here", new Renderer<JetExpression>() { + @NotNull + @Override + public String render(@NotNull JetExpression expression) { + String expressionType = expression.toString(); + return expressionType.substring(0, 1) + + expressionType.substring(1).toLowerCase(); + } + }); + + MAP.put(UPPER_BOUND_VIOLATED, "An upper bound {0} is violated", RENDER_TYPE); // TODO : Message + MAP.put(FINAL_CLASS_OBJECT_UPPER_BOUND, "{0} is a final type, and thus a class object cannot extend it", RENDER_TYPE); + MAP.put(FINAL_UPPER_BOUND, "{0} is a final type, and thus a value of the type parameter is predetermined", RENDER_TYPE); + MAP.put(USELESS_ELVIS, "Elvis operator (?:) always returns the left operand of non-nullable type {0}", RENDER_TYPE); + MAP.put(CONFLICTING_UPPER_BOUNDS, "Upper bounds of {0} have empty intersection", NAME); + MAP.put(CONFLICTING_CLASS_OBJECT_UPPER_BOUNDS, "Class object upper bounds of {0} have empty intersection", NAME); + + MAP.put(TOO_MANY_ARGUMENTS, "Too many arguments for {0}", TO_STRING); + MAP.put(ERROR_COMPILE_TIME_VALUE, "{0}", TO_STRING); + + MAP.put(ELSE_MISPLACED_IN_WHEN, "'else' entry must be the last one in a when-expression"); + + MAP.put(NO_ELSE_IN_WHEN, "'when' expression must contain 'else' branch"); + MAP.put(TYPE_MISMATCH_IN_RANGE, "Type mismatch: incompatible types of range and element checked in it"); + MAP.put(CYCLIC_INHERITANCE_HIERARCHY, "There's a cycle in the inheritance hierarchy for this type"); + + MAP.put(MANY_CLASSES_IN_SUPERTYPE_LIST, "Only one class may appear in a supertype list"); + MAP.put(SUPERTYPE_NOT_A_CLASS_OR_TRAIT, "Only classes and traits may serve as supertypes"); + MAP.put(SUPERTYPE_INITIALIZED_IN_TRAIT, "Traits cannot initialize supertypes"); + MAP.put(CONSTRUCTOR_IN_TRAIT, "A trait may not have a constructor"); + MAP.put(SECONDARY_CONSTRUCTORS_ARE_NOT_SUPPORTED, "Secondary constructors are not supported"); + MAP.put(SUPERTYPE_APPEARS_TWICE, "A supertype appears twice"); + MAP.put(FINAL_SUPERTYPE, "This type is final, so it cannot be inherited from"); + + MAP.put(ILLEGAL_SELECTOR, "Expression ''{0}'' cannot be a selector (occur after a dot)", TO_STRING); + + MAP.put(VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION, "A type annotation is required on a value parameter"); + MAP.put(BREAK_OR_CONTINUE_OUTSIDE_A_LOOP, "'break' and 'continue' are only allowed inside a loop"); + MAP.put(NOT_A_LOOP_LABEL, "The label ''{0}'' does not denote a loop", TO_STRING); + MAP.put(NOT_A_RETURN_LABEL, "The label ''{0}'' does not reference to a context from which we can return", TO_STRING); + + MAP.put(ANONYMOUS_INITIALIZER_WITHOUT_CONSTRUCTOR, "Anonymous initializers are only allowed in the presence of a primary constructor"); + MAP.put(NULLABLE_SUPERTYPE, "A supertype cannot be nullable"); + MAP.put(UNSAFE_CALL, "Only safe calls (?.) are allowed on a nullable receiver of type {0}", RENDER_TYPE); + MAP.put(AMBIGUOUS_LABEL, "Ambiguous label"); + MAP.put(UNSUPPORTED, "Unsupported [{0}]", TO_STRING); + MAP.put(UNNECESSARY_SAFE_CALL, "Unnecessary safe call on a non-null receiver of type {0}", RENDER_TYPE); + MAP.put(UNNECESSARY_NOT_NULL_ASSERTION, "Unnecessary non-null assertion (!!) on a non-null receiver of type {0}", RENDER_TYPE); + MAP.put(NAME_IN_CONSTRAINT_IS_NOT_A_TYPE_PARAMETER, "{0} does not refer to a type parameter of {1}", new Renderer<JetTypeConstraint>() { + @NotNull + @Override + public String render(@NotNull JetTypeConstraint typeConstraint) { + //noinspection ConstantConditions + return typeConstraint.getSubjectTypeParameterName().getReferencedName(); + } + }, NAME); + MAP.put(AUTOCAST_IMPOSSIBLE, "Automatic cast to {0} is impossible, because {1} could have changed since the is-check", RENDER_TYPE, + NAME); + + MAP.put(TYPE_MISMATCH_IN_FOR_LOOP, "The loop iterates over values of type {0} but the parameter is declared to be {1}", RENDER_TYPE, + RENDER_TYPE); + MAP.put(TYPE_MISMATCH_IN_CONDITION, "Condition must be of type Boolean, but was of type {0}", RENDER_TYPE); + MAP.put(TYPE_MISMATCH_IN_TUPLE_PATTERN, "Type mismatch: subject is of type {0} but the pattern is of type Tuple{1}", RENDER_TYPE, + TO_STRING); // TODO: message + MAP.put(TYPE_MISMATCH_IN_BINDING_PATTERN, "{0} must be a supertype of {1}. Use 'is' to match against {0}", RENDER_TYPE, RENDER_TYPE); + MAP.put(INCOMPATIBLE_TYPES, "Incompatible types: {0} and {1}", RENDER_TYPE, RENDER_TYPE); + MAP.put(EXPECTED_CONDITION, "Expected condition of Boolean type"); + + MAP.put(CANNOT_CHECK_FOR_ERASED, "Cannot check for instance of erased type: {0}", RENDER_TYPE); + MAP.put(UNCHECKED_CAST, "Unchecked cast: {0} to {1}", RENDER_TYPE, RENDER_TYPE); + + MAP.put(INCONSISTENT_TYPE_PARAMETER_VALUES, "Type parameter {0} of {1} has inconsistent values: {2}", NAME, DescriptorRenderer.TEXT, + new Renderer<Collection<JetType>>() { + @NotNull + @Override + public String render(@NotNull Collection<JetType> types) { + StringBuilder builder = new StringBuilder(); + for (Iterator<JetType> iterator = types.iterator(); iterator.hasNext(); ) { + JetType jetType = iterator.next(); + builder.append(jetType); + if (iterator.hasNext()) { + builder.append(", "); + } + } + return builder.toString(); + } + }); + + MAP.put(EQUALITY_NOT_APPLICABLE, "Operator {0} cannot be applied to {1} and {2}", new Renderer<JetSimpleNameExpression>() { + @NotNull + @Override + public String render(@NotNull JetSimpleNameExpression nameExpression) { + //noinspection ConstantConditions + return nameExpression.getReferencedName(); + } + }, TO_STRING, TO_STRING); + + MAP.put(OVERRIDING_FINAL_MEMBER, "''{0}'' in ''{1}'' is final and cannot be overridden", NAME, NAME); + MAP.put(CANNOT_WEAKEN_ACCESS_PRIVILEGE, "Cannot weaken access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME); + MAP.put(CANNOT_CHANGE_ACCESS_PRIVILEGE, "Cannot change access privilege ''{0}'' for ''{1}'' in ''{2}''", TO_STRING, NAME, NAME); + + MAP.put(RETURN_TYPE_MISMATCH_ON_OVERRIDE, "Return type of {0} is not a subtype of the return type overridden member {1}", + DescriptorRenderer.TEXT, DescriptorRenderer.TEXT); + + MAP.put(VAR_OVERRIDDEN_BY_VAL, "Var-property {0} cannot be overridden by val-property {1}", DescriptorRenderer.TEXT, + DescriptorRenderer.TEXT); + + MAP.put(ABSTRACT_MEMBER_NOT_IMPLEMENTED, "{0} must be declared abstract or implement abstract member {1}", RENDER_CLASS_OR_OBJECT, + DescriptorRenderer.TEXT); + + MAP.put(MANY_IMPL_MEMBER_NOT_IMPLEMENTED, "{0} must override {1} because it inherits many implementations of it", + RENDER_CLASS_OR_OBJECT, DescriptorRenderer.TEXT); + + MAP.put(CONFLICTING_OVERLOADS, "{1} is already defined in ''{0}''", DescriptorRenderer.TEXT, TO_STRING); + + + MAP.put(RESULT_TYPE_MISMATCH, "{0} must return {1} but returns {2}", TO_STRING, RENDER_TYPE, RENDER_TYPE); + MAP.put(UNSAFE_INFIX_CALL, + "Infix call corresponds to a dot-qualified call ''{0}.{1}({2})'' which is not allowed on a nullable receiver ''{0}''. " + + "Use '?.'-qualified call instead", + TO_STRING, TO_STRING, TO_STRING); + + MAP.put(OVERLOAD_RESOLUTION_AMBIGUITY, "Overload resolution ambiguity: {0}", AMBIGUOUS_CALLS); + MAP.put(NONE_APPLICABLE, "None of the following functions can be called with the arguments supplied: {0}", AMBIGUOUS_CALLS); + MAP.put(NO_VALUE_FOR_PARAMETER, "No value passed for parameter {0}", DescriptorRenderer.TEXT); + MAP.put(MISSING_RECEIVER, "A receiver of type {0} is required", RENDER_TYPE); + MAP.put(NO_RECEIVER_ADMITTED, "No receiver can be passed to this function or property"); + + MAP.put(CREATING_AN_INSTANCE_OF_ABSTRACT_CLASS, "Can not create an instance of an abstract class"); + MAP.put(TYPE_INFERENCE_FAILED, "Type inference failed: {0}", TO_STRING); + MAP.put(WRONG_NUMBER_OF_TYPE_ARGUMENTS, "{0} type arguments expected", new Renderer<Integer>() { + @NotNull + @Override + public String render(@NotNull Integer argument) { + return argument == 0 ? "No" : argument.toString(); + } + }); + + MAP.put(UNRESOLVED_IDE_TEMPLATE, "Unresolved IDE template: {0}", TO_STRING); + + MAP.put(DANGLING_FUNCTION_LITERAL_ARGUMENT_SUSPECTED, + "This expression is treated as an argument to the function call on the previous line. " + + "Separate it with a semicolon (;) if it is not intended to be an argument."); + + MAP.put(NOT_AN_ANNOTATION_CLASS, "{0} is not an annotation class", TO_STRING); + } + + private DefaultErrorMessages() { + } +} diff --git a/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticFactoryToRendererMap.java b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticFactoryToRendererMap.java new file mode 100644 index 0000000000000..3172e3f914400 --- /dev/null +++ b/compiler/frontend/src/org/jetbrains/jet/lang/diagnostics/rendering/DiagnosticFactoryToRendererMap.java @@ -0,0 +1,62 @@ +/* + * Copyright 2010-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. + * 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.jet.lang.diagnostics.rendering; + +import com.intellij.psi.PsiElement; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.lang.diagnostics.*; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author Evgeny Gerashchenko + * @since 4/13/12 + */ +public class DiagnosticFactoryToRendererMap { + private final Map<AbstractDiagnosticFactory, DiagnosticRenderer<?>> map = + new HashMap<AbstractDiagnosticFactory, DiagnosticRenderer<?>>(); + + public final <E extends PsiElement> void put(SimpleDiagnosticFactory<E> factory, String message) { + map.put(factory, new SimpleDiagnosticRenderer(message)); + } + + public final <E extends PsiElement, A> void put(DiagnosticFactory1<E, A> factory, String message, Renderer<? super A> rendererA) { + map.put(factory, new DiagnosticWithParameters1Renderer<A>(message, rendererA)); + } + + public final <E extends PsiElement, A, B> void put(DiagnosticFactory2<E, A, B> factory, + String message, + Renderer<? super A> rendererA, + Renderer<? super B> rendererB) { + map.put(factory, new DiagnosticWithParameters2Renderer<A, B>(message, rendererA, rendererB)); + } + + public final <E extends PsiElement, A, B, C> void put(DiagnosticFactory3<E, A, B, C> factory, + String message, + Renderer<? super A> rendererA, + Renderer<? super B> rendererB, + Renderer<? super C> rendererC) { + map.put(factory, new DiagnosticWithParameters3Renderer<A, B, C>(message, rendererA, rendererB, rendererC)); + } + + @Nullable + public final DiagnosticRenderer<?> get(@NotNull AbstractDiagnosticFactory factory) { + return map.get(factory); + } +}
40622f0031683d55f12f476f07076021f64bf5b2
aeshell$aesh
changed how the inputstream is read. using ConsoleInputSession with the possibility to read several chars at the same time, making support for arrow keys in vi-mode.
a
https://github.com/aeshell/aesh
diff --git a/src/main/java/Example.java b/src/main/java/Example.java index f6921ff21..34027ffd5 100644 --- a/src/main/java/Example.java +++ b/src/main/java/Example.java @@ -59,6 +59,11 @@ else if(line.equals("foobar")) { break; } } + + try { + console.stop(); + } catch (Exception e) { + } } } diff --git a/src/main/java/org/jboss/jreadline/console/Buffer.java b/src/main/java/org/jboss/jreadline/console/Buffer.java index ec5e4703f..05c62dced 100644 --- a/src/main/java/org/jboss/jreadline/console/Buffer.java +++ b/src/main/java/org/jboss/jreadline/console/Buffer.java @@ -222,6 +222,9 @@ private int moveCursor(final int move, boolean viMode) { } // dont move out of bounds + if(getCursor() + move <= 0) + return -getCursor(); + if(viMode) { if(getCursor() + move > line.length()-1) return (line.length()-1-getCursor()); @@ -231,9 +234,6 @@ private int moveCursor(final int move, boolean viMode) { return (line.length()-getCursor()); } - if(getCursor() + move < 0) - return -getCursor(); - return move; } diff --git a/src/main/java/org/jboss/jreadline/console/Console.java b/src/main/java/org/jboss/jreadline/console/Console.java index 48d005ad4..f21871da7 100644 --- a/src/main/java/org/jboss/jreadline/console/Console.java +++ b/src/main/java/org/jboss/jreadline/console/Console.java @@ -38,7 +38,6 @@ /** * A console reader. * Supports ansi terminals - * TODO: need a config setup * * @author Ståle W. Pedersen <[email protected]> */ @@ -59,7 +58,7 @@ public class Console { private boolean displayCompletion = false; private boolean askDisplayCompletion = false; - private Logger logger; + private Logger logger = LoggerUtil.getLogger(getClass().getName()); public Console() throws IOException { this(Settings.getInstance()); @@ -87,7 +86,6 @@ public Console(Settings settings) throws IOException { completionList = new ArrayList<Completion>(); this.settings = settings; - logger = LoggerUtil.getLogger(getClass().getName()); } private void setTerminal(Terminal term, InputStream in, OutputStream out) { @@ -129,6 +127,14 @@ public void addCompletions(List<Completion> completionList) { this.completionList.addAll(completionList); } + public void stop() throws IOException { + settings.getInputStream().close(); + //setting it to null to prevent uncertain state + settings.setInputStream(null); + terminal.reset(); + terminal = null; + } + public String read(String prompt) throws IOException { buffer.reset(prompt); terminal.write(buffer.getPrompt()); @@ -137,19 +143,19 @@ public String read(String prompt) throws IOException { while(true) { - int c = terminal.read(); + int[] in = terminal.read(settings.isReadAhead()); //System.out.println("got int:"+c); - if (c == -1) { + if (in[0] == -1) { return null; } - Operation operation = editMode.parseInput(c); + Operation operation = editMode.parseInput(in); Action action = operation.getAction(); if(askDisplayCompletion) { askDisplayCompletion = false; - if('y' == (char) c) { + if('y' == (char) in[0]) { displayCompletion = true; complete(); } @@ -162,7 +168,7 @@ public String read(String prompt) throws IOException { } } else if (action == Action.EDIT) { - writeChar(c); + writeChar(in[0]); } // For search movement is used a bit differently. // It only triggers what kind of search action thats performed @@ -204,7 +210,7 @@ else if(action == Action.SEARCH && !settings.isHistoryDisabled()) { break; // new search input, append to search case ALL: - searchTerm.appendCodePoint(c); + searchTerm.appendCodePoint(in[0]); //check if the new searchTerm will find anything String tmpResult = history.search(searchTerm.toString()); // @@ -361,7 +367,6 @@ private void getHistoryElement(boolean first) throws IOException { if(fromHistory.length() > getTerminalWidth() && fromHistory.length() > buffer.getLine().length()) { int currentRow = getCurrentRow(); - //logger.info("Current row: "+currentRow); if(currentRow > -1) { int cursorRow = buffer.getCursorWithPrompt() / getTerminalWidth(); if(currentRow + (fromHistory.length() / getTerminalWidth()) - cursorRow >= getTerminalHeight()) { @@ -751,7 +756,8 @@ private int getCurrentRow() { terminal.write(Buffer.printAnsi("6n")); StringBuilder builder = new StringBuilder(8); int row; - while((row = settings.getInputStream().read()) > -1 && row != 'R') { + while((row = terminal.read(false)[0]) > -1 && row != 'R') { + //while((row = settings.getInputStream().read()) > -1 && row != 'R') { //while((row = settings.getInputStream().read()) > -1 && row != 'R' && row != ';') { if (row != 27 && row != '[') { builder.append((char) row); diff --git a/src/main/java/org/jboss/jreadline/console/reader/CharInputStreamReader.java b/src/main/java/org/jboss/jreadline/console/reader/CharInputStreamReader.java deleted file mode 100644 index 43f1b7b08..000000000 --- a/src/main/java/org/jboss/jreadline/console/reader/CharInputStreamReader.java +++ /dev/null @@ -1,339 +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.jboss.jreadline.console.reader; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CoderResult; -import java.nio.charset.CodingErrorAction; -import java.nio.charset.MalformedInputException; -import java.nio.charset.UnmappableCharacterException; - - -/** - * NOTE: This is a copy of the InputStreamWriter from Apache Harmony - * - * A class for turning a byte stream into a character stream. Data read from the - * source input stream is converted into characters by either a default or a - * provided character converter. The default encoding is taken from the - * "file.encoding" system property. {@code InputStreamReader} contains a buffer - * of bytes read from the source stream and converts these into characters as - * needed. The buffer size is 8K. - * - * @see OutputStreamWriter - */ -public class CharInputStreamReader extends Reader { - private InputStream in; - - private static final int BUFFER_SIZE = 8192; - - private boolean endOfInput = false; - - String encoding; - - CharsetDecoder decoder; - - ByteBuffer bytes = ByteBuffer.allocate(BUFFER_SIZE); - - /** - * Constructs a new {@code InputStreamReader} on the {@link InputStream} - * {@code in}. This constructor sets the character converter to the encoding - * specified in the "file.encoding" property and falls back to ISO 8859_1 - * (ISO-Latin-1) if the property doesn't exist. - * - * @param in - * the input stream from which to read characters. - */ - public CharInputStreamReader(InputStream in) { - super(in); - this.in = in; - encoding = System.getProperty("file.encoding", "ISO8859_1"); //$NON-NLS-1$//$NON-NLS-2$ - decoder = Charset.forName(encoding).newDecoder().onMalformedInput( - CodingErrorAction.REPLACE).onUnmappableCharacter( - CodingErrorAction.REPLACE); - bytes.limit(0); - } - - /** - * Constructs a new InputStreamReader on the InputStream {@code in}. The - * character converter that is used to decode bytes into characters is - * identified by name by {@code enc}. If the encoding cannot be found, an - * UnsupportedEncodingException error is thrown. - * - * @param in - * the InputStream from which to read characters. - * @param enc - * identifies the character converter to use. - * @throws NullPointerException - * if {@code enc} is {@code null}. - * @throws UnsupportedEncodingException - * if the encoding specified by {@code enc} cannot be found. - */ - public CharInputStreamReader(InputStream in, final String enc) - throws UnsupportedEncodingException { - super(in); - if (enc == null) { - throw new NullPointerException(); - } - this.in = in; - try { - decoder = Charset.forName(enc).newDecoder().onMalformedInput( - CodingErrorAction.REPLACE).onUnmappableCharacter( - CodingErrorAction.REPLACE); - } catch (IllegalArgumentException e) { - throw (UnsupportedEncodingException) - new UnsupportedEncodingException(enc).initCause(e); - } - bytes.limit(0); - } - - /** - * Constructs a new InputStreamReader on the InputStream {@code in} and - * CharsetDecoder {@code dec}. - * - * @param in - * the source InputStream from which to read characters. - * @param dec - * the CharsetDecoder used by the character conversion. - */ - public CharInputStreamReader(InputStream in, CharsetDecoder dec) { - super(in); - dec.averageCharsPerByte(); - this.in = in; - decoder = dec; - bytes.limit(0); - } - - /** - * Constructs a new InputStreamReader on the InputStream {@code in} and - * Charset {@code charset}. - * - * @param in - * the source InputStream from which to read characters. - * @param charset - * the Charset that defines the character converter - */ - public CharInputStreamReader(InputStream in, Charset charset) { - super(in); - this.in = in; - decoder = charset.newDecoder().onMalformedInput( - CodingErrorAction.REPLACE).onUnmappableCharacter( - CodingErrorAction.REPLACE); - bytes.limit(0); - } - - /** - * Closes this reader. This implementation closes the source InputStream and - * releases all local storage. - * - * @throws IOException - * if an error occurs attempting to close this reader. - */ - @Override - public void close() throws IOException { - synchronized (lock) { - decoder = null; - if (in != null) { - in.close(); - in = null; - } - } - } - - /** - * Returns the name of the encoding used to convert bytes into characters. - * The value {@code null} is returned if this reader has been closed. - * - * @return the name of the character converter or {@code null} if this - * reader is closed. - */ - public String getEncoding() { - if (!isOpen()) { - return null; - } - return encoding; - } - - /** - * Reads a single character from this reader and returns it as an integer - * with the two higher-order bytes set to 0. Returns -1 if the end of the - * reader has been reached. The byte value is either obtained from - * converting bytes in this reader's buffer or by first filling the buffer - * from the source InputStream and then reading from the buffer. - * - * @return the character read or -1 if the end of the reader has been - * reached. - * @throws IOException - * if this reader is closed or some other I/O error occurs. - */ - @Override - public int read() throws IOException { - synchronized (lock) { - if (!isOpen()) { - throw new IOException("InputStreamReader is closed."); - } - - char buf[] = new char[1]; - return read(buf, 0, 1) != -1 ? buf[0] : -1; - } - } - - /** - * Reads at most {@code length} characters from this reader and stores them - * at position {@code offset} in the character array {@code buf}. Returns - * the number of characters actually read or -1 if the end of the reader has - * been reached. The bytes are either obtained from converting bytes in this - * reader's buffer or by first filling the buffer from the source - * InputStream and then reading from the buffer. - * - * @param buf - * the array to store the characters read. - * @param offset - * the initial position in {@code buf} to store the characters - * read from this reader. - * @param length - * the maximum number of characters to read. - * @return the number of characters read or -1 if the end of the reader has - * been reached. - * @throws IndexOutOfBoundsException - * if {@code offset < 0} or {@code length < 0}, or if - * {@code offset + length} is greater than the length of - * {@code buf}. - * @throws IOException - * if this reader is closed or some other I/O error occurs. - */ - @Override - public int read(char[] buf, int offset, int length) throws IOException { - synchronized (lock) { - if (!isOpen()) { - throw new IOException("InputStreamReader is closed."); - } - if (offset < 0 || offset > buf.length - length || length < 0) { - throw new IndexOutOfBoundsException(); - } - if (length == 0) { - return 0; - } - - CharBuffer out = CharBuffer.wrap(buf, offset, length); - CoderResult result = CoderResult.UNDERFLOW; - - // bytes.remaining() indicates number of bytes in buffer - // when 1-st time entered, it'll be equal to zero - boolean needInput = !bytes.hasRemaining(); - - while (out.hasRemaining()) { - // fill the buffer if needed - if (needInput) { - try { - if ((in.available() == 0) - && (out.position() > offset)) { - // we could return the result without blocking read - break; - } - } catch (IOException e) { - // available didn't work so just try the read - } - - int to_read = bytes.capacity() - bytes.limit(); - int off = bytes.arrayOffset() + bytes.limit(); - int was_red = in.read(bytes.array(), off, to_read); - - if (was_red == -1) { - endOfInput = true; - break; - } else if (was_red == 0) { - break; - } - bytes.limit(bytes.limit() + was_red); - needInput = false; - } - - // decode bytes - result = decoder.decode(bytes, out, false); - - if (result.isUnderflow()) { - // compact the buffer if no space left - if (bytes.limit() == bytes.capacity()) { - bytes.compact(); - bytes.limit(bytes.position()); - bytes.position(0); - } - needInput = true; - } else { - break; - } - } - - if (result == CoderResult.UNDERFLOW && endOfInput) { - result = decoder.decode(bytes, out, true); - decoder.flush(out); - decoder.reset(); - } - if (result.isMalformed()) { - throw new MalformedInputException(result.length()); - } else if (result.isUnmappable()) { - throw new UnmappableCharacterException(result.length()); - } - - return out.position() - offset == 0 ? -1 : out.position() - offset; - } - } - - /* - * Answer a boolean indicating whether or not this InputStreamReader is - * open. - */ - private boolean isOpen() { - return in != null; - } - - /** - * Indicates whether this reader is ready to be read without blocking. If - * the result is {@code true}, the next {@code read()} will not block. If - * the result is {@code false} then this reader may or may not block when - * {@code read()} is called. This implementation returns {@code true} if - * there are bytes available in the buffer or the source stream has bytes - * available. - * - * @return {@code true} if the receiver will not block when {@code read()} - * is called, {@code false} if unknown or blocking will occur. - * @throws IOException - * if this reader is closed or some other I/O error occurs. - */ - @Override - public boolean ready() throws IOException { - synchronized (lock) { - if (in == null) { - throw new IOException("InputStreamReader is closed."); - } - try { - return bytes.hasRemaining() || in.available() > 0; - } catch (IOException e) { - return false; - } - } - } -} \ No newline at end of file diff --git a/src/main/java/org/jboss/jreadline/console/reader/ConsoleInputSession.java b/src/main/java/org/jboss/jreadline/console/reader/ConsoleInputSession.java new file mode 100644 index 000000000..f4002e695 --- /dev/null +++ b/src/main/java/org/jboss/jreadline/console/reader/ConsoleInputSession.java @@ -0,0 +1,142 @@ +/* + * 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.console.reader; + +import java.io.IOException; +import java.io.InputStream; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.TimeUnit; + +/** + * + * @author Ståle W. Pedersen <[email protected]> + * @author Mike Brock + */ +public class ConsoleInputSession { + private InputStream consoleStream; + private InputStream externalInputStream; + + private ArrayBlockingQueue<String> blockingQueue = new ArrayBlockingQueue<String>(1000); + + private volatile boolean connected; + + public ConsoleInputSession(InputStream consoleStream) + { + this.consoleStream = consoleStream; + this.connected = true; + + this.externalInputStream = new InputStream() + { + private String b; + private int c; + + @Override + public int read() throws IOException + { + try + { + if (b == null || c == b.length()) + { + b = blockingQueue.poll(365, TimeUnit.DAYS); + c = 0; + } + + if (b != null && !b.isEmpty()) + { + return b.charAt(c++); + } + } + catch (InterruptedException e) + { + // + } + return -1; + } + + @Override + public int available() { + if(b != null) + return b.length(); + else + return 0; + } + + @Override + public void close() throws IOException { + stop(); + } + }; + + startReader(); + } + + private void startReader() + { + Thread readerThread = new Thread() + { + @Override + public void run() + { + while (connected) + { + try + { + byte[] bBuf = new byte[20]; + int read = consoleStream.read(bBuf); + + if (read > 0) + { + blockingQueue.put(new String(bBuf, 0, read)); + } + + Thread.sleep(10); + } + catch (IOException e) + { + if (connected) + { + connected = false; + throw new RuntimeException("broken pipe"); + } + } + catch (InterruptedException e) + { + // + } + } + } + }; + + readerThread.start(); + } + + public void interruptPipe() + { + blockingQueue.offer("\n"); + } + + public void stop() + { + connected = false; + blockingQueue.offer(""); + } + + public InputStream getExternalInputStream() + { + return externalInputStream; + } +} diff --git a/src/main/java/org/jboss/jreadline/console/settings/Settings.java b/src/main/java/org/jboss/jreadline/console/settings/Settings.java index 3e528e1a4..4d573861b 100644 --- a/src/main/java/org/jboss/jreadline/console/settings/Settings.java +++ b/src/main/java/org/jboss/jreadline/console/settings/Settings.java @@ -17,6 +17,7 @@ package org.jboss.jreadline.console.settings; import org.jboss.jreadline.console.Config; +import org.jboss.jreadline.console.reader.ConsoleInputSession; import org.jboss.jreadline.edit.*; import org.jboss.jreadline.terminal.POSIXTerminal; import org.jboss.jreadline.terminal.Terminal; @@ -46,6 +47,7 @@ public class Settings { private boolean isLogging = true; private String logFile; private boolean disableCompletion = false; + private boolean readAhead = true; private static final Settings INSTANCE = new Settings(); @@ -72,8 +74,8 @@ public void resetToDefaults() { disableCompletion = false; } /** - * Either EMACS or VI mode. - * EMACS is default if not set + * Either Emacs or Vi mode. + * Emacs is default if not set * * @return editing mode */ @@ -175,15 +177,15 @@ public void setAnsiConsole(boolean ansiConsole) { } /** - * If not set, FileDescriptor.in will be used + * If not set, System.in will be used * * @return input */ public InputStream getInputStream() { - if(inputStream == null) - return new FileInputStream(FileDescriptor.in); - else - return inputStream; + if(inputStream == null) { + inputStream = new ConsoleInputSession(System.in).getExternalInputStream(); + } + return inputStream; } /** @@ -372,4 +374,26 @@ public boolean isHistoryPersistent() { public void setHistoryPersistent(boolean historyPersistent) { this.historyPersistent = historyPersistent; } + + /** + * Read all bytes on buffer if its available + * Set to true by default + * WARNING: Do not set this to false if unsure + * + * @return readAhead + */ + public boolean isReadAhead() { + return readAhead; + } + + /** + * Read all bytes on buffer if its available + * Set to true by default + * WARNING: Do not set this to false if unsure + * + * @param readAhead read + */ + public void setReadAhead(boolean readAhead) { + this.readAhead = readAhead; + } } diff --git a/src/main/java/org/jboss/jreadline/edit/EditMode.java b/src/main/java/org/jboss/jreadline/edit/EditMode.java index d7d217c4a..1720f94e9 100644 --- a/src/main/java/org/jboss/jreadline/edit/EditMode.java +++ b/src/main/java/org/jboss/jreadline/edit/EditMode.java @@ -25,7 +25,7 @@ */ public interface EditMode { - Operation parseInput(int input); + Operation parseInput(int[] input); Action getCurrentAction(); diff --git a/src/main/java/org/jboss/jreadline/edit/EmacsEditMode.java b/src/main/java/org/jboss/jreadline/edit/EmacsEditMode.java index 2baba6e30..1daf6f905 100644 --- a/src/main/java/org/jboss/jreadline/edit/EmacsEditMode.java +++ b/src/main/java/org/jboss/jreadline/edit/EmacsEditMode.java @@ -16,6 +16,7 @@ */ package org.jboss.jreadline.edit; +import org.jboss.jreadline.console.Config; import org.jboss.jreadline.edit.actions.Action; import org.jboss.jreadline.edit.actions.Operation; @@ -43,20 +44,33 @@ public EmacsEditMode(List<KeyOperation> operations) { } @Override - public Operation parseInput(int input) { - //if we're in the middle of parsing a sequence input - if(operationLevel > 0) { - Iterator<KeyOperation> operationIterator = currentOperations.iterator(); - while(operationIterator.hasNext()) - if(input != operationIterator.next().getKeyValues()[operationLevel]) - operationIterator.remove(); + public Operation parseInput(int[] in) { + int input = in[0]; + if(Config.isOSPOSIXCompatible() && in.length > 1) { + KeyOperation ko = KeyOperationManager.findOperation(operations, in); + if(ko != null) { + //clear current operations to make sure that everything works as expected + currentOperations.clear(); + currentOperations.add(ko); + } } - // parse a first sequence input else { - for(KeyOperation ko : operations) - if(input == ko.getFirstValue()) - currentOperations.add(ko); + //if we're in the middle of parsing a sequence input + //currentOperations.add(KeyOperationManager.findOperation(operations, input)); + if(operationLevel > 0) { + Iterator<KeyOperation> operationIterator = currentOperations.iterator(); + while(operationIterator.hasNext()) + if(input != operationIterator.next().getKeyValues()[operationLevel]) + operationIterator.remove(); + + } + // parse a first sequence input + else { + for(KeyOperation ko : operations) + if(input == ko.getFirstValue()) + currentOperations.add(ko); + } } //search mode need special handling @@ -79,6 +93,11 @@ else if(currentOperations.get(0).getOperation() == Operation.DELETE_PREV_CHAR) { currentOperations.clear(); return Operation.SEARCH_DELETE; } + // TODO: unhandled operation, should parse better + else { + currentOperations.clear(); + return Operation.NO_ACTION; + } } //if we got more than one we know that it started with esc else if(currentOperations.size() > 1) { @@ -92,38 +111,41 @@ else if(currentOperations.size() > 1) { return Operation.SEARCH_INPUT; } } // end search mode + else { + // process if we have any hits... + if(currentOperations.isEmpty()) { + //if we've pressed meta-X, where X is not caught we just disable the output + if(operationLevel > 0) { + operationLevel = 0; + currentOperations.clear(); + return Operation.NO_ACTION; + } + else + return Operation.EDIT; + } + else if(currentOperations.size() == 1) { + //need to check if this one operation have more keys + int level = operationLevel+1; + if(in.length > level) + level = in.length; + if(currentOperations.get(0).getKeyValues().length > level) { + operationLevel++; + return Operation.NO_ACTION; + } + Operation currentOperation = currentOperations.get(0).getOperation(); + if(currentOperation == Operation.SEARCH_PREV || + currentOperation == Operation.SEARCH_NEXT_WORD) + mode = Action.SEARCH; - // process if we have any hits... - if(currentOperations.isEmpty()) { - //if we've pressed meta-X, where X is not caught we just disable the output - if(operationLevel > 0) { operationLevel = 0; currentOperations.clear(); - return Operation.NO_ACTION; + + return currentOperation; } - else - return Operation.EDIT; - } - else if(currentOperations.size() == 1) { - //System.out.println("Got Operation: "+matchingOperations.get(0).getOperation()); - //need to check if this one operation have more keys - if(currentOperations.get(0).getKeyValues().length > operationLevel+1) { + else { operationLevel++; return Operation.NO_ACTION; } - Operation currentOperation = currentOperations.get(0).getOperation(); - if(currentOperation == Operation.SEARCH_PREV || - currentOperation == Operation.SEARCH_NEXT_WORD) - mode = Action.SEARCH; - - operationLevel = 0; - currentOperations.clear(); - - return currentOperation; - } - else { - operationLevel++; - return Operation.NO_ACTION; } } diff --git a/src/main/java/org/jboss/jreadline/edit/KeyOperation.java b/src/main/java/org/jboss/jreadline/edit/KeyOperation.java index 0fa251e46..502dafcde 100644 --- a/src/main/java/org/jboss/jreadline/edit/KeyOperation.java +++ b/src/main/java/org/jboss/jreadline/edit/KeyOperation.java @@ -19,6 +19,8 @@ import org.jboss.jreadline.edit.actions.Action; import org.jboss.jreadline.edit.actions.Operation; +import java.util.Arrays; + /** * @author Ståle W. Pedersen <[email protected]> */ @@ -93,5 +95,9 @@ public String toString() { return "Operation: "+operation; } + public boolean equalValues(int[] values) { + return Arrays.equals(keyValues, values); + } + } diff --git a/src/main/java/org/jboss/jreadline/edit/KeyOperationManager.java b/src/main/java/org/jboss/jreadline/edit/KeyOperationManager.java index d21fdb8e7..b3ce73547 100644 --- a/src/main/java/org/jboss/jreadline/edit/KeyOperationManager.java +++ b/src/main/java/org/jboss/jreadline/edit/KeyOperationManager.java @@ -120,6 +120,12 @@ public static List<KeyOperation> generatePOSIXViMode() { List<KeyOperation> keys = generateGenericViMode(); keys.add(new KeyOperation(10, Operation.NEW_LINE)); + //movement + keys.add(new KeyOperation(new int[]{27,91,65}, Operation.HISTORY_PREV, Action.EDIT)); //arrow up + keys.add(new KeyOperation(new int[]{27,91,66}, Operation.HISTORY_NEXT, Action.EDIT)); //arrow down + keys.add(new KeyOperation(new int[]{27,91,67}, Operation.MOVE_NEXT_CHAR, Action.EDIT)); //arrow right + keys.add(new KeyOperation(new int[]{27,91,68}, Operation.MOVE_PREV_CHAR, Action.EDIT)); //arrow left + return keys; } @@ -182,4 +188,13 @@ private static List<KeyOperation> generateGenericViMode() { return keys; } + + public static KeyOperation findOperation(List<KeyOperation> operations, int[] input) { + for(KeyOperation operation : operations) { + if(operation.equalValues(input)) + return operation; + } + return null; + + } } diff --git a/src/main/java/org/jboss/jreadline/edit/ViEditMode.java b/src/main/java/org/jboss/jreadline/edit/ViEditMode.java index e77013024..762330b9d 100644 --- a/src/main/java/org/jboss/jreadline/edit/ViEditMode.java +++ b/src/main/java/org/jboss/jreadline/edit/ViEditMode.java @@ -16,6 +16,7 @@ */ package org.jboss.jreadline.edit; +import org.jboss.jreadline.console.Config; import org.jboss.jreadline.edit.actions.Action; import org.jboss.jreadline.edit.actions.Operation; @@ -81,24 +82,36 @@ private Operation saveAction(Operation action) { } @Override - public Operation parseInput(int c) { - //if we're in the middle of parsing a sequence input - if(operationLevel > 0) { - Iterator<KeyOperation> operationIterator = currentOperations.iterator(); - while(operationIterator.hasNext()) - if(c != operationIterator.next().getKeyValues()[operationLevel]) - operationIterator.remove(); - + public Operation parseInput(int[] in) { + int input = in[0]; + if(Config.isOSPOSIXCompatible() && in.length > 1) { + KeyOperation ko = KeyOperationManager.findOperation(operations, in); + if(ko != null) { + //clear current operations to make sure that everything works as expected + currentOperations.clear(); + currentOperations.add(ko); + } } - // parse a first sequence input else { - for(KeyOperation ko : operations) - if(c == ko.getFirstValue()) - currentOperations.add(ko); + //if we're in the middle of parsing a sequence input + if(operationLevel > 0) { + Iterator<KeyOperation> operationIterator = currentOperations.iterator(); + while(operationIterator.hasNext()) + if(input != operationIterator.next().getKeyValues()[operationLevel]) + operationIterator.remove(); + + } + // parse a first sequence input + else { + for(KeyOperation ko : operations) + if(input == ko.getFirstValue() && ko.getKeyValues().length == in.length) + currentOperations.add(ko); + } } //search mode need special handling - if(mode == Action.SEARCH && currentOperations.size() > 0) { + if(mode == Action.SEARCH) { + if(currentOperations.size() == 1) { if(currentOperations.get(0).getOperation() == Operation.NEW_LINE) { mode = Action.EDIT; currentOperations.clear(); @@ -112,8 +125,20 @@ else if(currentOperations.get(0).getOperation() == Operation.DELETE_PREV_CHAR) { currentOperations.clear(); return Operation.SEARCH_DELETE; } - //if we got more than one we know that it started with esc + //if we got more than one we know that it started with esc else if(currentOperations.get(0).getOperation() == Operation.ESCAPE) { + mode = Action.EDIT; + currentOperations.clear(); + return Operation.SEARCH_EXIT; + } + // search input + else { + currentOperations.clear(); + return Operation.SEARCH_INPUT; + } + } + //if we got more than one we know that it started with esc + else if(currentOperations.size() > 1) { mode = Action.EDIT; currentOperations.clear(); return Operation.SEARCH_EXIT; @@ -125,29 +150,6 @@ else if(currentOperations.get(0).getOperation() == Operation.ESCAPE) { } } // end search mode - //if we're already in search mode - /* - if(mode == Action.SEARCH) { - if(c == ENTER) { - mode = Action.EDIT; - return Operation.SEARCH_END; - } - else if(c == CTRL_R) { - return Operation.SEARCH_PREV_WORD; - } - else if(c == BACKSPACE) { - return Operation.SEARCH_DELETE; - } - else if(c == ESCAPE) { - mode = Action.EDIT; - return Operation.SEARCH_EXIT; - } - // search input - else { - return Operation.SEARCH_INPUT; - } - } - */ if(currentOperations.isEmpty()) { if(isInEditMode()) @@ -192,6 +194,16 @@ else if (operation == Operation.SEARCH_PREV) { } else if(operation == Operation.CLEAR) return Operation.CLEAR; + //make sure that this only works for working more == Action.EDIT + else if(operation == Operation.MOVE_PREV_CHAR && workingMode.equals(Action.EDIT)) + return Operation.MOVE_PREV_CHAR; + else if(operation == Operation.MOVE_NEXT_CHAR && workingMode.equals(Action.EDIT)) + return Operation.MOVE_NEXT_CHAR; + else if(operation == Operation.HISTORY_PREV && workingMode.equals(Action.EDIT)) + return operation; + else if(operation == Operation.HISTORY_NEXT && workingMode.equals(Action.EDIT)) + return operation; + if(!isInEditMode()) return inCommandMode(operation, workingMode); diff --git a/src/main/java/org/jboss/jreadline/terminal/POSIXTerminal.java b/src/main/java/org/jboss/jreadline/terminal/POSIXTerminal.java index 4d17c769e..622367f48 100644 --- a/src/main/java/org/jboss/jreadline/terminal/POSIXTerminal.java +++ b/src/main/java/org/jboss/jreadline/terminal/POSIXTerminal.java @@ -16,10 +16,10 @@ */ package org.jboss.jreadline.terminal; - -import org.jboss.jreadline.console.reader.CharInputStreamReader; +import org.jboss.jreadline.util.LoggerUtil; import java.io.*; +import java.util.logging.Logger; /** * Terminal that should work on most POSIX systems @@ -36,8 +36,10 @@ public class POSIXTerminal implements Terminal { private long ttyPropsLastFetched; private boolean restored = false; - private CharInputStreamReader reader; + private InputStream input; private Writer writer; + + private static final Logger logger = LoggerUtil.getLogger(POSIXTerminal.class.getName()); @Override public void init(InputStream inputStream, OutputStream outputStream) { @@ -59,8 +61,8 @@ public void init(InputStream inputStream, OutputStream outputStream) { stty("-echo"); echoEnabled = false; - //setting up reader - reader = new CharInputStreamReader(inputStream); + //setting up input + input = inputStream; } catch (IOException ioe) { System.err.println("TTY failed with: " + ioe.getMessage()); @@ -88,8 +90,19 @@ public void start() { * @see org.jboss.jreadline.terminal.Terminal */ @Override - public int read() throws IOException { - return reader.read(); + public int[] read(boolean readAhead) throws IOException { + int input = this.input.read(); + int available = this.input.available(); + if(available > 1 && readAhead) { + int[] in = new int[available]; + in[0] = input; + for(int c=1; c < available; c++ ) + in[c] = this.input.read(); + + return in; + } + else + return new int[] {input}; } /** @@ -132,7 +145,9 @@ public int getHeight() { try { height = getTerminalProperty("rows"); } - catch (Exception e) { /*ignored */ } + catch (Exception e) { + logger.severe("Failed to fetch terminal height: "+e.getMessage()); + } if(height < 0) height = 24; } @@ -149,7 +164,9 @@ public int getWidth() { try { width = getTerminalProperty("columns"); } - catch (Exception e) { /* ignored */ } + catch (Exception e) { + logger.severe("Failed to fetch terminal width: "+e.getMessage()); + } if(width < 0) width = 80; @@ -168,12 +185,18 @@ public boolean isEchoEnabled() { /** * @see org.jboss.jreadline.terminal.Terminal */ - public void reset() throws Exception { + @Override + public void reset() throws IOException { if(!restored) { if (ttyConfig != null) { - stty(ttyConfig); - ttyConfig = null; - restored = true; + try { + stty(ttyConfig); + ttyConfig = null; + restored = true; + } + catch (InterruptedException e) { + logger.severe("Failed to reset terminal: "+e.getMessage()); + } } } } @@ -275,7 +298,7 @@ private static String exec(final String[] cmd) throws IOException, InterruptedEx out.close(); } catch (Exception e) { - e.printStackTrace(); + logger.warning("Failed to close streams"); } } diff --git a/src/main/java/org/jboss/jreadline/terminal/Terminal.java b/src/main/java/org/jboss/jreadline/terminal/Terminal.java index 71a527830..ad15ba02c 100644 --- a/src/main/java/org/jboss/jreadline/terminal/Terminal.java +++ b/src/main/java/org/jboss/jreadline/terminal/Terminal.java @@ -41,7 +41,7 @@ public interface Terminal { * @return whats read * @throws IOException */ - int read() throws IOException; + int[] read(boolean readAhead) throws IOException; /** * Write to the output stream @@ -81,9 +81,10 @@ public interface Terminal { /** * Set it back to normal when we exit - * @throws Exception stream/os + * + * @throws java.io.IOException stream */ - void reset() throws Exception; + void reset() throws IOException; } diff --git a/src/main/java/org/jboss/jreadline/terminal/WindowsTerminal.java b/src/main/java/org/jboss/jreadline/terminal/WindowsTerminal.java index 3c3f3177e..cf574ec88 100644 --- a/src/main/java/org/jboss/jreadline/terminal/WindowsTerminal.java +++ b/src/main/java/org/jboss/jreadline/terminal/WindowsTerminal.java @@ -28,7 +28,6 @@ */ public class WindowsTerminal implements Terminal { - //private CharInputStreamReader reader; private Writer writer; @Override @@ -38,7 +37,6 @@ public void init(InputStream inputStream, OutputStream outputStream) { } //setting up reader - //reader = new CharInputStreamReader(inputStream); try { //AnsiConsole.systemInstall(); writer = new PrintWriter( new OutputStreamWriter(new WindowsAnsiOutputStream(outputStream))); @@ -46,12 +44,12 @@ public void init(InputStream inputStream, OutputStream outputStream) { catch (Exception ioe) { writer = new PrintWriter( new OutputStreamWriter(new AnsiOutputStream(outputStream))); } - } - public int read() throws IOException { + @Override + public int[] read(boolean readAhead) throws IOException { //return reader.read(); - return WindowsSupport.readByte(); + return new int[] {WindowsSupport.readByte()}; } @Override @@ -76,20 +74,23 @@ public void write(char out) throws IOException { writer.flush(); } + @Override public int getHeight() { return WindowsSupport.getWindowsTerminalHeight(); } + @Override public int getWidth() { return WindowsSupport.getWindowsTerminalWidth(); } + @Override public boolean isEchoEnabled() { return false; } - public void reset() throws Exception { - + @Override + public void reset() throws IOException { } } diff --git a/src/test/java/org/jboss/jreadline/JReadlineTestCase.java b/src/test/java/org/jboss/jreadline/JReadlineTestCase.java index ea9ff0556..cd4857e47 100644 --- a/src/test/java/org/jboss/jreadline/JReadlineTestCase.java +++ b/src/test/java/org/jboss/jreadline/JReadlineTestCase.java @@ -39,6 +39,7 @@ public void assertEquals(String expected, TestBuffer buffer) throws IOException settings.setInputStream(new ByteArrayInputStream(buffer.getBytes())); settings.setOutputStream(new ByteArrayOutputStream()); settings.setEditMode(Mode.EMACS); + settings.setReadAhead(false); Console console = new Console(settings); @@ -65,6 +66,7 @@ public void assertEqualsViMode(String expected, TestBuffer buffer) throws IOExce settings.setReadInputrc(false); settings.setInputStream(new ByteArrayInputStream(buffer.getBytes())); settings.setOutputStream(new ByteArrayOutputStream()); + settings.setReadAhead(false); settings.setEditMode(Mode.VI); Console console = new Console(settings); diff --git a/src/test/java/org/jboss/jreadline/console/BufferTest.java b/src/test/java/org/jboss/jreadline/console/BufferTest.java index 91e39f856..875423e59 100644 --- a/src/test/java/org/jboss/jreadline/console/BufferTest.java +++ b/src/test/java/org/jboss/jreadline/console/BufferTest.java @@ -80,6 +80,18 @@ public void testMove() { expected = new char[] {(char) 27,'[','7','C'}; assertEquals(new String(expected), new String(out)); assertEquals(7, buffer.getCursor()); + + buffer.reset(">"); + buffer.write("foo"); + buffer.move(-4, 80, true); + + assertEquals(2, buffer.getCursorWithPrompt()); + + buffer.move(5, 80, true); + assertEquals(4, buffer.getCursorWithPrompt()); + + buffer.move(-4, 80, true); + assertEquals(2, buffer.getCursorWithPrompt()); } public void testPrintAnsi() {
d698699901d72f73212e302ad715c97a4c4fc10e
tapiji
Adapts the namespace of all TapiJI plug-ins to org.eclipselabs.tapiji.*.
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 0ea76ea6..bd239651 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/plugin.xml +++ b/com.essiembre.eclipse.i18n.resourcebundle/plugin.xml @@ -26,7 +26,7 @@ <import plugin="org.eclipse.jdt.ui" optional="true"/> <import plugin="org.eclipse.ui.views"/> <import plugin="org.eclipse.jdt.core" version="3.5.2"/> - <import plugin="at.ac.tuwien.inso.eclipse.rbe" version="0.0.1"/> + <import plugin="org.eclipselabs.tapiji.translator.rbe" version="0.0.1"/> </requires> <extension-point id="resourceFactory" name="resourceFactory" schema="schema/resourceFactory.exsd"/> diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/AnalyzerFactory.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/AnalyzerFactory.java index a5fe31d5..4f2c1b24 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/AnalyzerFactory.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/AnalyzerFactory.java @@ -20,7 +20,7 @@ */ package com.essiembre.eclipse.rbe.api; -import at.ac.tuwien.inso.eclipse.rbe.model.analyze.ILevenshteinDistanceAnalyzer; +import org.eclipselabs.tapiji.translator.rbe.model.analyze.ILevenshteinDistanceAnalyzer; import com.essiembre.eclipse.rbe.model.utils.LevenshteinDistanceAnalyzer; diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/BundleFactory.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/BundleFactory.java index edfe0560..c5e90c47 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/BundleFactory.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/BundleFactory.java @@ -20,11 +20,12 @@ */ package com.essiembre.eclipse.rbe.api; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleEntry; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup; + import com.essiembre.eclipse.rbe.model.bundle.BundleEntry; import com.essiembre.eclipse.rbe.model.bundle.BundleGroup; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleEntry; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup; public class BundleFactory { diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/EditorUtil.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/EditorUtil.java index 9b20cdd8..b2acc777 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/EditorUtil.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/EditorUtil.java @@ -3,8 +3,7 @@ import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IWorkbenchPage; - -import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTreeItem; +import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTreeItem; import com.essiembre.eclipse.rbe.ui.editor.ResourceBundleEditor; import com.essiembre.eclipse.rbe.ui.editor.i18n.I18nPage; diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/KeyTreeFactory.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/KeyTreeFactory.java index 94c1e361..4677e0d5 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/KeyTreeFactory.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/KeyTreeFactory.java @@ -20,9 +20,9 @@ */ package com.essiembre.eclipse.rbe.api; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTree; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.updater.IKeyTreeUpdater; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup; +import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTree; +import org.eclipselabs.tapiji.translator.rbe.model.tree.updater.IKeyTreeUpdater; import com.essiembre.eclipse.rbe.model.tree.KeyTree; import com.essiembre.eclipse.rbe.model.tree.updater.FlatKeyTreeUpdater; diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/PropertiesGenerator.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/PropertiesGenerator.java index fd540203..ab7c09a9 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/PropertiesGenerator.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/PropertiesGenerator.java @@ -22,8 +22,8 @@ import java.util.Iterator; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundle; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleEntry; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundle; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleEntry; import com.essiembre.eclipse.rbe.model.workbench.RBEPreferences; diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/PropertiesParser.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/PropertiesParser.java index 9d25446d..bd87acfa 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/PropertiesParser.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/PropertiesParser.java @@ -20,7 +20,7 @@ */ package com.essiembre.eclipse.rbe.api; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundle; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundle; import com.essiembre.eclipse.rbe.RBEPlugin; import com.essiembre.eclipse.rbe.model.bundle.Bundle; diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/ValuedKeyTreeItem.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/ValuedKeyTreeItem.java index 98a9e97b..d2099e36 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/ValuedKeyTreeItem.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/api/ValuedKeyTreeItem.java @@ -27,11 +27,10 @@ import java.util.Locale; import java.util.Map; -import com.essiembre.eclipse.rbe.model.tree.KeyTreeItem; - +import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTree; +import org.eclipselabs.tapiji.translator.rbe.model.tree.IValuedKeyTreeItem; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTree; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.IValuedKeyTreeItem; +import com.essiembre.eclipse.rbe.model.tree.KeyTreeItem; public class ValuedKeyTreeItem extends KeyTreeItem implements IValuedKeyTreeItem { diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/Bundle.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/Bundle.java index 6bb8c8f0..5d866dd3 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/Bundle.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/Bundle.java @@ -27,12 +27,11 @@ import java.util.Locale; import java.util.Map; import java.util.Set; -import java.util.SortedSet; import java.util.TreeSet; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundle; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleEntry; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundle; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleEntry; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup; import com.essiembre.eclipse.rbe.model.Model; diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/BundleEntry.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/BundleEntry.java index cf014bab..7dae3c70 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/BundleEntry.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/BundleEntry.java @@ -22,8 +22,8 @@ import java.util.Locale; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundle; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleEntry; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundle; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleEntry; /** * Represents an entry in a properties file. diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/BundleGroup.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/BundleGroup.java index b9097dd1..4b958f06 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/BundleGroup.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/BundleGroup.java @@ -30,9 +30,9 @@ import java.util.SortedSet; import java.util.TreeSet; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundle; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleEntry; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundle; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleEntry; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup; import com.essiembre.eclipse.rbe.model.Model; diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/BundleVisitorAdapter.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/BundleVisitorAdapter.java index 82983e1f..22fc6a3b 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/BundleVisitorAdapter.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/BundleVisitorAdapter.java @@ -20,9 +20,9 @@ */ package com.essiembre.eclipse.rbe.model.bundle; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundle; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleEntry; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundle; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleEntry; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup; /** * Convenience implementation of <code>IBundleVisitor</code> allowing to diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/IBundleVisitor.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/IBundleVisitor.java index c6407447..57454b47 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/IBundleVisitor.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/bundle/IBundleVisitor.java @@ -20,9 +20,9 @@ */ package com.essiembre.eclipse.rbe.model.bundle; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundle; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleEntry; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundle; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleEntry; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup; /** * Objects implementing this interface can act as a visitor to any diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/IKeyTreeVisitor.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/IKeyTreeVisitor.java index 321e3d7b..06140840 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/IKeyTreeVisitor.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/IKeyTreeVisitor.java @@ -20,8 +20,8 @@ */ package com.essiembre.eclipse.rbe.model.tree; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTree; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTreeItem; +import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTree; +import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTreeItem; /** * Objects implementing this interface can act as a visitor to any diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/KeyTree.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/KeyTree.java index 3a7929c3..b098c7ed 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/KeyTree.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/KeyTree.java @@ -28,10 +28,9 @@ import java.util.TreeSet; import org.eclipse.jface.viewers.ViewerFilter; - -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTree; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.updater.IKeyTreeUpdater; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup; +import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTree; +import org.eclipselabs.tapiji.translator.rbe.model.tree.updater.IKeyTreeUpdater; import com.essiembre.eclipse.rbe.model.DeltaEvent; import com.essiembre.eclipse.rbe.model.IDeltaListener; diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/KeyTreeItem.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/KeyTreeItem.java index 112c419e..dd924522 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/KeyTreeItem.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/KeyTreeItem.java @@ -24,8 +24,8 @@ import java.util.SortedSet; import java.util.TreeSet; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTree; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTreeItem; +import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTree; +import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTreeItem; /** * Leaf (tree) representation of one or several resource bundle entries sharing diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/KeyTreeVisitorAdapter.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/KeyTreeVisitorAdapter.java index 94939393..42fe4858 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/KeyTreeVisitorAdapter.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/KeyTreeVisitorAdapter.java @@ -20,8 +20,8 @@ */ package com.essiembre.eclipse.rbe.model.tree; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTree; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTreeItem; +import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTree; +import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTreeItem; /** * Convenience implementation of <code>IKeyTreeVisitor</code> allowing diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/updater/FlatKeyTreeUpdater.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/updater/FlatKeyTreeUpdater.java index 745f6953..85c05948 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/updater/FlatKeyTreeUpdater.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/updater/FlatKeyTreeUpdater.java @@ -22,7 +22,7 @@ import java.util.Map; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTree; +import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTree; import com.essiembre.eclipse.rbe.model.tree.KeyTreeItem; diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/updater/GroupedKeyTreeUpdater.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/updater/GroupedKeyTreeUpdater.java index e86e3cf1..89a402c9 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/updater/GroupedKeyTreeUpdater.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/updater/GroupedKeyTreeUpdater.java @@ -23,7 +23,7 @@ import java.util.Map; import java.util.StringTokenizer; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTree; +import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTree; import com.essiembre.eclipse.rbe.model.tree.KeyTree; import com.essiembre.eclipse.rbe.model.tree.KeyTreeItem; diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/updater/IncompletionUpdater.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/updater/IncompletionUpdater.java index 1290142e..b0366140 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/updater/IncompletionUpdater.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/updater/IncompletionUpdater.java @@ -24,8 +24,8 @@ import java.util.Collection; import java.util.Iterator; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTree; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup; +import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTree; import com.essiembre.eclipse.rbe.model.bundle.BundleEntry; diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/updater/KeyTreeUpdater.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/updater/KeyTreeUpdater.java index 6410a305..37aff57c 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/updater/KeyTreeUpdater.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/updater/KeyTreeUpdater.java @@ -22,8 +22,8 @@ import java.util.Map; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTree; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.updater.IKeyTreeUpdater; +import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTree; +import org.eclipselabs.tapiji.translator.rbe.model.tree.updater.IKeyTreeUpdater; import com.essiembre.eclipse.rbe.model.tree.KeyTree; import com.essiembre.eclipse.rbe.model.tree.KeyTreeItem; diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/visitors/IsCommentedVisitor.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/visitors/IsCommentedVisitor.java index 1cba5fc0..ce877b35 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/visitors/IsCommentedVisitor.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/visitors/IsCommentedVisitor.java @@ -23,7 +23,7 @@ import java.util.Collection; import java.util.Iterator; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup; import com.essiembre.eclipse.rbe.model.bundle.BundleEntry; import com.essiembre.eclipse.rbe.model.tree.KeyTreeItem; diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/visitors/IsMissingValueVisitor.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/visitors/IsMissingValueVisitor.java index a1b5dc21..0fff4599 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/visitors/IsMissingValueVisitor.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/tree/visitors/IsMissingValueVisitor.java @@ -23,7 +23,7 @@ import java.util.Collection; import java.util.Iterator; -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup; import com.essiembre.eclipse.rbe.model.bundle.BundleEntry; import com.essiembre.eclipse.rbe.model.tree.KeyTreeItem; diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/utils/LevenshteinDistanceAnalyzer.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/utils/LevenshteinDistanceAnalyzer.java index 4643c774..9af3023c 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/utils/LevenshteinDistanceAnalyzer.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/model/utils/LevenshteinDistanceAnalyzer.java @@ -20,7 +20,7 @@ */ package com.essiembre.eclipse.rbe.model.utils; -import at.ac.tuwien.inso.eclipse.rbe.model.analyze.ILevenshteinDistanceAnalyzer; +import org.eclipselabs.tapiji.translator.rbe.model.analyze.ILevenshteinDistanceAnalyzer; /** diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/editor/ResourceBundleEditor.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/editor/ResourceBundleEditor.java index ed097a12..6841e156 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/editor/ResourceBundleEditor.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/editor/ResourceBundleEditor.java @@ -49,8 +49,7 @@ import org.eclipse.ui.ide.IGotoMarker; import org.eclipse.ui.part.MultiPageEditorPart; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; - -import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTree; +import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTree; import com.essiembre.eclipse.rbe.RBEPlugin; import com.essiembre.eclipse.rbe.model.tree.KeyTree; diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/editor/i18n/tree/KeyTreeComposite.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/editor/i18n/tree/KeyTreeComposite.java index d898dc5f..e83d8452 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/editor/i18n/tree/KeyTreeComposite.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/editor/i18n/tree/KeyTreeComposite.java @@ -48,8 +48,7 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Text; - -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup; import com.essiembre.eclipse.rbe.RBEPlugin; import com.essiembre.eclipse.rbe.model.tree.KeyTree; diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/editor/i18n/tree/KeyTreeLabelProvider.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/editor/i18n/tree/KeyTreeLabelProvider.java index 2d6530a0..c7247569 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/editor/i18n/tree/KeyTreeLabelProvider.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/editor/i18n/tree/KeyTreeLabelProvider.java @@ -29,7 +29,7 @@ import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; -import at.ac.tuwien.inso.eclipse.rbe.model.tree.IKeyTreeItem; +import org.eclipselabs.tapiji.translator.rbe.model.tree.IKeyTreeItem; import com.essiembre.eclipse.rbe.RBEPlugin; import com.essiembre.eclipse.rbe.model.tree.KeyTreeItem; diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/editor/i18n/tree/TreeViewerContributor.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/editor/i18n/tree/TreeViewerContributor.java index 62018100..fc33f1bb 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/editor/i18n/tree/TreeViewerContributor.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/editor/i18n/tree/TreeViewerContributor.java @@ -1,4 +1,5 @@ /* + * Copyright (C) 2003, 2004 Pascal Essiembre, Essiembre Consultant Inc. * * This file is part of Essiembre ResourceBundle Editor. @@ -39,8 +40,7 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; - -import at.ac.tuwien.inso.eclipse.rbe.model.bundle.IBundleGroup; +import org.eclipselabs.tapiji.translator.rbe.model.bundle.IBundleGroup; import com.essiembre.eclipse.rbe.RBEPlugin; import com.essiembre.eclipse.rbe.model.tree.KeyTree; diff --git a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/wizards/ResourceBundleWizard.java b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/wizards/ResourceBundleWizard.java index 320eb545..623ff380 100644 --- a/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/wizards/ResourceBundleWizard.java +++ b/com.essiembre.eclipse.i18n.resourcebundle/src/com/essiembre/eclipse/rbe/ui/wizards/ResourceBundleWizard.java @@ -47,8 +47,7 @@ import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.ide.IDE; - -import at.ac.tuwien.inso.eclipse.rbe.ui.wizards.IResourceBundleWizard; +import org.eclipselabs.tapiji.translator.rbe.ui.wizards.IResourceBundleWizard; import com.essiembre.eclipse.rbe.RBEPlugin; import com.essiembre.eclipse.rbe.api.PropertiesGenerator;
1fe1191dcc823281c2e2f857c24f3ee5c610b206
Delta Spike
DELTASPIKE-289 add sample ClientWindowConfig
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/examples/jsf-examples/src/main/java/org/apache/deltaspike/example/window/SampleClientWindowConfig.java b/deltaspike/examples/jsf-examples/src/main/java/org/apache/deltaspike/example/window/SampleClientWindowConfig.java new file mode 100644 index 000000000..69f573ccf --- /dev/null +++ b/deltaspike/examples/jsf-examples/src/main/java/org/apache/deltaspike/example/window/SampleClientWindowConfig.java @@ -0,0 +1,37 @@ +/* + * 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.example.window; + +import javax.enterprise.inject.Specializes; +import javax.faces.context.FacesContext; + +import org.apache.deltaspike.jsf.spi.scope.window.DefaultClientWindowConfig; + +/** + * A sample ClientWindowConfig + */ +@Specializes +public class SampleClientWindowConfig extends DefaultClientWindowConfig +{ + @Override + public ClientWindowRenderMode getClientWindowRenderMode(FacesContext facesContext) + { + return ClientWindowRenderMode.CLIENTWINDOW; + } +}